Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
653 changes: 653 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,12 @@ Prices are in the smallest currency unit (e.g. pence, cents). For multi-listing
- Public key encrypts on submission (no auth needed)
- Private key only available to authenticated admin sessions
- A database dump alone is not sufficient to recover PII - an attacker would also need the encryption key from the environment
- **AES-256-GCM** for payment IDs, prices, check-in status, API keys, holiday names, usernames
- **AES-256-GCM** for payment references, API credentials, and selected configuration fields
- **PBKDF2** (600k iterations, SHA-256) for password hashing
- Three-layer key hierarchy: env var root key → RSA key pair → per-user wrapped data keys
- The data key is wrapped with a key derived from the admin password (never stored), so a database dump plus the environment key still can't decrypt PII without a login
- Activity log entries are encrypted with the owner's public key: unauthenticated code (webhooks, error handlers) can write them, but only a logged-in admin can read them
- If you lose the password, the data is permanently unreadable - there is no backdoor
- If no other keyed role (owner, manager, or agent) or recovery owner exists, losing the last keyed password makes the protected data unreadable
Comment thread
stefan-burke marked this conversation as resolved.
Resolved

### Concurrency

Expand Down Expand Up @@ -418,11 +418,11 @@ See the [CONFIG_KEYS reference](https://chobbledotcom.github.io/tickets/doc.ts/~

- **Runtime**: Deno - runs standalone, via Docker, or on Bunny Edge Scripting
- **Database**: libsql (local SQLite or remote Turso)
- **Payments**: Stripe, Square
- **Payments**: Stripe, Square, SumUp
- **Build**: esbuild, single-file output
- **Templates**: Server-rendered JSX
- **Crypto**: Web Crypto API (AES-256-GCM, RSA-OAEP, PBKDF2)

## License

AGPLv3 - developed by [Chobble CIC](https://chobble.com), a community interest company.
AGPL-3.0-only - developed by [Chobble CIC](https://chobble.com), a community interest company.
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
34 changes: 34 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,40 @@ out of scope for that PR's brief — recorded here for a follow-up.*
a deliberate test review, which is the only way the test catches the failure
mode it is meant to catch.

---

## Scheduled finalize for SumUp payments without a webhook or redirect

*Origin: follow-up to the SumUp provider work, surfaced 2026-07-25 while
documenting SumUp in `README.md` / `src/docs/payments.ts` (PR #1918).*

SumUp does not sign its webhooks (`requiresWebhookSignature: false` in
`src/shared/sumup-provider.ts`). Today a SumUp checkout is finalized through
two paths: the `CHECKOUT_STATUS_CHANGED` webhook (unsigned, but
`resolveWebhookSession` pre-filters against staged checkout rows in
`src/shared/db/sumup-checkouts.ts` and re-fetches the checkout from SumUp to
establish authenticity and paid status) and the redirect return, which calls
`retrieveSession`. If both are lost — the webhook delivery never arrives and
the customer never returns to the redirect URL — a paid checkout stays in the
`pending` / `unpaid` state indefinitely until manual intervention.

Add a scheduled task that polls outstanding staged SumUp checkouts whose
status is not yet terminal and finalizes any the SumUp API reports as `PAID`
through the same `validatePaidSession` → `processPaymentSession` path the
redirect return uses. The shared processor owns reservation, conflict handling,
booking, refund, and replay behavior, so the scheduled task must not call
`completePaidBooking` directly. In lieu of a trustworthy webhook, this
scheduled poll is the reliable fallback. It should reuse the existing
scheduled-task mechanism (`src/shared/site-scheduler.ts`,
`src/shared/maintenance/runner.ts`) and stay within the per-request edge
subrequest budget, so bound each run to a page of staged checkouts and let the
next tick continue. Cover it with a regression test that stages a
paid-but-unfinalized checkout, runs the poll, and proves the attendee/ledger
rows are created exactly once across concurrent webhook, redirect, and
scheduled-poll attempts.

---

## Stale equivalent-mutant line numbers across recent refactors

*Origin: running `deno task mutation:audit-equivalents` while hardening
Expand Down
8 changes: 3 additions & 5 deletions scripts/lock-file.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/** Open (creating if needed) a file to hold an advisory lock. Shared by the
* mutation-run isolation lock and the stripe-mock install lock. */
/** Open (creating if needed) a file to hold an advisory lock. */
export const openLockFile = (path: string): Promise<Deno.FsFile> =>
Deno.open(path, { create: true, read: true, write: true });

/** Hold an exclusive advisory lock on the file at `path` while `body` runs,
* then release and close it no matter how `body` ends. The one "lock a file,
* run something, unlock" dance the stripe-mock start and install locks share. */
* then release and close it no matter how `body` ends. */
export const withFileLock = async <T>(
path: string,
body: () => Promise<T>,
Expand All @@ -16,7 +14,7 @@ export const withFileLock = async <T>(
try {
return await body();
} finally {
file.unlock();
await file.unlock();
}
} finally {
file.close();
Expand Down
22 changes: 22 additions & 0 deletions scripts/precommit/lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
* Cross-worktree precommit lock.
*
* The file is only a stable rendezvous point. Ownership lives in the kernel's
* advisory lock and is tied to the open file handle, so process exit releases
* it automatically. There is no PID, stale state, or takeover race to repair.
*/
import { tmpdir } from "node:os";
import { join } from "node:path";
import { withFileLock } from "#scripts/lock-file.ts";

/** One project-wide path shared by every checkout and worktree. */
export const PRECOMMIT_LOCK_PATH = join(
tmpdir(),
"chobble-tickets-precommit.lock",
);
Comment thread
stefan-burke marked this conversation as resolved.
Resolved

/** Run `task` while this process owns the project-wide precommit lock. */
export const withPrecommitLock = <T>(
task: () => Promise<T>,
lockPath: string = PRECOMMIT_LOCK_PATH,
): Promise<T> => withFileLock(lockPath, task);
14 changes: 14 additions & 0 deletions scripts/precommit/run-order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Run the heavy checks under the cross-worktree lock, then release it before
* the optional push prompt. CI jobs are already isolated and skip the lock.
*/
export const runChecksBeforePush = async (
ci: boolean,
checks: () => Promise<void>,
push: () => Promise<void>,
lock: (task: () => Promise<void>) => Promise<void>,
): Promise<void> => {
if (ci) await checks();
else await lock(checks);
await push();
};
35 changes: 29 additions & 6 deletions scripts/precommit/runner.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { readStream } from "#scripts/stream-lines.ts";
import { resolveDenoJobs } from "#scripts/workers.ts";
import { bold, dim, green, red, yellow } from "./colors.ts";
import { runCommand, runInteractiveCommand, splitCommand } from "./git.ts";
import { withPrecommitLock } from "./lock.ts";
import { getMergeConflictWarning } from "./merge-warning.ts";
import { promptToPushCheckedInChanges, shouldPushFromAnswer } from "./push.ts";
import { runChecksBeforePush } from "./run-order.ts";
import { getSteps, type Step } from "./steps.ts";
import {
canPrompt,
Expand Down Expand Up @@ -90,12 +93,7 @@ const runStep = async (step: Step): Promise<boolean> => {
return success;
};

export const main = async (): Promise<void> => {
const ci = isCi();
if (ci && !Deno.env.get("CI")) Deno.env.set("CI", "1");
console.log(bold(ci ? "precommit (ci)" : "precommit"));
await warnAboutMergeConflicts();

const runSteps = async (): Promise<void> => {
const steps = getSteps();
for (const step of steps) {
const passed = await runStep(step);
Expand All @@ -106,6 +104,9 @@ export const main = async (): Promise<void> => {
}

console.log(`\n${green("precommit passed")}`);
};

const pushCheckedInChanges = async (): Promise<void> => {
const pushSucceeded = await promptToPushCheckedInChanges({
confirm: confirmPush,
isInteractive: canPromptNow,
Expand All @@ -117,3 +118,25 @@ export const main = async (): Promise<void> => {
Deno.exit(1);
}
};

export const main = async (): Promise<void> => {
const ci = isCi();
if (ci && !Deno.env.get("CI")) Deno.env.set("CI", "1");
// Cap test parallelism for the run. CI uses every thread; a local git hook
// uses (threads / 2) - 1 so the editor and foreground work keep headroom.
// An explicit DENO_JOBS always wins — only set a default when unset.
const jobs = resolveDenoJobs(
navigator.hardwareConcurrency,
ci,
Deno.env.get("DENO_JOBS"),
);
if (jobs !== undefined) Deno.env.set("DENO_JOBS", String(jobs));
console.log(bold(ci ? "precommit (ci)" : "precommit"));
await warnAboutMergeConflicts();
await runChecksBeforePush(
ci,
runSteps,
pushCheckedInChanges,
withPrecommitLock,
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
);
};
30 changes: 30 additions & 0 deletions scripts/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,33 @@ export const parseWorkerCount = (
const jobs = Number(value);
return Number.isInteger(jobs) && jobs > 0 ? jobs : fallback;
};

/**
* Test worker count for a precommit run. In CI, use every available thread.
* Locally, leave headroom for the editor and other foreground work: half the
* threads minus one (never less than one). Callers should skip setting
* `DENO_JOBS` when the operator has already set it, so an explicit override
* always wins.
*/
export const precommitWorkerCount = (
hardwareConcurrency: number,
ci: boolean,
): number =>
ci
? hardwareConcurrency
: Math.max(1, Math.floor(hardwareConcurrency / 2) - 1);

/**
* The `DENO_JOBS` value a precommit run should use: an explicit operator-set
* value always wins; otherwise the capped worker count for CI vs local.
* Returns `undefined` when the caller should not change the env (the operator
* set `DENO_JOBS` themselves — `main` checks for this and skips).
*/
export const resolveDenoJobs = (
hardwareConcurrency: number,
ci: boolean,
currentDenoJobs: string | undefined,
): number | undefined => {
if (currentDenoJobs !== undefined) return;
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
return precommitWorkerCount(hardwareConcurrency, ci);
};
2 changes: 1 addition & 1 deletion src/docs/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Uses the Web Crypto API for:
* - Hybrid RSA-OAEP + AES-256-GCM encryption for PII at rest
* - HMAC-SHA256 for webhooks and CSRF tokens
* - Argon2-style password hashing
* - PBKDF2-SHA256 password hashing
* - Constant-time comparison for timing-safe checks
*
* @module
Expand Down
8 changes: 5 additions & 3 deletions src/docs/payments.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
/**
* Payment processing with Stripe and Square.
* Payment processing with Stripe, Square, and SumUp.
*
* A provider-agnostic payment interface with adapters for Stripe and Square.
* A provider-agnostic payment interface with adapters for all three providers.
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
* Handles checkout sessions, webhook verification, refunds, and
* idempotent payment processing.
*
* ## Provider Interface
*
* {@link PaymentProvider} defines the common contract:
* - Create single and multi-listing checkout sessions
* - Verify webhook signatures
* - Validate incoming webhooks (signature verification where the provider
* signs, as with Stripe and Square; for unsigned providers like SumUp,
* authenticity is re-established by fetching the checkout from the provider)
* - Retrieve session details and process refunds
*
* @module
Expand Down
98 changes: 98 additions & 0 deletions test/scripts/precommit/lock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { join } from "node:path";
import { expect } from "@std/expect";
import { afterEach, beforeEach, describe, it as test } from "@std/testing/bdd";
import { removeIfPresent } from "#scripts/cleanup.ts";
import { withPrecommitLock } from "#scripts/precommit/lock.ts";

const LOCK_PATH = join(
Deno.env.get("TMPDIR") ?? "/tmp",
`chobble-tickets-precommit-test-${Deno.pid}-${Date.now()}.lock`,
);

const HOLD_LOCK_SCRIPT = `
const file = await Deno.open(Deno.args[0], {
create: true,
read: true,
write: true,
});
await file.lock();
await Deno.stdout.write(new TextEncoder().encode("locked\\n"));
await Deno.stdin.read(new Uint8Array(1));
file.close();
`;

const EXIT_WITH_LOCK_SCRIPT = `
const file = await Deno.open(Deno.args[0], {
create: true,
read: true,
write: true,
});
await file.lock();
await Deno.stdout.write(new TextEncoder().encode("locked\\n"));
Deno.exit(0);
`;

const startHolder = (
script: string,
stdin: "piped" | "null" = "piped",
): Deno.ChildProcess =>
new Deno.Command(Deno.execPath(), {
args: ["eval", script, "--", LOCK_PATH],
stdin,
stdout: "piped",
}).spawn();

const waitUntilLocked = async (child: Deno.ChildProcess): Promise<void> => {
const reader = child.stdout.getReader();
try {
const { value } = await reader.read();
expect(new TextDecoder().decode(value)).toBe("locked\n");
} finally {
await reader.cancel();
reader.releaseLock();
}
};

const releaseHolder = async (child: Deno.ChildProcess): Promise<void> => {
const writer = child.stdin.getWriter();
await writer.write(new Uint8Array([1]));
await writer.close();
await child.status;
};

describe("withPrecommitLock", () => {
beforeEach(() => removeIfPresent(LOCK_PATH));
afterEach(() => removeIfPresent(LOCK_PATH));

test("runs the task and returns its value", async () => {
await expect(
withPrecommitLock(() => Promise.resolve("checked"), LOCK_PATH),
).resolves.toBe("checked");
});

test("waits for a lock held by another process", async () => {
const holder = startHolder(HOLD_LOCK_SCRIPT);
await waitUntilLocked(holder);

let ran = false;
const waiting = withPrecommitLock(async () => {
ran = true;
}, LOCK_PATH);
await new Promise<void>((resolve) => queueMicrotask(resolve));
expect(ran).toBe(false);
Comment thread
stefan-burke marked this conversation as resolved.
Resolved

await releaseHolder(holder);
await waiting;
expect(ran).toBe(true);
});

test("acquires after a holder exits without unlocking", async () => {
const holder = startHolder(EXIT_WITH_LOCK_SCRIPT, "null");
await waitUntilLocked(holder);
await holder.status;

await expect(
withPrecommitLock(() => Promise.resolve("recovered"), LOCK_PATH),
).resolves.toBe("recovered");
});
});
Loading