Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 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.

14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ It is developed by [Chobble CIC](https://chobble.com) - a community interest com

**Website**: [tickets.chobble.com](https://tickets.chobble.com)

This is not "open core" - every feature is available under **AGPLv3** with no proprietary add-ons. If you'd rather not host it yourself, I offer hosted instances at [tix.chobble.com](https://tix.chobble.com/ticket/register) for £5/month or £50/year.
This is not "open core" - every feature is available under [AGPL-3.0-only](LICENSE) with no proprietary add-ons. If you'd rather not host it yourself, I offer hosted instances at [tix.chobble.com](https://tix.chobble.com/ticket/register) for £5/month or £50/year.

---

Expand Down Expand Up @@ -207,16 +207,16 @@ Prices are in the smallest currency unit (e.g. pence, cents). For multi-listing

### Encryption

- **Hybrid RSA-OAEP + AES-256-GCM** for attendee PII (name, email, phone, postal address)
- **Hybrid RSA-OAEP + AES-256-GCM** for attendee PII (name, email, phone, postal address) and payment references
- 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 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
- The data key is wrapped with each owner, manager, and agent password and each API key. These credentials are never stored, so a database dump plus the environment key still cannot decrypt PII without one of them
- 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 every owner, manager, and agent password and every API key is lost, protected data cannot be recovered

### 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
24 changes: 24 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,30 @@ 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.

---

## Recover paid SumUp checkouts 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. If its webhook is lost and the customer never
returns to the redirect URL, SumUp can charge the customer without creating a
booking or payment record. Only the staged checkout remains, and database
pruning removes it after 24 hours.

Add a bounded maintenance task to `src/shared/maintenance/registry.ts` that
checks a page of staged SumUp checkouts on each run. Fetch each checkout once.
When SumUp reports it as `PAID`, pass the fetched session through the same
classification and `processPaymentSession` path used by webhooks and redirects.
Extract a shared entry point that accepts an already fetched session so the task
does not make a second provider request. Keep each run within the edge request
budget and request a follow-up run when a full page remains. Add a regression
test that runs webhook, redirect, and maintenance attempts concurrently and
proves they create the attendee and ledger rows exactly once.

---

## Stale equivalent-mutant line numbers across recent refactors

*Origin: running `deno task mutation:audit-equivalents` while hardening
Expand Down
9 changes: 4 additions & 5 deletions scripts/lock-file.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
/** 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. Shared by local
* tooling that must not run the same expensive operation concurrently. */
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 +15,7 @@ export const withFileLock = async <T>(
try {
return await body();
} finally {
file.unlock();
await file.unlock();
}
} finally {
file.close();
Expand Down
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();
};
42 changes: 36 additions & 6 deletions scripts/precommit/runner.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { tmpdir } from "node:os";
import { join } from "node:path";
import { withFileLock } from "#scripts/lock-file.ts";
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 { 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 All @@ -11,6 +16,11 @@ import {
} from "./terminal.ts";
import { write } from "./write.ts";

const PRECOMMIT_LOCK_PATH = join(tmpdir(), "chobble-tickets-precommit.lock");

const withPrecommitLock = (task: () => Promise<void>): Promise<void> =>
withFileLock(PRECOMMIT_LOCK_PATH, task);

const canPromptNow = (): boolean => canPrompt(currentTerminalState());

const canShowProgressNow = (): boolean =>
Expand Down Expand Up @@ -90,12 +100,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 +111,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 +125,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.
// A valid explicit DENO_JOBS wins; replace invalid values with the default.
const jobs = resolveDenoJobs(
navigator.hardwareConcurrency,
ci,
Deno.env.get("DENO_JOBS"),
);
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: 29 additions & 1 deletion scripts/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,34 @@ export const parseWorkerCount = (
value: string | undefined,
fallback: number,
): number => {
if (!value || !/^\d+$/.test(value)) return fallback;
const jobs = Number(value);
return Number.isInteger(jobs) && jobs > 0 ? jobs : fallback;
return Number.isSafeInteger(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).
*/
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. A valid positive whole
* number wins; otherwise use the capped worker count for CI or local work.
*/
export const resolveDenoJobs = (
hardwareConcurrency: number,
ci: boolean,
currentDenoJobs: string | undefined,
): number =>
parseWorkerCount(
currentDenoJobs,
precommitWorkerCount(hardwareConcurrency, ci),
);
4 changes: 2 additions & 2 deletions src/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*
* ## Features
*
* - Free and paid listings (Stripe/Square integration)
* - Free and paid listings (Stripe, Square, and SumUp integration)
* - Standard listings (fixed capacity) and daily listings (date-based booking)
* - Multi-listing bookings in one checkout
* - Hybrid RSA-OAEP + AES-256-GCM encryption for PII at rest
Expand All @@ -24,7 +24,7 @@
* |--------|-------------|
* | [Database](../docs/database.ts) | ORM, table abstractions, and entity CRUD |
* | [Crypto](../docs/crypto.ts) | Encryption, hashing, and CSRF |
* | [Payments](../docs/payments.ts) | Stripe and Square integration |
* | [Payments](../docs/payments.ts) | Stripe, Square, and SumUp integration |
* | [Email](../docs/email.ts) | Email sending and templates |
* | [Tickets](../docs/tickets.ts) | QR codes, SVG tickets, Apple Wallet |
* | [Listings](../docs/listings.ts) | Listing fields, sorting, availability |
Expand Down
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
6 changes: 3 additions & 3 deletions src/docs/payments.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/**
* 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 using each provider's checks
* - Retrieve session details and process refunds
*
* @module
Expand Down
123 changes: 123 additions & 0 deletions test/scripts/lock-file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { join } from "node:path";
import { expect } from "@std/expect";
import { afterEach, beforeEach, describe, it as test } from "@std/testing/bdd";
import { stub } from "@std/testing/mock";
import { removeIfPresent } from "#scripts/cleanup.ts";
import { withFileLock } from "#scripts/lock-file.ts";

const LOCK_PATH = join(
Deno.env.get("TMPDIR") ?? "/tmp",
`chobble-tickets-file-lock-test-${Deno.pid}-${Date.now()}.lock`,
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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("withFileLock", () => {
beforeEach(() => removeIfPresent(LOCK_PATH));
afterEach(() => removeIfPresent(LOCK_PATH));

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

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

const lockAttempted = Promise.withResolvers<void>();
const open = Deno.open;
const openStub = stub(
Deno,
"open",
async (
path: string | URL,
options?: Deno.OpenOptions,
): Promise<Deno.FsFile> => {
const file = await open(path, options);
const lock = file.lock.bind(file);
file.lock = (exclusive?: boolean): Promise<void> => {
lockAttempted.resolve();
return lock(exclusive);
};
return file;
},
);

let ran = false;
let waiting: Promise<void> = Promise.resolve();
try {
waiting = withFileLock(LOCK_PATH, async () => {
ran = true;
});
await lockAttempted.promise;
expect(ran).toBe(false);
} finally {
openStub.restore();
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(
withFileLock(LOCK_PATH, () => Promise.resolve("recovered")),
).resolves.toBe("recovered");
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Loading