diff --git a/.gitignore b/.gitignore
index 719845e..49fa600 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@ data/
.env
.DS_Store
public/vendor/
+web-demo/dist/
diff --git a/README.md b/README.md
index 0456437..475d8d8 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,27 @@
A small invite-only ticketing app for a private event. Guests are named. There is no payment, no resale marketplace, and the app never messages anyone. The door code rotates every few seconds, in the same spirit as Ticketmaster SafeTix: a screenshot goes stale, and a code that already admitted someone cannot be used again.
+## Nitro 05
+
+Breakpoint 2026 is Solana's conference at Olympia London, 15–17 November. Around it, about 155 side events — dinners, mixers, investor rooms — are invite-only or capped. The host has a list of names. The door is a volunteer with a phone. A screenshot forwarded in a group chat should not get a second person in.
+
+This is that door. The host imports a CSV (`name`, and optionally `email` and `handle`). Each good row becomes a named ticket. Bad rows are reported and skipped. The host copies each guest link and hands it over. The app does not email or text anyone. The guest page shows a QR code with a countdown ring. It changes every five seconds. The volunteer sees a green ADMIT and the guest's name, or a red REJECTED and the reason: already used, expired, wrong event, or revoked. The host desk shows a live checked-in count.
+
+NoahAI Nitro 05 asks for a product people could genuinely use at Breakpoint. The brief is at https://luma.com/kk4ymgrb. A judge can run the whole loop with no server from `web-demo/`: import the sample list, open a rotating ticket, scan it on the same screen, see the replay rejected, see a 15-second-old code rejected, then approve a transfer.
+
+## At a Breakpoint side event
+
+1. Create the event, or run `npm run seed` for the demo dinner "Breakpoint side-event dinner, London".
+2. Import `samples/breakpoint-guests.csv`, or paste your own list. Fix any rows the import names.
+3. Copy each guest link and give it to that person yourself.
+4. Create a door-staff link and give it to the volunteer. That page can scan this event only. It cannot open or edit the guest list.
+5. At the door, the guest shows the live QR. The volunteer admits them once.
+6. If someone gives their seat away, they request a transfer. Nothing changes until you approve it. Approval replaces the secret, so the old code and the old link die.
+
+## Browser demo
+
+`web-demo/` is a self-contained page for a front-end builder. It has no login and no server. The guest list lives in `localStorage`. Check-in uses the same decision order as the server, and the code is an HMAC from WebCrypto, truncated the same way. `npm run demo:web` serves it. The files to copy are `web-demo/` plus `src/protocol.ts`, `src/csv.ts`, `src/clock.ts`, `src/format.ts`, `src/demo-event.ts`, and `samples/breakpoint-guests.csv`.
+
## How a code works
Each ticket has a secret of 32 random bytes that stays on the server. The guest page polls the server and shows a QR code. The payload is:
@@ -38,6 +59,8 @@ On approval the same ticket gets the new name, a new 32-byte secret, and a new g
## Threat model
+In plain words: the rotating code stops a screenshot and a second scan of a ticket that already came in. It does not prove who is holding the phone. Anyone looking at the live guest page can keep showing a fresh code. The host token is one shared secret, not a set of accounts. The staff link is narrower than the host token, and it is still just a bearer link. One SQLite file, one process.
+
What rotating codes actually stop:
- Forwarding a screenshot or a copied payload. It dies within about 10 seconds, and by 15 seconds it is three steps old and always rejected.
@@ -49,7 +72,8 @@ What they do not stop:
- Someone holding the live phone, or anyone who has the guest link open, can keep showing fresh codes. That is the same limit as SafeTix. The rotation proves the phone is talking to the server right now. It does not prove who is holding the phone.
- The host token is a single shared bearer secret. Anyone who has it can issue, revoke, and approve. It is not an account system.
-- The door endpoint is not separately authenticated. Anyone who can reach the server and knows an event id can submit codes. That fits a door device on a trusted network. It is not a production perimeter.
+- A door-staff link is scoped to one event. With it, a volunteer can scan codes for that night and see ADMIT or REJECTED, including the guest's name. They cannot list the other guests, import, revoke, or approve a transfer. A code from another event is rejected and that ticket stays unclaimed. Revoking the link stops it.
+- The open `/api/scan` route is still there for the host's own door page. Anyone who can reach the server and knows an event id can submit a code to it. That fits a host running the door on their own phone. It is not a lock for the public internet.
- Event name, venue, and start time are readable without the host token so the door page can list them. The guest list and ticket links are not.
- There is one SQLite file and one process. This is not a multi-node deployment.
@@ -62,8 +86,19 @@ cp .env.example .env
# Put a real token in .env. Generate one with: openssl rand -hex 32
npm install
npm start
+npm run seed
```
+`npm run seed` writes the Breakpoint side-event dinner and the sample guests into `DATABASE_PATH`, and prints guest links plus one door-staff link. Run it again and it will not duplicate the dinner.
+
+The no-server demo:
+
+```bash
+npm run demo:web
+```
+
+Open http://localhost:4173. Import the sample list, open a guest, and use "Scan the ticket on this screen". That path needs no camera, so it works on one laptop.
+
`.env` is loaded if it is present. Values already set in the environment win. The sample token in `.env.example` is a placeholder, not a secret, and it is not loaded on its own.
Open:
@@ -99,4 +134,4 @@ GitHub Actions runs typecheck and the tests on Node 20 and Node 22.
## What this is not
-No payments, no marketplace, no guest messaging, no production deploy, no multi-user accounts.
+No payments, no marketplace, no guest messaging, no production deploy, no crypto wallets, no multi-user accounts.
diff --git a/SUBMISSION.md b/SUBMISSION.md
new file mode 100644
index 0000000..e00513e
--- /dev/null
+++ b/SUBMISSION.md
@@ -0,0 +1,5 @@
+Breakpoint side events are invite-only dinners and mixers around Olympia London. Hosts need a named list. Volunteers check people in on a phone. A screenshot should not get someone else through the door.
+
+Each guest holds a QR that changes every 5 seconds. The door admits it once: ADMIT and their name, or REJECTED (already used, expired, wrong event, or revoked). The host imports a CSV and approves any transfer. A door link scans that one night only.
+
+[LIVE URL]
diff --git a/package-lock.json b/package-lock.json
index 7a75090..fa35578 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,6 +21,7 @@
"@types/qrcode": "^1.5.6",
"tsx": "^4.20.6",
"typescript": "^5.9.3",
+ "vite": "^6.4.1",
"vitest": "^3.2.4"
},
"engines": {
@@ -2212,24 +2213,24 @@
"license": "MIT"
},
"node_modules/vite": {
- "version": "7.3.8",
- "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.8.tgz",
- "integrity": "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==",
+ "version": "6.4.6",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz",
+ "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==",
"dev": true,
"license": "MIT",
"dependencies": {
- "esbuild": "^0.27.0 || ^0.28.0",
- "fdir": "^6.5.0",
- "picomatch": "^4.0.3",
- "postcss": "^8.5.6",
- "rollup": "^4.43.0",
- "tinyglobby": "^0.2.15"
+ "esbuild": "^0.25.0",
+ "fdir": "^6.4.4",
+ "picomatch": "^4.0.2",
+ "postcss": "^8.5.3",
+ "rollup": "^4.34.9",
+ "tinyglobby": "^0.2.13"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
- "node": "^20.19.0 || >=22.12.0"
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://github.com/vitejs/vite?sponsor=1"
@@ -2238,14 +2239,14 @@
"fsevents": "~2.3.3"
},
"peerDependencies": {
- "@types/node": "^20.19.0 || >=22.12.0",
+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"jiti": ">=1.21.0",
- "less": "^4.0.0",
+ "less": "*",
"lightningcss": "^1.21.0",
- "sass": "^1.70.0",
- "sass-embedded": "^1.70.0",
- "stylus": ">=0.54.8",
- "sugarss": "^5.0.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
@@ -2309,6 +2310,490 @@
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/vite/node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/android-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/linux-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/win32-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/esbuild": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
"node_modules/vitest": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",
diff --git a/package.json b/package.json
index 0466e20..55e9abf 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,9 @@
"start": "tsx src/index.ts",
"typecheck": "tsc --noEmit",
"test": "vitest run",
- "demo": "tsx scripts/demo.ts"
+ "demo": "tsx scripts/demo.ts",
+ "seed": "tsx scripts/seed.ts",
+ "demo:web": "vite --config web-demo/vite.config.ts"
},
"dependencies": {
"@hono/node-server": "^1.19.9",
@@ -27,6 +29,7 @@
"@types/qrcode": "^1.5.6",
"tsx": "^4.20.6",
"typescript": "^5.9.3",
+ "vite": "^6.4.1",
"vitest": "^3.2.4"
}
}
diff --git a/public/door.html b/public/door.html
index bae86d5..87e5bba 100644
--- a/public/door.html
+++ b/public/door.html
@@ -9,12 +9,14 @@
+ Breakpoint side-event door
Event
diff --git a/public/door.js b/public/door.js
index 7cbc85b..4cc6fae 100644
--- a/public/door.js
+++ b/public/door.js
@@ -2,7 +2,11 @@ const eventSelect = document.querySelector('#event');
const resultEl = document.querySelector('#result');
const cameraButton = document.querySelector('#camera');
const cameraState = document.querySelector('#camera-state');
+const eventLock = document.querySelector('#event-lock');
+const hostLink = document.querySelector('#host-link');
const params = new URLSearchParams(location.search);
+const staffMatch = location.pathname.match(/^\/door\/s\/([^/]+)$/);
+const staffToken = staffMatch ? decodeURIComponent(staffMatch[1]) : '';
let scanner = null;
let busy = false;
@@ -28,6 +32,25 @@ const REASONS = {
};
async function loadEvents() {
+ if (staffToken) {
+ const res = await fetch(`/api/staff/${encodeURIComponent(staffToken)}`, { cache: 'no-store' });
+ const data = await res.json().catch(() => ({}));
+ eventSelect.replaceChildren();
+ if (!res.ok) {
+ show('reject', 'REJECTED', 'this door link is not active');
+ cameraButton.disabled = true;
+ return;
+ }
+ const option = document.createElement('option');
+ option.value = data.event.id;
+ option.textContent = `${data.event.name} · ${data.event.venue}`;
+ eventSelect.append(option);
+ eventSelect.disabled = true;
+ eventLock.hidden = false;
+ eventLock.textContent = `${data.event.name} · scan only`;
+ hostLink.hidden = true;
+ return;
+ }
const res = await fetch('/api/events');
const data = await res.json();
eventSelect.replaceChildren();
@@ -55,10 +78,10 @@ async function submit(code) {
show('reject', 'REJECTED', 'pick an event');
return;
}
- const res = await fetch('/api/scan', {
+ const res = await fetch(staffToken ? `/api/staff/${encodeURIComponent(staffToken)}/scan` : '/api/scan', {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ event_id: eventId, code }),
+ body: JSON.stringify(staffToken ? { code } : { event_id: eventId, code }),
});
const data = await res.json();
if (!res.ok) {
diff --git a/public/guest.html b/public/guest.html
index 140994e..cdc3593 100644
--- a/public/guest.html
+++ b/public/guest.html
@@ -9,13 +9,20 @@
+ Breakpoint side-event door
Guest ticket
Loading…
-
+
+
+
+
+
+
+
New code in – s
diff --git a/public/guest.js b/public/guest.js
index 37d4e2b..34d25ac 100644
--- a/public/guest.js
+++ b/public/guest.js
@@ -12,6 +12,11 @@ const holdEl = document.querySelector('#hold');
const form = document.querySelector('#transfer');
const errorEl = document.querySelector('#error');
const countdown = document.querySelector('#countdown');
+const ring = document.querySelector('#ring');
+const ringRadius = Number(ring?.getAttribute('r') || 54);
+const ringLength = 2 * Math.PI * ringRadius;
+if (ring) ring.style.strokeDasharray = `${ringLength} ${ringLength}`;
+let stepMs = 5000;
let stepEndsAt = 0;
let skew = 0;
@@ -45,6 +50,7 @@ async function load() {
errorEl.textContent = '';
skew = data.server_now - Date.now();
stepEndsAt = data.step_ends_at;
+ stepMs = data.step_ms || 5000;
status = data.status;
eventName.textContent = data.event.name;
whenEl.textContent = new Date(data.event.starts_at).toLocaleString();
@@ -83,6 +89,11 @@ async function load() {
function frame() {
const remain = stepEndsAt - localNow();
remainEl.textContent = stepEndsAt ? Math.max(0, remain / 1000).toFixed(1) : '–';
+ if (ring) {
+ const fraction = stepEndsAt ? Math.max(0, Math.min(1, remain / stepMs)) : 0;
+ ring.style.strokeDashoffset = String(ringLength * (1 - fraction));
+ ring.classList.toggle('urgent', remain < 1000);
+ }
const dueForStep = status === 'issued' && stepEndsAt && remain <= 40 && Date.now() >= nextFetchAt;
const dueForStatus = status === 'issued' && Date.now() >= nextStatusAt;
if (dueForStep || dueForStatus) {
diff --git a/public/host.html b/public/host.html
index b82ed7f..2d37862 100644
--- a/public/host.html
+++ b/public/host.html
@@ -9,6 +9,7 @@
+ Breakpoint side-event door
Host desk
@@ -32,16 +33,20 @@
Host token
Tickets
+
Event
@@ -52,7 +57,22 @@ Tickets
Issue ticket
+
Import a guest list
+
CSV header name,email,handle . Email and handle can be blank. Bad rows are skipped and listed.
+
+
+
Import guests
+
+
Door staff
+
A volunteer with this link can scan this event and nothing else. They cannot open the guest list.
+
+
diff --git a/public/host.js b/public/host.js
index 6a72456..f3116da 100644
--- a/public/host.js
+++ b/public/host.js
@@ -6,6 +6,10 @@ const guestsBody = document.querySelector('#guests');
const transfersEl = document.querySelector('#transfers');
const issuedLink = document.querySelector('#issued-link');
const doorLink = document.querySelector('#door-link');
+const tallyCount = document.querySelector('#tally-count');
+const tallyLabel = document.querySelector('#tally-label');
+const importReport = document.querySelector('#import-report');
+const staffLinks = document.querySelector('#staff-links');
const TOKEN_KEY = 'private-tickets-host-token';
const EVENT_KEY = 'private-tickets-event';
@@ -98,6 +102,10 @@ async function refresh() {
api('GET', `/api/host/events/${eventId}/tickets`),
api('GET', `/api/host/events/${eventId}/transfers`),
]);
+ const checkedIn = ticketData.tickets.filter((ticket) => ticket.status === 'checked_in').length;
+ tallyCount.textContent = String(checkedIn);
+ tallyLabel.textContent = `of ${ticketData.tickets.length} checked in`;
+ await renderStaff(eventId);
if (ticketData.tickets.length === 0) {
const tr = document.createElement('tr');
const td = document.createElement('td');
@@ -111,8 +119,18 @@ async function refresh() {
const tr = document.createElement('tr');
const name = document.createElement('td');
name.textContent = ticket.guest_name;
+ const extra = [ticket.email, ticket.handle].filter(Boolean).join(' · ');
+ if (extra) {
+ const sub = document.createElement('div');
+ sub.className = 'muted';
+ sub.textContent = extra;
+ name.append(sub);
+ }
const status = document.createElement('td');
- status.textContent = ticket.status.replaceAll('_', ' ');
+ const pill = document.createElement('span');
+ pill.className = `pill ${ticket.status}`;
+ pill.textContent = ticket.status.replaceAll('_', ' ');
+ status.append(pill);
const link = document.createElement('td');
link.append(linkLine(ticket.guest_path, 'Open ticket'));
const actions = document.createElement('td');
@@ -216,6 +234,92 @@ document.querySelector('#issue-form').addEventListener('submit', async (event) =
}
});
+async function renderStaff(eventId) {
+ staffLinks.replaceChildren();
+ const data = await api('GET', `/api/host/events/${eventId}/staff`);
+ const active = data.staff.filter((staff) => !staff.revoked_at);
+ if (active.length === 0) {
+ const empty = document.createElement('p');
+ empty.className = 'muted';
+ empty.textContent = 'No door link yet.';
+ staffLinks.append(empty);
+ return;
+ }
+ for (const staff of active) {
+ const row = document.createElement('div');
+ row.className = 'row';
+ const link = linkLine(staff.door_path, `${staff.label}: ${staff.door_path}`);
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'secondary';
+ button.textContent = 'Revoke';
+ button.addEventListener('click', async () => {
+ try {
+ await api('POST', `/api/host/staff/${staff.id}/revoke`, {});
+ say(`Revoked the ${staff.label} link`);
+ await refresh();
+ } catch (error) {
+ say(error.message);
+ }
+ });
+ row.append(link, button);
+ staffLinks.append(row);
+ }
+}
+
+document.querySelector('#csv-file').addEventListener('change', async (event) => {
+ const file = event.currentTarget.files && event.currentTarget.files[0];
+ if (!file) return;
+ document.querySelector('#csv-text').value = await file.text();
+});
+
+document.querySelector('#import-csv').addEventListener('click', async () => {
+ const eventId = selectedEventId();
+ if (!eventId) {
+ say('Create or select an event first.');
+ return;
+ }
+ const csv = document.querySelector('#csv-text').value;
+ if (!csv.trim()) {
+ say('Paste a CSV or choose a file.');
+ return;
+ }
+ try {
+ const data = await api('POST', `/api/host/events/${eventId}/import`, { csv });
+ importReport.replaceChildren();
+ const summary = document.createElement('p');
+ summary.textContent = `${data.created.length} guests added. ${data.errors.length} rows need a fix.`;
+ importReport.append(summary);
+ for (const error of data.errors) {
+ const line = document.createElement('p');
+ line.textContent = `Line ${error.line}: ${error.reason}`;
+ importReport.append(line);
+ }
+ say('Import finished. Copy each guest link yourself. This app does not message anyone.');
+ await refresh();
+ } catch (error) {
+ say(error.message);
+ }
+});
+
+document.querySelector('#staff-form').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const eventId = selectedEventId();
+ if (!eventId) {
+ say('Create or select an event first.');
+ return;
+ }
+ const label = new FormData(event.currentTarget).get('label');
+ try {
+ const data = await api('POST', `/api/host/events/${eventId}/staff`, { label: label || 'Door' });
+ event.currentTarget.reset();
+ say(`Door link ready: ${data.staff.door_path}`);
+ await refresh();
+ } catch (error) {
+ say(error.message);
+ }
+});
+
eventSelect.addEventListener('change', () => {
refresh().catch((error) => say(error.message));
});
diff --git a/public/index.html b/public/index.html
index f9f927f..a2ac0cf 100644
--- a/public/index.html
+++ b/public/index.html
@@ -9,9 +9,10 @@
+ Breakpoint side-event door
Invite only
Private tickets
- Named guests, host-approved transfers, and a door code that rotates every five seconds.
+ Named guests for a Breakpoint side event. The door code rotates every five seconds, and a transfer waits until the host approves it.
Host desk
Door scanner
@@ -19,9 +20,9 @@
Private tickets
How a night works
- The host creates an event and issues a ticket to a named guest.
+ The host creates an event and imports a guest list, or issues one named ticket.
The guest opens their link. The page shows a QR code that changes every five seconds.
- The door scans that code. It works once. A photo from a minute ago does not.
+ A volunteer opens a door-staff link for that event. The scan works once. A photo from a few seconds ago does not.
A transfer sits pending until the host approves it. Approval kills the old code and issues a new one.
diff --git a/public/styles.css b/public/styles.css
index 4f2bc33..95ef100 100644
--- a/public/styles.css
+++ b/public/styles.css
@@ -15,6 +15,7 @@
}
* { box-sizing: border-box; }
+[hidden] { display: none !important; }
body {
margin: 0;
@@ -29,25 +30,31 @@ a { color: var(--accent); }
button,
input,
-select {
+select,
+textarea {
font: inherit;
color: inherit;
+ font-size: 16px;
}
button,
input,
-select {
+select,
+textarea {
border: 1px solid var(--line);
background: white;
border-radius: 6px;
padding: 0.55rem 0.7rem;
}
+textarea { width: 100%; min-height: 6.5rem; }
+
button {
background: var(--ink);
color: var(--paper);
border-color: var(--ink);
cursor: pointer;
+ min-height: 44px;
}
button.secondary {
@@ -71,6 +78,16 @@ header.top {
margin-bottom: 1.5rem;
}
+.brand {
+ margin: 0 0 0.8rem;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ font-size: 0.75rem;
+ color: var(--muted);
+}
+
+.brand span { color: var(--ink); font-weight: 700; }
+
.eyebrow {
margin: 0 0 0.25rem;
letter-spacing: 0.14em;
@@ -134,12 +151,57 @@ code, .code {
text-align: center;
}
-.ticket img {
- width: min(100%, 320px);
- height: auto;
+.qr-stage {
+ position: relative;
+ width: min(100%, 340px);
+ margin: 0 auto;
+ aspect-ratio: 1;
+}
+
+.qr-stage .ring {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ transform: rotate(-90deg);
+}
+
+.ring-track,
+.ring-value { fill: none; stroke-width: 4; }
+.ring-track { stroke: var(--line); }
+.ring-value { stroke: var(--good); stroke-linecap: round; }
+.ring-value.urgent { stroke: var(--bad); }
+
+.ticket img,
+.qr-stage img {
+ position: absolute;
+ inset: 12%;
+ width: 76%;
+ height: 76%;
+ object-fit: contain;
background: white;
}
+.tally { display: flex; align-items: baseline; gap: 0.6rem; }
+.tally-count {
+ margin: 0;
+ font-size: clamp(2.8rem, 10vw, 4rem);
+ line-height: 0.9;
+ font-variant-numeric: tabular-nums;
+}
+
+.pill {
+ display: inline-block;
+ padding: 0.1rem 0.45rem;
+ border-radius: 999px;
+ border: 1px solid var(--line);
+ font-size: 0.78rem;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+.pill.checked_in { background: var(--good-bg); color: var(--good); }
+.pill.revoked { background: var(--bad-bg); color: var(--bad); }
+
.status {
display: inline-block;
padding: 0.15rem 0.5rem;
@@ -151,12 +213,12 @@ code, .code {
}
.result {
- margin-top: 1rem;
+ margin-top: 0.4rem;
border-radius: 14px;
- padding: 1.2rem 1rem;
+ padding: 1.3rem 1rem;
text-align: center;
- font-size: clamp(2rem, 8vw, 3.4rem);
- line-height: 1;
+ font-size: clamp(2.6rem, 12vw, 4.4rem);
+ line-height: 0.95;
letter-spacing: 0.04em;
border: 1px solid var(--line);
background: white;
diff --git a/samples/breakpoint-guests.csv b/samples/breakpoint-guests.csv
new file mode 100644
index 0000000..8912f77
--- /dev/null
+++ b/samples/breakpoint-guests.csv
@@ -0,0 +1,13 @@
+name,email,handle
+Amira Shah,amira.shah@example.com,@amirashah
+Jonah Ellison,jonah@example.com,@jellison
+Priya Raman,,@priyar
+Leo Martins,leo.martins@example.com,
+Nora Blake,,
+Sam Okonkwo,sam.okonkwo@example.com,@samokonkwo
+Helen Cho,helen.cho@example.com,@helencho
+Mateo Ruiz,,@mateoruiz
+Ines Berger,ines.berger@example.com,
+Owen Clarke,owen@example.com,@owenclarke
+Fatima Diallo,fatima.diallo@example.com,@fdiallo
+Chris Nguyen,,
diff --git a/scripts/seed.ts b/scripts/seed.ts
new file mode 100644
index 0000000..6cfe0c1
--- /dev/null
+++ b/scripts/seed.ts
@@ -0,0 +1,63 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { DEMO_EVENT, DEMO_EVENT_NAME } from '../src/demo-event';
+import { openDatabase, type EventRow } from '../src/db';
+import { loadEnvFile } from '../src/env';
+import { createEvent, createStaffToken, importGuests, listStaff, listTickets } from '../src/service';
+
+loadEnvFile(resolve(process.cwd(), '.env'));
+
+const databasePath = process.env.DATABASE_PATH ?? './data/tickets.db';
+const db = openDatabase(databasePath === ':memory:' ? databasePath : resolve(databasePath));
+const now = Date.now();
+const csv = readFileSync(resolve(process.cwd(), 'samples/breakpoint-guests.csv'), 'utf8');
+
+const existing = db.prepare('SELECT * FROM events WHERE name = ? ORDER BY created_at ASC').get(DEMO_EVENT_NAME) as
+ | EventRow
+ | undefined;
+
+let eventId: string;
+if (existing) {
+ eventId = existing.id;
+ console.log('Demo event already exists. Leaving the guest list as it is.');
+} else {
+ const event = createEvent(db, {
+ name: DEMO_EVENT.name,
+ startsAt: DEMO_EVENT.startsAt,
+ venue: DEMO_EVENT.venue,
+ host: DEMO_EVENT.host,
+ nowMs: now,
+ });
+ eventId = event.id;
+ const imported = importGuests(db, { eventId, csv, nowMs: now });
+ if (!imported.ok) {
+ console.error(imported.error);
+ process.exit(1);
+ }
+ console.log(`Imported ${imported.created.length} guests.`);
+ for (const error of imported.errors) console.log(`line ${error.line}: ${error.reason}`);
+}
+
+const staffList = listStaff(db, eventId) ?? [];
+let doorPath = staffList.find((staff) => !staff.revoked_at)?.door_path;
+if (!doorPath) {
+ const created = createStaffToken(db, { eventId, label: 'Front door', nowMs: now });
+ if ('error' in created) {
+ console.error(created.error);
+ process.exit(1);
+ }
+ doorPath = created.door_path;
+}
+
+const tickets = listTickets(db, eventId) ?? [];
+console.log('');
+console.log(DEMO_EVENT_NAME);
+console.log(`${DEMO_EVENT.venue} · ${DEMO_EVENT.host}`);
+console.log(`guests: ${tickets.length}`);
+console.log(`door staff: ${doorPath}`);
+console.log('');
+for (const ticket of tickets) {
+ const contact = [ticket.email, ticket.handle].filter(Boolean).join(' ');
+ console.log(`${ticket.guest_name}${contact ? ` ${contact}` : ''} ${ticket.guest_path}`);
+}
+db.close();
diff --git a/src/app.ts b/src/app.ts
index af4e984..287323e 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -4,17 +4,24 @@ import { join } from 'node:path';
import { Hono } from 'hono';
import { systemClock, type Clock } from './clock';
import type { DB } from './db';
+import { cleanGuestEmail, cleanGuestHandle, cleanGuestName } from './csv';
import {
approveTransfer,
createEvent,
+ createStaffToken,
guestView,
+ importGuests,
issueTicket,
listEvents,
+ listStaff,
listTickets,
listTransfers,
requestTransfer,
+ revokeStaffToken,
revokeTicket,
scanCode,
+ scanWithStaff,
+ staffSession,
} from './service';
export type AppDeps = {
@@ -106,6 +113,31 @@ export function createApp(deps: AppDeps): Hono {
return c.json(result);
});
+ app.get('/api/staff/:token', (c) => {
+ const session = staffSession(deps.db, c.req.param('token'));
+ if (!session) return c.json({ error: 'not_found' }, 404);
+ c.header('cache-control', 'no-store');
+ return c.json(session);
+ });
+
+ app.post('/api/staff/:token/scan', async (c) => {
+ const body = await readJson(c);
+ if (!body) return c.json({ error: 'invalid_json' }, 400);
+ const code = typeof body.code === 'string' ? body.code.trim() : '';
+ if (code.length === 0) return c.json({ error: 'invalid_body' }, 400);
+ const requestedEvent = body.event_id === undefined ? null : cleanText(body.event_id, 80);
+ if (body.event_id !== undefined && !requestedEvent) return c.json({ error: 'invalid_body' }, 400);
+ const result = scanWithStaff(deps.db, {
+ token: c.req.param('token'),
+ code,
+ nowMs: clock(),
+ eventId: requestedEvent,
+ });
+ if (!result.ok) return c.json({ error: result.error }, 401);
+ c.header('cache-control', 'no-store');
+ return c.json(result.scan);
+ });
+
app.get('/api/guest/:token', async (c) => {
const view = await guestView(deps.db, c.req.param('token'), clock());
if (!view) return c.json({ error: 'not_found' }, 404);
@@ -150,14 +182,82 @@ export function createApp(deps: AppDeps): Hono {
return c.json({ event }, 201);
});
+ host.post('/events/:eventId/import', async (c) => {
+ const contentType = c.req.header('content-type') ?? '';
+ let csv = '';
+ if (contentType.includes('text/csv') || contentType.includes('text/plain')) {
+ csv = await c.req.text();
+ } else {
+ const body = await readJson(c);
+ if (!body || typeof body.csv !== 'string') return c.json({ error: 'invalid_body' }, 400);
+ csv = body.csv;
+ }
+ if (csv.trim() === '') return c.json({ error: 'invalid_body' }, 400);
+ const result = importGuests(deps.db, { eventId: c.req.param('eventId'), csv, nowMs: clock() });
+ if (!result.ok) {
+ const status = result.error === 'not_found' ? 404 : 400;
+ return c.json({ error: result.error }, status);
+ }
+ return c.json({ created: result.created, errors: result.errors });
+ });
+
+ host.post('/events/:eventId/staff', async (c) => {
+ const body = await readJson(c);
+ if (!body) return c.json({ error: 'invalid_json' }, 400);
+ const label = cleanText(body.label ?? 'Door', 80) ?? 'Door';
+ if (body && body.label !== undefined && typeof body.label !== 'string') {
+ return c.json({ error: 'invalid_body' }, 400);
+ }
+ if (body && typeof body.label === 'string' && !cleanText(body.label, 80)) {
+ return c.json({ error: 'invalid_body' }, 400);
+ }
+ const result = createStaffToken(deps.db, {
+ eventId: c.req.param('eventId'),
+ label,
+ nowMs: clock(),
+ });
+ if ('error' in result) return c.json({ error: result.error }, 404);
+ return c.json({ staff: result }, 201);
+ });
+
+ host.get('/events/:eventId/staff', (c) => {
+ const staff = listStaff(deps.db, c.req.param('eventId'));
+ if (!staff) return c.json({ error: 'not_found' }, 404);
+ return c.json({ staff });
+ });
+
+ host.post('/staff/:staffId/revoke', (c) => {
+ const result = revokeStaffToken(deps.db, c.req.param('staffId'), clock());
+ if ('error' in result) {
+ const status = result.error === 'not_found' ? 404 : 409;
+ return c.json({ error: result.error }, status);
+ }
+ return c.json({ staff: result });
+ });
+
host.post('/events/:eventId/tickets', async (c) => {
const body = await readJson(c);
if (!body) return c.json({ error: 'invalid_json' }, 400);
- const guestName = cleanText(body.guest_name);
- if (!guestName) return c.json({ error: 'invalid_name' }, 400);
+ const named = typeof body.guest_name === 'string' ? cleanGuestName(body.guest_name) : { ok: false as const };
+ if (!named.ok) return c.json({ error: 'invalid_name' }, 400);
+ const email =
+ body.email === undefined || body.email === ''
+ ? { ok: true as const, email: null }
+ : typeof body.email === 'string'
+ ? cleanGuestEmail(body.email)
+ : { ok: false as const };
+ const handle =
+ body.handle === undefined || body.handle === ''
+ ? { ok: true as const, handle: null }
+ : typeof body.handle === 'string'
+ ? cleanGuestHandle(body.handle)
+ : { ok: false as const };
+ if (!email.ok || !handle.ok) return c.json({ error: 'invalid_body' }, 400);
const result = issueTicket(deps.db, {
eventId: c.req.param('eventId'),
- guestName,
+ guestName: named.name,
+ email: email.email,
+ handle: handle.handle,
nowMs: clock(),
});
if ('error' in result) return c.json({ error: result.error }, 404);
@@ -203,6 +303,7 @@ export function createApp(deps: AppDeps): Hono {
app.get('/', (c) => c.html(page(publicDir, 'index.html')));
app.get('/host', (c) => c.html(page(publicDir, 'host.html')));
app.get('/door', (c) => c.html(page(publicDir, 'door.html')));
+ app.get('/door/s/:token', (c) => c.html(page(publicDir, 'door.html')));
app.get('/t/:token', (c) => c.html(page(publicDir, 'guest.html')));
for (const [route, contentType] of Object.entries(STATIC_FILES)) {
diff --git a/src/codes.ts b/src/codes.ts
index 8767255..6407a5a 100644
--- a/src/codes.ts
+++ b/src/codes.ts
@@ -1,12 +1,14 @@
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
-import { stepAt } from './clock';
+import {
+ MAC_BYTES,
+ formatCode,
+ macMessage,
+ parsePayload,
+ stepWithinWindow,
+ type ParsedPayload,
+} from './protocol';
-/** Truncated authentication tag. 16 bytes of HMAC-SHA256, hex-encoded in the payload. */
-export const MAC_BYTES = 16;
-
-const CODE_VERSION = 'pt1';
-const UUID_RE =
- /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+export { MAC_BYTES, macMessage, stepWithinWindow };
export type ParsedCode = {
ticketId: string;
@@ -14,13 +16,10 @@ export type ParsedCode = {
mac: Buffer;
};
-/**
- * Message is the UTF-8 encoding of `ticketId|decimalStep`.
- * The pipe is the field boundary so the two values cannot be confused.
- * The payload carries the ticket id and the step; it never carries the secret.
- */
-export function macMessage(ticketId: string, step: number): string {
- return `${ticketId}|${step}`;
+export function parseCode(raw: string): ParsedCode | null {
+ const parsed: ParsedPayload | null = parsePayload(raw);
+ if (!parsed) return null;
+ return { ticketId: parsed.ticketId, step: parsed.step, mac: Buffer.from(parsed.mac) };
}
export function computeMac(secret: Buffer, ticketId: string, step: number): Buffer {
@@ -33,30 +32,7 @@ export function compareMacs(expected: Buffer, provided: Buffer): boolean {
}
export function mintCode(secret: Buffer, ticketId: string, step: number): string {
- const mac = computeMac(secret, ticketId, step);
- return `${CODE_VERSION}.${ticketId}.${step}.${mac.toString('hex')}`;
-}
-
-export function parseCode(raw: string): ParsedCode | null {
- if (typeof raw !== 'string' || raw.length > 256) return null;
- const parts = raw.trim().split('.');
- if (parts.length !== 4) return null;
- const version = parts[0];
- const ticketId = parts[1];
- const stepText = parts[2];
- const macHex = parts[3];
- if (version !== CODE_VERSION || ticketId === undefined || stepText === undefined || macHex === undefined) {
- return null;
- }
- if (!UUID_RE.test(ticketId)) return null;
- if (!/^(0|[1-9][0-9]*)$/.test(stepText)) return null;
- const step = Number(stepText);
- if (!Number.isSafeInteger(step)) return null;
- const hex = macHex.toLowerCase();
- if (!/^[0-9a-f]{32}$/.test(hex)) return null;
- const mac = Buffer.from(hex, 'hex');
- if (mac.length !== MAC_BYTES) return null;
- return { ticketId: ticketId.toLowerCase(), step, mac };
+ return formatCode(ticketId, step, computeMac(secret, ticketId, step));
}
export function newSecret(): Buffer {
@@ -66,8 +42,3 @@ export function newSecret(): Buffer {
export function newAccessToken(): string {
return randomBytes(32).toString('base64url');
}
-
-/** A code is live for the current step and one step of clock skew on either side. */
-export function stepWithinWindow(codeStep: number, nowMs: number): boolean {
- return Math.abs(codeStep - stepAt(nowMs)) <= 1;
-}
diff --git a/src/csv.ts b/src/csv.ts
new file mode 100644
index 0000000..905dfc8
--- /dev/null
+++ b/src/csv.ts
@@ -0,0 +1,194 @@
+export const MAX_CSV_CHARS = 200_000;
+export const MAX_IMPORT_ROWS = 500;
+export const NAME_MAX = 120;
+
+const NAME_KEYS = new Set(['name', 'guest', 'guest_name', 'guest name']);
+const EMAIL_KEYS = new Set(['email', 'e-mail', 'email address']);
+const HANDLE_KEYS = new Set(['handle', 'twitter', 'social']);
+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+const HANDLE_RE = /^@?[A-Za-z0-9._]{1,40}$/;
+
+export type GuestDraft = {
+ line: number;
+ name: string;
+ email: string | null;
+ handle: string | null;
+};
+
+export type CsvRowError = {
+ line: number;
+ reason: string;
+};
+
+export type CsvRead =
+ | { ok: true; guests: GuestDraft[]; errors: CsvRowError[] }
+ | { ok: false; error: 'too_large' | 'missing_name_column' | 'duplicate_column' | 'too_many_rows' };
+
+type CsvRecord = { line: number; cells: string[] };
+
+function normHeader(value: string): string {
+ return value.trim().toLowerCase().replace(/\s+/g, ' ');
+}
+
+function isHeaderAlias(value: string): boolean {
+ const key = normHeader(value);
+ return NAME_KEYS.has(key) || EMAIL_KEYS.has(key) || HANDLE_KEYS.has(key);
+}
+
+export function cleanGuestName(value: string): { ok: true; name: string } | { ok: false; reason: string } {
+ const name = value.trim();
+ if (name.length < 1) return { ok: false, reason: 'Name is required' };
+ if (name.length > NAME_MAX) return { ok: false, reason: 'Name is too long' };
+ if (/[\u0000-\u001F\u007F]/.test(name)) return { ok: false, reason: 'Name has invalid characters' };
+ return { ok: true, name };
+}
+
+export function cleanGuestEmail(value: string): { ok: true; email: string | null } | { ok: false; reason: string } {
+ const email = value.trim();
+ if (email === '') return { ok: true, email: null };
+ if (email.length > 200 || /[\u0000-\u001F\u007F]/.test(email) || !EMAIL_RE.test(email)) {
+ return { ok: false, reason: 'Email is not valid' };
+ }
+ return { ok: true, email };
+}
+
+export function cleanGuestHandle(value: string): { ok: true; handle: string | null } | { ok: false; reason: string } {
+ const handle = value.trim();
+ if (handle === '') return { ok: true, handle: null };
+ if (!HANDLE_RE.test(handle)) return { ok: false, reason: 'Handle is not valid' };
+ return { ok: true, handle };
+}
+
+export function parseCsvRecords(input: string): CsvRecord[] {
+ const text = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
+ const records: CsvRecord[] = [];
+ let cells: string[] = [];
+ let field = '';
+ let inQuotes = false;
+ let line = 1;
+ let startLine = 1;
+
+ const finish = () => {
+ cells.push(field);
+ field = '';
+ if (cells.some((cell) => cell.trim() !== '')) records.push({ line: startLine, cells });
+ cells = [];
+ startLine = line;
+ };
+
+ for (let i = 0; i < text.length; i += 1) {
+ const char = text[i] ?? '';
+ if (inQuotes) {
+ if (char === '"') {
+ if (text[i + 1] === '"') {
+ field += '"';
+ i += 1;
+ continue;
+ }
+ inQuotes = false;
+ continue;
+ }
+ field += char;
+ if (char === '\n') line += 1;
+ continue;
+ }
+ if (char === '"') {
+ inQuotes = true;
+ continue;
+ }
+ if (char === ',') {
+ cells.push(field);
+ field = '';
+ continue;
+ }
+ if (char === '\n' || char === '\r') {
+ if (char === '\r' && text[i + 1] === '\n') i += 1;
+ line += 1;
+ finish();
+ continue;
+ }
+ field += char;
+ }
+ finish();
+ return records;
+}
+
+type ColumnMap = { name: number; email: number | null; handle: number | null };
+
+function headerMap(cells: string[]): ColumnMap | 'missing_name_column' | 'duplicate_column' | null {
+ const keys = cells.map(normHeader);
+ const hasName = keys.some((key) => NAME_KEYS.has(key));
+ const onlyAliases = keys.every((key) => key === '' || isHeaderAlias(key));
+ if (!hasName && keys.length > 0 && onlyAliases) return 'missing_name_column';
+ if (!hasName) return null;
+ const map: ColumnMap = { name: -1, email: null, handle: null };
+ for (let index = 0; index < keys.length; index += 1) {
+ const key = keys[index] ?? '';
+ if (NAME_KEYS.has(key)) {
+ if (map.name !== -1) return 'duplicate_column';
+ map.name = index;
+ } else if (EMAIL_KEYS.has(key)) {
+ if (map.email !== null) return 'duplicate_column';
+ map.email = index;
+ } else if (HANDLE_KEYS.has(key)) {
+ if (map.handle !== null) return 'duplicate_column';
+ map.handle = index;
+ }
+ }
+ if (map.name === -1) return 'missing_name_column';
+ return map;
+}
+
+function cell(cells: string[], index: number | null): string {
+ if (index === null || index < 0) return '';
+ return cells[index] ?? '';
+}
+
+/**
+ * Read a guest-list CSV. A header row is optional.
+ * With a header, `name` is required and `email` and `handle` are optional.
+ * Without one, columns are name, email, handle. Blank lines are skipped.
+ * Valid rows are returned even when other rows are rejected.
+ */
+export function readGuestCsv(input: string): CsvRead {
+ if (input.length > MAX_CSV_CHARS) return { ok: false, error: 'too_large' };
+ const records = parseCsvRecords(input);
+ if (records.length === 0) return { ok: true, guests: [], errors: [] };
+
+ const first = records[0];
+ if (!first) return { ok: true, guests: [], errors: [] };
+ const mapped = headerMap(first.cells);
+ if (mapped === 'missing_name_column' || mapped === 'duplicate_column') return { ok: false, error: mapped };
+
+ const data = mapped ? records.slice(1) : records;
+ if (data.length > MAX_IMPORT_ROWS) return { ok: false, error: 'too_many_rows' };
+
+ const guests: GuestDraft[] = [];
+ const errors: CsvRowError[] = [];
+ for (const record of data) {
+ const nameRaw = mapped ? cell(record.cells, mapped.name) : (record.cells[0] ?? '');
+ const emailRaw = mapped ? cell(record.cells, mapped.email) : (record.cells[1] ?? '');
+ const handleRaw = mapped ? cell(record.cells, mapped.handle) : (record.cells[2] ?? '');
+ if (!mapped && record.cells.length > 3) {
+ errors.push({ line: record.line, reason: 'Too many columns' });
+ continue;
+ }
+ const name = cleanGuestName(nameRaw);
+ if (!name.ok) {
+ errors.push({ line: record.line, reason: name.reason });
+ continue;
+ }
+ const email = cleanGuestEmail(emailRaw);
+ if (!email.ok) {
+ errors.push({ line: record.line, reason: email.reason });
+ continue;
+ }
+ const handle = cleanGuestHandle(handleRaw);
+ if (!handle.ok) {
+ errors.push({ line: record.line, reason: handle.reason });
+ continue;
+ }
+ guests.push({ line: record.line, name: name.name, email: email.email, handle: handle.handle });
+ }
+ return { ok: true, guests, errors };
+}
diff --git a/src/db.ts b/src/db.ts
index 1e5a9cc..1a9a21c 100644
--- a/src/db.ts
+++ b/src/db.ts
@@ -21,6 +21,8 @@ export type TicketRow = {
id: string;
event_id: string;
guest_name: string;
+ email: string | null;
+ handle: string | null;
status: TicketStatus;
secret: Buffer;
access_token: string;
@@ -28,6 +30,15 @@ export type TicketRow = {
checked_in_at: string | null;
};
+export type StaffRow = {
+ id: string;
+ event_id: string;
+ token: string;
+ label: string;
+ created_at: string;
+ revoked_at: string | null;
+};
+
export type TransferRow = {
id: string;
ticket_id: string;
@@ -53,6 +64,8 @@ CREATE TABLE IF NOT EXISTS tickets (
id TEXT PRIMARY KEY,
event_id TEXT NOT NULL REFERENCES events(id),
guest_name TEXT NOT NULL,
+ email TEXT,
+ handle TEXT,
status TEXT NOT NULL CHECK (status IN ('issued', 'checked_in', 'revoked')),
secret BLOB NOT NULL,
access_token TEXT NOT NULL UNIQUE,
@@ -71,11 +84,32 @@ CREATE TABLE IF NOT EXISTS transfers (
resolved_at TEXT
);
+CREATE TABLE IF NOT EXISTS staff_tokens (
+ id TEXT PRIMARY KEY,
+ event_id TEXT NOT NULL REFERENCES events(id),
+ token TEXT NOT NULL UNIQUE,
+ label TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ revoked_at TEXT
+);
+
CREATE INDEX IF NOT EXISTS idx_tickets_event ON tickets(event_id);
CREATE INDEX IF NOT EXISTS idx_transfers_event ON transfers(event_id);
CREATE INDEX IF NOT EXISTS idx_transfers_ticket ON transfers(ticket_id);
+CREATE INDEX IF NOT EXISTS idx_staff_event ON staff_tokens(event_id);
`;
+function tableColumns(db: DB, table: string): Set
{
+ const rows = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
+ return new Set(rows.map((row) => row.name));
+}
+
+function migrate(db: DB): void {
+ const tickets = tableColumns(db, 'tickets');
+ if (!tickets.has('email')) db.exec('ALTER TABLE tickets ADD COLUMN email TEXT');
+ if (!tickets.has('handle')) db.exec('ALTER TABLE tickets ADD COLUMN handle TEXT');
+}
+
export function openDatabase(filename = ':memory:'): DB {
if (filename !== ':memory:') {
mkdirSync(dirname(filename), { recursive: true });
@@ -87,6 +121,7 @@ export function openDatabase(filename = ':memory:'): DB {
db.pragma('journal_mode = WAL');
}
db.exec(SCHEMA);
+ migrate(db);
return db;
}
@@ -101,6 +136,8 @@ export function mapTicket(row: Record): TicketRow {
id: String(row.id),
event_id: String(row.event_id),
guest_name: String(row.guest_name),
+ email: row.email == null ? null : String(row.email),
+ handle: row.handle == null ? null : String(row.handle),
status: row.status as TicketStatus,
secret: asBuffer(row.secret),
access_token: String(row.access_token),
diff --git a/src/demo-event.ts b/src/demo-event.ts
new file mode 100644
index 0000000..494ef62
--- /dev/null
+++ b/src/demo-event.ts
@@ -0,0 +1,8 @@
+export const DEMO_EVENT_NAME = 'Breakpoint side-event dinner, London';
+
+export const DEMO_EVENT = {
+ name: DEMO_EVENT_NAME,
+ startsAt: '2026-11-16T19:00:00.000Z',
+ venue: 'Private room, Olympia London',
+ host: 'Nia Cole',
+};
diff --git a/src/protocol.ts b/src/protocol.ts
new file mode 100644
index 0000000..fc37b15
--- /dev/null
+++ b/src/protocol.ts
@@ -0,0 +1,113 @@
+import { stepAt } from './clock';
+import type { ScanResult } from './format';
+
+/** Truncated authentication tag. 16 bytes of HMAC-SHA256, hex-encoded in the payload. */
+export const MAC_BYTES = 16;
+
+const CODE_VERSION = 'pt1';
+const UUID_RE =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+export type ParsedPayload = {
+ ticketId: string;
+ step: number;
+ mac: Uint8Array;
+};
+
+export type ClaimTicket = {
+ id: string;
+ eventId: string;
+ guestName: string;
+ status: 'issued' | 'checked_in' | 'revoked';
+};
+
+/**
+ * Message is the UTF-8 encoding of `ticketId|decimalStep`.
+ * The pipe is the field boundary so the two values cannot be confused.
+ * The payload carries the ticket id and the step; it never carries the secret.
+ */
+export function macMessage(ticketId: string, step: number): string {
+ return `${ticketId}|${step}`;
+}
+
+export function bytesToHex(bytes: Uint8Array): string {
+ let hex = '';
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');
+ return hex;
+}
+
+export function formatCode(ticketId: string, step: number, mac: Uint8Array): string {
+ return `${CODE_VERSION}.${ticketId}.${step}.${bytesToHex(mac)}`;
+}
+
+export function parsePayload(raw: string): ParsedPayload | null {
+ if (typeof raw !== 'string' || raw.length > 256) return null;
+ const parts = raw.trim().split('.');
+ if (parts.length !== 4) return null;
+ const version = parts[0];
+ const ticketId = parts[1];
+ const stepText = parts[2];
+ const macHex = parts[3];
+ if (version !== CODE_VERSION || ticketId === undefined || stepText === undefined || macHex === undefined) {
+ return null;
+ }
+ if (!UUID_RE.test(ticketId)) return null;
+ if (!/^(0|[1-9][0-9]*)$/.test(stepText)) return null;
+ const step = Number(stepText);
+ if (!Number.isSafeInteger(step)) return null;
+ const hex = macHex.toLowerCase();
+ if (!/^[0-9a-f]{32}$/.test(hex)) return null;
+ const mac = new Uint8Array(MAC_BYTES);
+ for (let i = 0; i < MAC_BYTES; i += 1) mac[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
+ return { ticketId: ticketId.toLowerCase(), step, mac };
+}
+
+/** A code is live for the current step and one step of clock skew on either side. */
+export function stepWithinWindow(codeStep: number, nowMs: number): boolean {
+ return Math.abs(codeStep - stepAt(nowMs)) <= 1;
+}
+
+/**
+ * Door decision before the ticket is claimed.
+ * Order: signature, time window, event. A stale code is expired even if the
+ * ticket was already used, so a screenshot is not described as a replay.
+ * Returns null when the door should try to claim the ticket.
+ */
+export function rejectBeforeClaim(input: {
+ macOk: boolean;
+ inWindow: boolean;
+ eventMatches: boolean;
+}): ScanResult | null {
+ if (!input.macOk) return { result: 'reject', reason: 'invalid_code' };
+ if (!input.inWindow) return { result: 'reject', reason: 'expired' };
+ if (!input.eventMatches) return { result: 'reject', reason: 'wrong_event' };
+ return null;
+}
+
+/**
+ * Door decision while the ticket row is locked for check-in.
+ * The signature and event are read again so a transfer that rotated the
+ * secret in between cannot be admitted. Returns null when the row may flip
+ * from issued to checked_in.
+ */
+export function rejectAtClaim(input: {
+ present: boolean;
+ macOk: boolean;
+ eventMatches: boolean;
+ status: ClaimTicket['status'] | null;
+}): ScanResult | null {
+ if (!input.present || !input.macOk) return { result: 'reject', reason: 'invalid_code' };
+ if (!input.eventMatches) return { result: 'reject', reason: 'wrong_event' };
+ if (input.status === 'revoked') return { result: 'reject', reason: 'revoked' };
+ if (input.status !== 'issued') return { result: 'reject', reason: 'already_used' };
+ return null;
+}
+
+export function admitTicket(ticket: ClaimTicket): ScanResult {
+ return {
+ result: 'admit',
+ ticket_id: ticket.id,
+ guest_name: ticket.guestName,
+ event_id: ticket.eventId,
+ };
+}
diff --git a/src/service.ts b/src/service.ts
index 5feb98a..8eea3c5 100644
--- a/src/service.ts
+++ b/src/service.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import QRCode from 'qrcode';
import { STEP_MS, stepAt, stepEndsAt } from './clock';
import { compareMacs, computeMac, mintCode, newAccessToken, newSecret, parseCode, stepWithinWindow } from './codes';
+import { readGuestCsv, type CsvRowError } from './csv';
import {
getEvent,
getTicket,
@@ -9,12 +10,14 @@ import {
mapTicket,
type DB,
type EventRow,
+ type StaffRow,
type TicketRow,
type TicketStatus,
type TransferRow,
type TransferStatus,
} from './db';
import { type ScanResult } from './format';
+import { admitTicket, rejectAtClaim, rejectBeforeClaim } from './protocol';
const DUMMY_SECRET = newSecret();
@@ -31,12 +34,23 @@ export type PublicTicket = {
id: string;
event_id: string;
guest_name: string;
+ email: string | null;
+ handle: string | null;
status: TicketStatus;
created_at: string;
checked_in_at: string | null;
guest_path: string;
};
+export type PublicStaff = {
+ id: string;
+ event_id: string;
+ label: string;
+ door_path: string;
+ created_at: string;
+ revoked_at: string | null;
+};
+
export type PublicTransfer = {
id: string;
ticket_id: string;
@@ -81,6 +95,8 @@ function publicTicket(row: TicketRow): PublicTicket {
id: row.id,
event_id: row.event_id,
guest_name: row.guest_name,
+ email: row.email,
+ handle: row.handle,
status: row.status,
created_at: row.created_at,
checked_in_at: row.checked_in_at,
@@ -118,13 +134,15 @@ export function createEvent(
export function issueTicket(
db: DB,
- input: { eventId: string; guestName: string; nowMs: number },
+ input: { eventId: string; guestName: string; nowMs: number; email?: string | null; handle?: string | null },
): { ticket: PublicTicket; accessToken: string } | { error: 'not_found' } {
if (!getEvent(db, input.eventId)) return { error: 'not_found' };
const row: TicketRow = {
id: randomUUID(),
event_id: input.eventId,
guest_name: input.guestName,
+ email: input.email ?? null,
+ handle: input.handle ?? null,
status: 'issued',
secret: newSecret(),
access_token: newAccessToken(),
@@ -132,12 +150,41 @@ export function issueTicket(
checked_in_at: null,
};
db.prepare(
- `INSERT INTO tickets (id, event_id, guest_name, status, secret, access_token, created_at, checked_in_at)
- VALUES (@id, @event_id, @guest_name, @status, @secret, @access_token, @created_at, @checked_in_at)`,
+ `INSERT INTO tickets (id, event_id, guest_name, email, handle, status, secret, access_token, created_at, checked_in_at)
+ VALUES (@id, @event_id, @guest_name, @email, @handle, @status, @secret, @access_token, @created_at, @checked_in_at)`,
).run(row);
return { ticket: publicTicket(row), accessToken: row.access_token };
}
+export type ImportGuestsResult =
+ | { ok: true; created: PublicTicket[]; errors: CsvRowError[] }
+ | { ok: false; error: 'not_found' | 'too_large' | 'missing_name_column' | 'duplicate_column' | 'too_many_rows' };
+
+export function importGuests(
+ db: DB,
+ input: { eventId: string; csv: string; nowMs: number },
+): ImportGuestsResult {
+ if (!getEvent(db, input.eventId)) return { ok: false, error: 'not_found' };
+ const read = readGuestCsv(input.csv);
+ if (!read.ok) return { ok: false, error: read.error };
+ const insert = db.transaction((guests: typeof read.guests) => {
+ const created: PublicTicket[] = [];
+ for (const guest of guests) {
+ const issued = issueTicket(db, {
+ eventId: input.eventId,
+ guestName: guest.name,
+ email: guest.email,
+ handle: guest.handle,
+ nowMs: input.nowMs,
+ });
+ if ('error' in issued) throw new Error('event missing during import');
+ created.push(issued.ticket);
+ }
+ return created;
+ });
+ return { ok: true, created: insert(read.guests), errors: read.errors };
+}
+
export function listTickets(db: DB, eventId: string): PublicTicket[] | null {
if (!getEvent(db, eventId)) return null;
const rows = db
@@ -225,7 +272,7 @@ export function approveTransfer(db: DB, transferId: string, nowMs: number): Appr
const updated = db
.prepare(
`UPDATE tickets
- SET guest_name = ?, secret = ?, access_token = ?
+ SET guest_name = ?, secret = ?, access_token = ?, email = NULL, handle = NULL
WHERE id = ? AND status = 'issued'`,
)
.run(transfer.to_name, secret, accessToken, ticket.id);
@@ -291,23 +338,26 @@ export function scanCode(db: DB, input: { eventId: string; code: string; nowMs:
const ticket = getTicket(db, parsed.ticketId);
const expected = computeMac(ticket?.secret ?? DUMMY_SECRET, parsed.ticketId, parsed.step);
- if (!ticket || !compareMacs(expected, parsed.mac)) return { result: 'reject', reason: 'invalid_code' };
-
- if (!stepWithinWindow(parsed.step, input.nowMs)) {
- return { result: 'reject', reason: 'expired' };
- }
- if (ticket.event_id !== input.eventId) {
- return { result: 'reject', reason: 'wrong_event' };
- }
+ const macOk = Boolean(ticket) && compareMacs(expected, parsed.mac);
+ const early = rejectBeforeClaim({
+ macOk,
+ inWindow: stepWithinWindow(parsed.step, input.nowMs),
+ eventMatches: ticket?.event_id === input.eventId,
+ });
+ if (early) return early;
+ if (!ticket) return { result: 'reject', reason: 'invalid_code' };
const claim = db.transaction((): ScanResult => {
const current = getTicket(db, ticket.id);
- if (!current) return { result: 'reject', reason: 'invalid_code' };
- const lockedMac = computeMac(current.secret, current.id, parsed.step);
- if (!compareMacs(lockedMac, parsed.mac)) return { result: 'reject', reason: 'invalid_code' };
- if (current.event_id !== input.eventId) return { result: 'reject', reason: 'wrong_event' };
- if (current.status === 'revoked') return { result: 'reject', reason: 'revoked' };
- if (current.status !== 'issued') return { result: 'reject', reason: 'already_used' };
+ const lockedMac = computeMac(current?.secret ?? DUMMY_SECRET, parsed.ticketId, parsed.step);
+ const lockedOk = Boolean(current) && compareMacs(lockedMac, parsed.mac);
+ const blocked = rejectAtClaim({
+ present: Boolean(current),
+ macOk: lockedOk,
+ eventMatches: current?.event_id === input.eventId,
+ status: current?.status ?? null,
+ });
+ if (blocked || !current) return blocked ?? { result: 'reject', reason: 'invalid_code' };
const info = db
.prepare(
`UPDATE tickets SET status = 'checked_in', checked_in_at = ?
@@ -319,12 +369,12 @@ export function scanCode(db: DB, input: { eventId: string; code: string; nowMs:
if (again?.status === 'revoked') return { result: 'reject', reason: 'revoked' };
return { result: 'reject', reason: 'already_used' };
}
- return {
- result: 'admit',
- ticket_id: current.id,
- guest_name: current.guest_name,
- event_id: current.event_id,
- };
+ return admitTicket({
+ id: current.id,
+ eventId: current.event_id,
+ guestName: current.guest_name,
+ status: current.status,
+ });
});
return claim.immediate();
}
@@ -332,3 +382,93 @@ export function scanCode(db: DB, input: { eventId: string; code: string; nowMs:
export function snapshotTicket(db: DB, ticketId: string): TicketRow | null {
return getTicket(db, ticketId);
}
+
+function publicStaff(row: StaffRow): PublicStaff {
+ return {
+ id: row.id,
+ event_id: row.event_id,
+ label: row.label,
+ door_path: `/door/s/${row.token}`,
+ created_at: row.created_at,
+ revoked_at: row.revoked_at,
+ };
+}
+
+function getStaffByToken(db: DB, token: string): StaffRow | null {
+ const row = db.prepare('SELECT * FROM staff_tokens WHERE token = ?').get(token) as StaffRow | undefined;
+ return row ?? null;
+}
+
+export function createStaffToken(
+ db: DB,
+ input: { eventId: string; label: string; nowMs: number },
+): PublicStaff | { error: 'not_found' } {
+ if (!getEvent(db, input.eventId)) return { error: 'not_found' };
+ const row: StaffRow = {
+ id: randomUUID(),
+ event_id: input.eventId,
+ token: newAccessToken(),
+ label: input.label,
+ created_at: iso(input.nowMs),
+ revoked_at: null,
+ };
+ db.prepare(
+ `INSERT INTO staff_tokens (id, event_id, token, label, created_at, revoked_at)
+ VALUES (@id, @event_id, @token, @label, @created_at, @revoked_at)`,
+ ).run(row);
+ return publicStaff(row);
+}
+
+export function listStaff(db: DB, eventId: string): PublicStaff[] | null {
+ if (!getEvent(db, eventId)) return null;
+ const rows = db
+ .prepare('SELECT * FROM staff_tokens WHERE event_id = ? ORDER BY created_at ASC')
+ .all(eventId) as StaffRow[];
+ return rows.map(publicStaff);
+}
+
+export function revokeStaffToken(
+ db: DB,
+ staffId: string,
+ nowMs: number,
+): PublicStaff | { error: 'not_found' | 'not_revocable' } {
+ const existing = db.prepare('SELECT * FROM staff_tokens WHERE id = ?').get(staffId) as StaffRow | undefined;
+ if (!existing) return { error: 'not_found' };
+ if (existing.revoked_at) return { error: 'not_revocable' };
+ const info = db
+ .prepare(`UPDATE staff_tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL`)
+ .run(iso(nowMs), staffId);
+ if (info.changes !== 1) return { error: 'not_revocable' };
+ const updated = db.prepare('SELECT * FROM staff_tokens WHERE id = ?').get(staffId) as StaffRow | undefined;
+ if (!updated) return { error: 'not_found' };
+ return publicStaff(updated);
+}
+
+export type StaffSession = {
+ label: string;
+ event: PublicEvent;
+};
+
+export function staffSession(db: DB, token: string): StaffSession | null {
+ const staff = getStaffByToken(db, token);
+ if (!staff || staff.revoked_at) return null;
+ const event = getEvent(db, staff.event_id);
+ if (!event) return null;
+ return { label: staff.label, event: publicEvent(event) };
+}
+
+/**
+ * Scan with a door-staff token. The event is the one on the token.
+ * A different event id is rejected without claiming any ticket.
+ */
+export function scanWithStaff(
+ db: DB,
+ input: { token: string; code: string; nowMs: number; eventId?: string | null },
+): { ok: true; scan: ScanResult } | { ok: false; error: 'unauthorized' } {
+ const staff = getStaffByToken(db, input.token);
+ if (!staff || staff.revoked_at) return { ok: false, error: 'unauthorized' };
+ if (input.eventId && input.eventId !== staff.event_id) {
+ return { ok: true, scan: { result: 'reject', reason: 'wrong_event' } };
+ }
+ return { ok: true, scan: scanCode(db, { eventId: staff.event_id, code: input.code, nowMs: input.nowMs }) };
+}
diff --git a/tests/browser-store.test.ts b/tests/browser-store.test.ts
new file mode 100644
index 0000000..5b18438
--- /dev/null
+++ b/tests/browser-store.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+import { STEP_MS, stepAt } from '../src/clock';
+import { computeMac, mintCode } from '../src/codes';
+import { DEMO_EVENT_NAME } from '../src/demo-event';
+import { createDoorStore, hmacTag, memoryKv } from '../web-demo/store';
+
+const NOW = 1_780_000_000_000;
+
+describe('browser door store', () => {
+ it('uses the same HMAC tag as the server', async () => {
+ const secret = new Uint8Array(32);
+ crypto.getRandomValues(secret);
+ const ticketId = crypto.randomUUID();
+ const web = await hmacTag(secret, ticketId, 42);
+ const node = computeMac(Buffer.from(secret), ticketId, 42);
+ expect(Buffer.from(web).equals(node)).toBe(true);
+ });
+
+ it('seeds the Breakpoint dinner and imports good rows while reporting bad ones', () => {
+ const store = createDoorStore(memoryKv(), NOW);
+ expect(store.dinner().name).toBe(DEMO_EVENT_NAME);
+ const csv = `name,email,handle
+Amira Shah,amira@example.com,@amira
+,missing@example.com,@no
+Bob,not-an-email,@bob
+`;
+ const imported = store.importCsv(store.dinner().id, csv, NOW);
+ expect(imported.ok).toBe(true);
+ if (!imported.ok) return;
+ expect(imported.created.map((ticket) => ticket.guestName)).toEqual(['Amira Shah']);
+ expect(imported.errors.map((error) => error.reason)).toEqual(['Name is required', 'Email is not valid']);
+ expect(store.tickets(store.dinner().id)).toHaveLength(1);
+ const again = createDoorStore(memoryKv(), NOW);
+ again.importCsv(again.dinner().id, csv, NOW);
+ const saved = memoryKv();
+ const first = createDoorStore(saved, NOW);
+ first.importCsv(first.dinner().id, 'name\nNora Blake\n', NOW);
+ const reloaded = createDoorStore(saved, NOW);
+ expect(reloaded.tickets(reloaded.dinner().id).map((ticket) => ticket.guestName)).toEqual(['Nora Blake']);
+ });
+
+ it('admits a server-minted code once, rejects the replay, and rejects a stale code', async () => {
+ const store = createDoorStore(memoryKv(), NOW);
+ const imported = store.importCsv(store.dinner().id, 'name\nAmira Shah\nJonah Ellison\n', NOW);
+ if (!imported.ok) throw new Error('import failed');
+ const amira = imported.created[0];
+ const jonah = imported.created[1];
+ if (!amira || !jonah) throw new Error('missing guests');
+ const secret = store.secretOf(amira.id);
+ if (!secret) throw new Error('missing secret');
+ const live = mintCode(Buffer.from(secret), amira.id, stepAt(NOW));
+ expect(await store.scan(live, NOW)).toMatchObject({ result: 'admit', guest_name: 'Amira Shah' });
+ expect(await store.scan(live, NOW)).toEqual({ result: 'reject', reason: 'already_used' });
+ expect(store.tickets(store.dinner().id).find((ticket) => ticket.id === amira.id)?.status).toBe('checked_in');
+
+ const stale = await store.codeAt(jonah.id, stepAt(NOW) - 3);
+ if (!stale) throw new Error('missing stale code');
+ expect(await store.scan(stale, NOW)).toEqual({ result: 'reject', reason: 'expired' });
+ expect(store.tickets(store.dinner().id).find((ticket) => ticket.id === jonah.id)?.status).toBe('issued');
+ const stillLive = await store.codeAt(jonah.id, stepAt(NOW));
+ if (!stillLive) throw new Error('missing live code');
+ expect((await store.scan(stillLive, NOW)).result).toBe('admit');
+ });
+
+ it('does not check in a ticket from another event', async () => {
+ const store = createDoorStore(memoryKv(), NOW);
+ const other = store.createEvent({
+ name: 'Somewhere else',
+ startsAt: '2026-11-17T19:00:00.000Z',
+ venue: 'Elsewhere',
+ host: 'Nia',
+ });
+ const imported = store.importCsv(other.id, 'name\nOutside Guest\n', NOW);
+ if (!imported.ok || !imported.created[0]) throw new Error('import failed');
+ const code = await store.codeAt(imported.created[0].id, stepAt(NOW));
+ if (!code) throw new Error('missing code');
+ expect(await store.scan(code, NOW)).toEqual({ result: 'reject', reason: 'wrong_event' });
+ expect(store.tickets(other.id)[0]?.status).toBe('issued');
+ });
+
+ it('keeps the old code dead until the host approves a transfer, then rotates it', async () => {
+ const store = createDoorStore(memoryKv(), NOW);
+ const imported = store.importCsv(store.dinner().id, 'name,email\nPriya Raman,priya@example.com\n', NOW);
+ if (!imported.ok || !imported.created[0]) throw new Error('import failed');
+ const ticket = imported.created[0];
+ const before = await store.guestPass(ticket.id, NOW);
+ const requested = store.requestTransfer(ticket.id, 'Mina Patel', NOW);
+ expect(requested.ok).toBe(true);
+ const waiting = await store.guestPass(ticket.id, NOW);
+ expect(waiting?.guestName).toBe('Priya Raman');
+ expect(waiting?.code).toBe(before?.code);
+ expect(waiting?.pendingTransfer?.toName).toBe('Mina Patel');
+ if (!requested.ok) return;
+ const oldToken = ticket.accessToken;
+ const approved = store.approveTransfer(requested.transfer.id, NOW + 10);
+ expect(approved.ok).toBe(true);
+ if (!approved.ok) return;
+ expect(approved.ticket.guestName).toBe('Mina Patel');
+ expect(approved.ticket.email).toBeNull();
+ expect(approved.ticket.accessToken).not.toBe(oldToken);
+ expect(await store.guestPassByToken(oldToken, NOW + 10)).toBeNull();
+ expect(await store.scan(before?.code ?? '', NOW + 10)).toEqual({ result: 'reject', reason: 'invalid_code' });
+ const fresh = await store.guestPass(ticket.id, NOW + STEP_MS);
+ expect(fresh?.guestName).toBe('Mina Patel');
+ expect(fresh?.code).toBeTruthy();
+ expect(fresh?.code).not.toBe(before?.code);
+ expect(await store.scan(fresh?.code ?? '', NOW + STEP_MS)).toMatchObject({
+ result: 'admit',
+ guest_name: 'Mina Patel',
+ });
+ });
+});
diff --git a/tests/import.test.ts b/tests/import.test.ts
new file mode 100644
index 0000000..bde208a
--- /dev/null
+++ b/tests/import.test.ts
@@ -0,0 +1,115 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import { createEvent } from '../src/service';
+import { hostJson, setup, T0 } from './helpers';
+
+const CSV = `name,email,handle
+Ada Lovelace,ada@example.com,@ada
+"Hopper, Grace",grace@example.com,@grace
+,missing@example.com,@nope
+${'N'.repeat(121)},long@example.com,@long
+Bob,not-an-email,@bob
+Cara,cara@example.com,bad handle!
+Priya Raman,,@priya
+`;
+
+describe('csv import', () => {
+ it('creates named tickets and reports bad rows', async () => {
+ const ctx = setup();
+ const created = await hostJson(ctx.app, '/api/host/events', {
+ name: 'Dinner',
+ starts_at: '2026-11-16T19:00:00.000Z',
+ venue: 'Olympia',
+ host: 'Nia',
+ });
+ const eventId = created.json.event.id as string;
+ const imported = await hostJson(ctx.app, `/api/host/events/${eventId}/import`, { csv: CSV });
+ expect(imported.status).toBe(200);
+ expect(imported.json.created.map((ticket: { guest_name: string }) => ticket.guest_name)).toEqual([
+ 'Ada Lovelace',
+ 'Hopper, Grace',
+ 'Priya Raman',
+ ]);
+ expect(imported.json.created[0].email).toBe('ada@example.com');
+ expect(imported.json.created[0].handle).toBe('@ada');
+ expect(imported.json.created[2].email).toBeNull();
+ expect(imported.json.errors).toEqual([
+ { line: 4, reason: 'Name is required' },
+ { line: 5, reason: 'Name is too long' },
+ { line: 6, reason: 'Email is not valid' },
+ { line: 7, reason: 'Handle is not valid' },
+ ]);
+ const list = await hostJson(ctx.app, `/api/host/events/${eventId}/tickets`);
+ expect(list.json.tickets).toHaveLength(3);
+ ctx.close();
+ });
+
+ it('accepts a header with the name column elsewhere and a file with no header', async () => {
+ const ctx = setup();
+ const event = createEvent(ctx.db, {
+ name: 'Dinner',
+ startsAt: '2026-11-16T19:00:00.000Z',
+ venue: 'Olympia',
+ host: 'Nia',
+ nowMs: T0,
+ });
+ const swapped = await hostJson(ctx.app, `/api/host/events/${event.id}/import`, {
+ csv: 'email,name\nleo@example.com,Leo Martins\n',
+ });
+ expect(swapped.status).toBe(200);
+ expect(swapped.json.created[0].guest_name).toBe('Leo Martins');
+ expect(swapped.json.created[0].email).toBe('leo@example.com');
+ const positional = await hostJson(ctx.app, `/api/host/events/${event.id}/import`, {
+ csv: 'Nora Blake\n',
+ });
+ expect(positional.json.created[0].guest_name).toBe('Nora Blake');
+ expect(positional.json.created[0].email).toBeNull();
+ expect(positional.json.created[0].handle).toBeNull();
+ ctx.close();
+ });
+
+ it('rejects a header that has no name column and does not issue tickets', async () => {
+ const ctx = setup();
+ const event = createEvent(ctx.db, {
+ name: 'Dinner',
+ startsAt: '2026-11-16T19:00:00.000Z',
+ venue: 'Olympia',
+ host: 'Nia',
+ nowMs: T0,
+ });
+ const missing = await hostJson(ctx.app, `/api/host/events/${event.id}/import`, {
+ csv: 'email,handle\nada@example.com,@ada\n',
+ });
+ expect(missing.status).toBe(400);
+ expect(missing.json.error).toBe('missing_name_column');
+ const list = await hostJson(ctx.app, `/api/host/events/${event.id}/tickets`);
+ expect(list.json.tickets).toHaveLength(0);
+ const denied = await ctx.app.request(`/api/host/events/${event.id}/import`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ csv: 'name\nAda\n' }),
+ });
+ expect(denied.status).toBe(401);
+ ctx.close();
+ });
+
+ it('imports the Breakpoint sample list', async () => {
+ const ctx = setup();
+ const event = createEvent(ctx.db, {
+ name: 'Dinner',
+ startsAt: '2026-11-16T19:00:00.000Z',
+ venue: 'Olympia',
+ host: 'Nia',
+ nowMs: T0,
+ });
+ const csv = readFileSync(new URL('../samples/breakpoint-guests.csv', import.meta.url), 'utf8');
+ const imported = await hostJson(ctx.app, `/api/host/events/${event.id}/import`, { csv });
+ expect(imported.status).toBe(200);
+ expect(imported.json.errors).toEqual([]);
+ expect(imported.json.created).toHaveLength(12);
+ expect(imported.json.created[0].guest_name).toBe('Amira Shah');
+ expect(imported.json.created[4].guest_name).toBe('Nora Blake');
+ expect(imported.json.created[4].email).toBeNull();
+ ctx.close();
+ });
+});
diff --git a/tests/staff.test.ts b/tests/staff.test.ts
new file mode 100644
index 0000000..5efe12f
--- /dev/null
+++ b/tests/staff.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import { stepAt } from '../src/clock';
+import { mintCode } from '../src/codes';
+import { createEvent, issueTicket, snapshotTicket } from '../src/service';
+import { HOST, hostJson, seed, setup, T0 } from './helpers';
+
+function codeFor(ctx: ReturnType, ticketId: string, step = stepAt(T0)): string {
+ const row = snapshotTicket(ctx.db, ticketId);
+ if (!row) throw new Error('missing ticket');
+ return mintCode(row.secret, row.id, step);
+}
+
+describe('door staff', () => {
+ it('can scan its own event, cannot list guests, and cannot scan another event', async () => {
+ const ctx = setup();
+ const { event, ticket } = seed(ctx.db);
+ const other = createEvent(ctx.db, {
+ name: 'Other dinner',
+ startsAt: '2026-11-17T19:00:00.000Z',
+ venue: 'Elsewhere',
+ host: 'Nia',
+ nowMs: T0,
+ });
+ const outsider = issueTicket(ctx.db, { eventId: other.id, guestName: 'Outside Guest', nowMs: T0 });
+ if ('error' in outsider) throw new Error(outsider.error);
+
+ const created = await hostJson(ctx.app, `/api/host/events/${event.id}/staff`, { label: 'Front door' });
+ expect(created.status).toBe(201);
+ const doorPath = created.json.staff.door_path as string;
+ expect(doorPath).toMatch(/^\/door\/s\//);
+ const token = doorPath.slice('/door/s/'.length);
+
+ const page = await ctx.app.request(doorPath);
+ expect(page.status).toBe(200);
+
+ const admitted = await ctx.app.request(`/api/staff/${token}/scan`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: codeFor(ctx, ticket.id) }),
+ });
+ expect(await admitted.json()).toMatchObject({ result: 'admit', guest_name: 'Ada Lovelace' });
+
+ const replay = await ctx.app.request(`/api/staff/${token}/scan`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: codeFor(ctx, ticket.id) }),
+ });
+ expect(await replay.json()).toEqual({ result: 'reject', reason: 'already_used' });
+
+ const list = await ctx.app.request(`/api/host/events/${event.id}/tickets`, {
+ headers: { authorization: `Bearer ${token}` },
+ });
+ expect(list.status).toBe(401);
+ const imported = await ctx.app.request(`/api/host/events/${event.id}/import`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ csv: 'name\nSomeone\n' }),
+ });
+ expect(imported.status).toBe(401);
+
+ const session = await ctx.app.request(`/api/staff/${token}`);
+ const sessionBody = await session.json();
+ expect(session.status).toBe(200);
+ expect(sessionBody.event.id).toBe(event.id);
+ expect(JSON.stringify(sessionBody)).not.toContain('Ada Lovelace');
+ expect(JSON.stringify(sessionBody)).not.toContain('guest_name');
+
+ const wrong = await ctx.app.request(`/api/staff/${token}/scan`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: codeFor(ctx, outsider.ticket.id) }),
+ });
+ expect(await wrong.json()).toEqual({ result: 'reject', reason: 'wrong_event' });
+ expect(snapshotTicket(ctx.db, outsider.ticket.id)?.status).toBe('issued');
+
+ const fresh = issueTicket(ctx.db, { eventId: event.id, guestName: 'Second Guest', nowMs: T0 });
+ if ('error' in fresh) throw new Error(fresh.error);
+ const mismatched = await ctx.app.request(`/api/staff/${token}/scan`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: codeFor(ctx, fresh.ticket.id), event_id: other.id }),
+ });
+ expect(await mismatched.json()).toEqual({ result: 'reject', reason: 'wrong_event' });
+ expect(snapshotTicket(ctx.db, fresh.ticket.id)?.status).toBe('issued');
+
+ const hostList = await ctx.app.request(`/api/host/events/${event.id}/tickets`, {
+ headers: { authorization: `Bearer ${HOST}` },
+ });
+ expect(hostList.status).toBe(200);
+
+ const revoked = await hostJson(ctx.app, `/api/host/staff/${created.json.staff.id}/revoke`, {});
+ expect(revoked.status).toBe(200);
+ const dead = await ctx.app.request(`/api/staff/${token}/scan`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ code: codeFor(ctx, fresh.ticket.id) }),
+ });
+ expect(dead.status).toBe(401);
+ expect(snapshotTicket(ctx.db, fresh.ticket.id)?.status).toBe('issued');
+ ctx.close();
+ });
+});
diff --git a/tsconfig.json b/tsconfig.json
index 1c68734..f490547 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -14,7 +14,7 @@
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"types": ["node"],
- "lib": ["ES2022"]
+ "lib": ["ES2022", "DOM"]
},
- "include": ["src", "scripts", "tests"]
+ "include": ["src", "scripts", "tests", "web-demo"]
}
diff --git a/web-demo/index.html b/web-demo/index.html
new file mode 100644
index 0000000..611f21f
--- /dev/null
+++ b/web-demo/index.html
@@ -0,0 +1,86 @@
+
+
+
+
+
+
+
+ Breakpoint side-event door
+
+
+
+
+ Import the list, open a ticket, then scan it here. A second scan is rejected. A 15-second-old code is rejected. A transfer waits until the host approves it.
+
+
+
+ Host desk
+
+
+ Import sample guest list
+ CSV file
+
+
+
+
+
+
+ Transfers
+
+
+
+ Guest ticket
+ Choose a guest
+
+
+
+
+
+
+
+
+ New code in – s
+
+
+
+
+ Door
+ Scanner
+
+
Ready
+
Scan a live code
+
+
+
Scan the ticket on this screen
+
Scan a 15-second-old code
+
Use the camera
+
+
+
+
+
+
+
+
+
diff --git a/web-demo/main.ts b/web-demo/main.ts
new file mode 100644
index 0000000..f2c9920
--- /dev/null
+++ b/web-demo/main.ts
@@ -0,0 +1,374 @@
+import QRCode from 'qrcode';
+import sampleCsv from '../samples/breakpoint-guests.csv?raw';
+import { stepAt } from '../src/clock';
+import { REJECT_LABEL, type ScanResult } from '../src/format';
+import { createDoorStore, memoryKv, type GuestPass, type Kv } from './store';
+
+const ring = document.querySelector('#ring');
+const radius = Number(ring?.getAttribute('r') ?? 54);
+const circumference = 2 * Math.PI * radius;
+if (ring) ring.style.strokeDasharray = `${circumference} ${circumference}`;
+
+const store = createDoorStore(browserKv());
+let selectedId = '';
+let pass: GuestPass | null = null;
+let scanning = false;
+let queuedCode: string | null | undefined;
+let camera: import('html5-qrcode').Html5Qrcode | null = null;
+
+function browserKv(): Kv {
+ try {
+ const probe = 'breakpoint-door-probe';
+ localStorage.setItem(probe, '1');
+ localStorage.removeItem(probe);
+ return {
+ getItem: (key) => localStorage.getItem(key),
+ setItem: (key, value) => localStorage.setItem(key, value),
+ removeItem: (key) => localStorage.removeItem(key),
+ };
+ } catch {
+ return memoryKv();
+ }
+}
+
+function note(message: string): void {
+ const el = document.querySelector('#note');
+ if (el) el.textContent = message;
+}
+
+function showScan(result: ScanResult): void {
+ const box = document.querySelector('#result');
+ const title = box?.querySelector('.result-title');
+ const detail = box?.querySelector('.result-detail');
+ if (!box || !title || !detail) return;
+ if (result.result === 'admit') {
+ box.className = 'result admit';
+ title.textContent = 'ADMIT';
+ detail.textContent = result.guest_name;
+ return;
+ }
+ box.className = 'result reject';
+ title.textContent = 'REJECTED';
+ detail.textContent = REJECT_LABEL[result.reason];
+}
+
+async function drawTicket(): Promise {
+ const nameEl = document.querySelector('#guest-name');
+ const statusEl = document.querySelector('#guest-status');
+ const pendingEl = document.querySelector('#pending');
+ const countdown = document.querySelector('#countdown');
+ const form = document.querySelector('#transfer-form');
+ const img = document.querySelector('#qr');
+ if (!nameEl || !statusEl || !pendingEl || !countdown || !form || !img) return;
+ if (!selectedId) {
+ pass = null;
+ nameEl.textContent = 'Choose a guest';
+ statusEl.textContent = '';
+ pendingEl.textContent = '';
+ countdown.hidden = true;
+ form.hidden = true;
+ img.hidden = true;
+ document.querySelector('.qr-stage')?.toggleAttribute('hidden', true);
+ return;
+ }
+ pass = await store.guestPass(selectedId, Date.now());
+ if (!pass) return;
+ nameEl.textContent = pass.guestName;
+ statusEl.textContent = pass.status === 'issued' ? 'Show this at the door' : pass.status === 'checked_in' ? 'Checked in' : 'Revoked';
+ countdown.hidden = pass.status !== 'issued';
+ form.hidden = pass.status !== 'issued';
+ document.querySelector('.qr-stage')?.toggleAttribute('hidden', pass.status !== 'issued');
+ pendingEl.textContent = pass.pendingTransfer
+ ? `Transfer to ${pass.pendingTransfer.toName} is waiting for the host. Nothing changes until they approve.`
+ : '';
+ if (pass.code) {
+ if (img.dataset.code !== pass.code) {
+ img.src = await QRCode.toDataURL(pass.code, { width: 360, margin: 1, errorCorrectionLevel: 'M' });
+ img.dataset.code = pass.code;
+ }
+ img.hidden = false;
+ } else {
+ img.hidden = true;
+ img.removeAttribute('src');
+ delete img.dataset.code;
+ }
+}
+
+function paintRing(): void {
+ const remainEl = document.querySelector('#remain');
+ if (!ring || !remainEl) return;
+ if (!pass || pass.status !== 'issued') {
+ ring.style.strokeDashoffset = String(circumference);
+ remainEl.textContent = '–';
+ return;
+ }
+ const remain = pass.stepEndsAt - Date.now();
+ const fraction = Math.max(0, Math.min(1, remain / pass.stepMs));
+ ring.style.strokeDashoffset = String(circumference * (1 - fraction));
+ ring.classList.toggle('urgent', remain < 1000);
+ remainEl.textContent = Math.max(0, remain / 1000).toFixed(1);
+}
+
+function renderLists(): void {
+ const event = store.dinner();
+ const meta = document.querySelector('#event-meta');
+ const title = document.querySelector('#event-name');
+ if (title) title.textContent = event.name;
+ if (meta) {
+ const when = new Date(event.startsAt).toLocaleString('en-GB', {
+ weekday: 'short',
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZone: 'Europe/London',
+ });
+ meta.textContent = `${event.venue} · ${when} · Host ${event.host}`;
+ }
+ const tickets = store.tickets(event.id);
+ const count = document.querySelector('#tally-count');
+ const label = document.querySelector('#tally-label');
+ const checked = tickets.filter((ticket) => ticket.status === 'checked_in').length;
+ if (count) count.textContent = String(checked);
+ if (label) label.textContent = `of ${tickets.length} checked in`;
+ const body = document.querySelector('#guests');
+ if (!body) return;
+ body.replaceChildren();
+ if (tickets.length === 0) {
+ const row = document.createElement('tr');
+ const cell = document.createElement('td');
+ cell.colSpan = 2;
+ cell.className = 'muted';
+ cell.textContent = 'No guests yet. Import the sample list.';
+ row.append(cell);
+ body.append(row);
+ }
+ for (const ticket of tickets) {
+ const row = document.createElement('tr');
+ row.className = ticket.id === selectedId ? 'guest selected' : 'guest';
+ const name = document.createElement('td');
+ name.textContent = ticket.guestName;
+ const extra = [ticket.email, ticket.handle].filter(Boolean).join(' · ');
+ if (extra) {
+ const sub = document.createElement('div');
+ sub.className = 'sub';
+ sub.textContent = extra;
+ name.append(sub);
+ }
+ const status = document.createElement('td');
+ const pill = document.createElement('span');
+ pill.className = `pill ${ticket.status}`;
+ pill.textContent = ticket.status === 'checked_in' ? 'checked in' : ticket.status === 'issued' ? 'not in yet' : 'revoked';
+ status.append(pill);
+ row.append(name, status);
+ row.addEventListener('click', () => {
+ selectedId = ticket.id;
+ void render();
+ });
+ body.append(row);
+ }
+ const transfers = document.querySelector('#transfers');
+ if (!transfers) return;
+ transfers.replaceChildren();
+ const pending = store.transfers(event.id).filter((transfer) => transfer.status === 'pending');
+ if (pending.length === 0) {
+ const empty = document.createElement('p');
+ empty.className = 'muted';
+ empty.textContent = 'No transfer is waiting.';
+ transfers.append(empty);
+ }
+ for (const transfer of pending) {
+ const row = document.createElement('div');
+ row.className = 'row';
+ const text = document.createElement('span');
+ text.textContent = `${transfer.fromName} → ${transfer.toName}`;
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'approve';
+ button.textContent = 'Approve transfer';
+ button.addEventListener('click', () => {
+ const result = store.approveTransfer(transfer.id, Date.now());
+ if (!result.ok) {
+ note(result.error);
+ return;
+ }
+ note(`Approved. ${result.ticket.guestName} now holds this ticket. The old code is dead.`);
+ showScanPlaceholder();
+ const detail = document.querySelector('#result .result-detail');
+ if (detail) detail.textContent = 'The new guest has a new code';
+ void render();
+ });
+ row.append(text, button);
+ transfers.append(row);
+ }
+}
+
+async function render(): Promise {
+ renderLists();
+ await drawTicket();
+ paintRing();
+}
+
+function reportImport(created: number, errors: Array<{ line: number; reason: string }>, failure = ''): void {
+ const report = document.querySelector('#import-report');
+ const list = document.querySelector('#import-errors');
+ if (!report || !list) return;
+ list.replaceChildren();
+ if (failure) {
+ report.textContent = failure;
+ return;
+ }
+ report.textContent = `${created} guests added. ${errors.length} rows need a fix.`;
+ for (const error of errors) {
+ const item = document.createElement('li');
+ item.textContent = `Line ${error.line}: ${error.reason}`;
+ list.append(item);
+ }
+}
+
+function importText(csv: string): void {
+ const result = store.importCsv(store.dinner().id, csv, Date.now());
+ if (!result.ok) {
+ reportImport(0, [], result.error.replaceAll('_', ' '));
+ return;
+ }
+ reportImport(result.created.length, result.errors);
+ const first = result.created[0];
+ if (first && !selectedId) selectedId = first.id;
+ note(result.errors.length ? 'Some rows were skipped.' : 'Guest list imported. Open a name to show their ticket.');
+ void render();
+}
+
+async function submitCode(code: string | null): Promise {
+ if (scanning) {
+ queuedCode = code;
+ return;
+ }
+ scanning = true;
+ if (camera) {
+ try { camera.pause(true); } catch { /* already paused */ }
+ window.setTimeout(() => {
+ if (!camera) return;
+ try { camera.resume(); } catch { /* camera stopped */ }
+ }, 1200);
+ }
+ try {
+ let next: string | null | undefined = code;
+ while (next !== undefined) {
+ const current = next;
+ queuedCode = undefined;
+ if (!current) showScan({ result: 'reject', reason: 'invalid_code' });
+ else showScan(await store.scan(current, Date.now()));
+ await render();
+ next = queuedCode;
+ queuedCode = undefined;
+ }
+ } finally {
+ scanning = false;
+ }
+}
+
+document.querySelector('#import-sample')?.addEventListener('click', () => {
+ importText(sampleCsv);
+});
+
+document.querySelector('#csv-file')?.addEventListener('change', async (event) => {
+ const input = event.currentTarget as HTMLInputElement;
+ const file = input.files?.[0];
+ if (!file) return;
+ importText(await file.text());
+ input.value = '';
+});
+
+document.querySelector('#transfer-form')?.addEventListener('submit', (event) => {
+ event.preventDefault();
+ const input = document.querySelector('#transfer-name');
+ if (!selectedId || !input) return;
+ const result = store.requestTransfer(selectedId, input.value, Date.now());
+ if (!result.ok) {
+ note(result.error.replaceAll('_', ' '));
+ return;
+ }
+ input.value = '';
+ note(`Transfer to ${result.transfer.toName} is waiting for approval.`);
+ void render();
+});
+
+document.querySelector('#scan-screen')?.addEventListener('click', () => {
+ if (pass?.status === 'issued' && pass.code) {
+ void submitCode(pass.code);
+ return;
+ }
+ if (!selectedId) {
+ void submitCode(null);
+ return;
+ }
+ void store.codeAt(selectedId, stepAt(Date.now())).then((code) => submitCode(code));
+});
+
+document.querySelector('#scan-stale')?.addEventListener('click', async () => {
+ if (!selectedId) return;
+ const stale = await store.codeAt(selectedId, stepAt(Date.now()) - 3);
+ await submitCode(stale);
+});
+
+document.querySelector('#camera')?.addEventListener('click', async () => {
+ const state = document.querySelector('#camera-state');
+ const button = document.querySelector('#camera');
+ if (!state || !button) return;
+ button.disabled = true;
+ try {
+ const { Html5Qrcode } = await import('html5-qrcode');
+ camera ??= new Html5Qrcode('reader');
+ await camera.start(
+ { facingMode: 'environment' },
+ { fps: 8, qrbox: { width: 220, height: 220 } },
+ (text) => { void submitCode(text); },
+ () => {},
+ );
+ state.textContent = 'Camera on';
+ } catch (error) {
+ button.disabled = false;
+ const message = error instanceof Error ? error.message : 'permission denied';
+ state.textContent = `Camera unavailable (${message}). Use the button above.`;
+ }
+});
+
+document.querySelector('#reset')?.addEventListener('click', () => {
+ store.reset();
+ selectedId = '';
+ pass = null;
+ reportImport(0, [], '');
+ const report = document.querySelector('#import-report');
+ if (report) report.textContent = '';
+ showScanPlaceholder();
+ note('Demo reset.');
+ void render();
+});
+
+function showScanPlaceholder(): void {
+ const box = document.querySelector('#result');
+ const title = box?.querySelector('.result-title');
+ const detail = box?.querySelector('.result-detail');
+ if (!box || !title || !detail) return;
+ box.className = 'result';
+ title.textContent = 'Ready';
+ detail.textContent = 'Scan a live code';
+}
+
+let refreshing = false;
+function frame(): void {
+ paintRing();
+ const due = pass?.status === 'issued' && pass.stepEndsAt - Date.now() <= 40;
+ if (due && !refreshing) {
+ refreshing = true;
+ void drawTicket().finally(() => {
+ refreshing = false;
+ });
+ }
+ requestAnimationFrame(frame);
+}
+
+void render();
+requestAnimationFrame(frame);
diff --git a/web-demo/raw.d.ts b/web-demo/raw.d.ts
new file mode 100644
index 0000000..3e27d47
--- /dev/null
+++ b/web-demo/raw.d.ts
@@ -0,0 +1,18 @@
+declare module '*.csv?raw' {
+ const content: string;
+ export default content;
+}
+
+declare module 'html5-qrcode' {
+ export class Html5Qrcode {
+ constructor(elementId: string);
+ start(
+ camera: { facingMode: string },
+ config: { fps: number; qrbox: { width: number; height: number } },
+ onScan: (text: string) => void,
+ onError: (error: string) => void,
+ ): Promise;
+ pause(pauseVideo?: boolean): void;
+ resume(): void;
+ }
+}
diff --git a/web-demo/store.ts b/web-demo/store.ts
new file mode 100644
index 0000000..01d3d09
--- /dev/null
+++ b/web-demo/store.ts
@@ -0,0 +1,384 @@
+import { STEP_MS, stepAt, stepEndsAt } from '../src/clock';
+import { readGuestCsv, cleanGuestName, type CsvRowError } from '../src/csv';
+import { DEMO_EVENT, DEMO_EVENT_NAME } from '../src/demo-event';
+import type { ScanResult } from '../src/format';
+import {
+ MAC_BYTES,
+ admitTicket,
+ formatCode,
+ macMessage,
+ parsePayload,
+ rejectAtClaim,
+ rejectBeforeClaim,
+ stepWithinWindow,
+} from '../src/protocol';
+
+const STORAGE_KEY = 'breakpoint-door-demo-v1';
+const DUMMY_SECRET = new Uint8Array(32);
+
+export type Kv = {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+};
+
+export type DemoEvent = {
+ id: string;
+ name: string;
+ startsAt: string;
+ venue: string;
+ host: string;
+ createdAt: string;
+};
+
+export type DemoTicket = {
+ id: string;
+ eventId: string;
+ guestName: string;
+ email: string | null;
+ handle: string | null;
+ status: 'issued' | 'checked_in' | 'revoked';
+ accessToken: string;
+ createdAt: string;
+ checkedInAt: string | null;
+};
+
+export type DemoTransfer = {
+ id: string;
+ ticketId: string;
+ eventId: string;
+ fromName: string;
+ toName: string;
+ status: 'pending' | 'approved' | 'denied';
+ createdAt: string;
+ resolvedAt: string | null;
+};
+
+export type GuestPass = {
+ ticketId: string;
+ guestName: string;
+ status: DemoTicket['status'];
+ event: DemoEvent;
+ pendingTransfer: { id: string; toName: string } | null;
+ step: number;
+ stepMs: number;
+ serverNow: number;
+ stepEndsAt: number;
+ code: string | null;
+};
+
+type TicketRecord = DemoTicket & { secret: string };
+
+type State = {
+ events: DemoEvent[];
+ tickets: TicketRecord[];
+ transfers: DemoTransfer[];
+};
+
+export type ImportOutcome =
+ | { ok: true; created: DemoTicket[]; errors: CsvRowError[] }
+ | { ok: false; error: 'not_found' | 'too_large' | 'missing_name_column' | 'duplicate_column' | 'too_many_rows' };
+
+export function memoryKv(): Kv {
+ const data = new Map();
+ return {
+ getItem: (key) => data.get(key) ?? null,
+ setItem: (key, value) => {
+ data.set(key, value);
+ },
+ removeItem: (key) => {
+ data.delete(key);
+ },
+ };
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+}
+
+function base64ToBytes(value: string): Uint8Array {
+ const binary = atob(value);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
+ return bytes;
+}
+
+function randomToken(): string {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return bytesToBase64(bytes).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
+}
+
+function randomSecret(): Uint8Array {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return bytes;
+}
+
+export async function hmacTag(secret: Uint8Array, ticketId: string, step: number): Promise {
+ const key = await crypto.subtle.importKey('raw', secret.slice(), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ const signed = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(macMessage(ticketId, step)));
+ return new Uint8Array(signed).slice(0, MAC_BYTES);
+}
+
+function tagsEqual(expected: Uint8Array, provided: Uint8Array): boolean {
+ if (expected.length !== provided.length) return false;
+ let diff = 0;
+ for (let index = 0; index < expected.length; index += 1) diff |= (expected[index] ?? 0) ^ (provided[index] ?? 0);
+ return diff === 0;
+}
+
+function toPublic(ticket: TicketRecord): DemoTicket {
+ return {
+ id: ticket.id,
+ eventId: ticket.eventId,
+ guestName: ticket.guestName,
+ email: ticket.email,
+ handle: ticket.handle,
+ status: ticket.status,
+ accessToken: ticket.accessToken,
+ createdAt: ticket.createdAt,
+ checkedInAt: ticket.checkedInAt,
+ };
+}
+
+function seedEvent(nowMs: number): DemoEvent {
+ return {
+ id: crypto.randomUUID(),
+ name: DEMO_EVENT.name,
+ startsAt: DEMO_EVENT.startsAt,
+ venue: DEMO_EVENT.venue,
+ host: DEMO_EVENT.host,
+ createdAt: new Date(nowMs).toISOString(),
+ };
+}
+
+function emptyState(nowMs: number): State {
+ return { events: [seedEvent(nowMs)], tickets: [], transfers: [] };
+}
+
+export type DoorStore = ReturnType;
+
+export function createDoorStore(kv: Kv, nowMs = Date.now()) {
+ let state = readState(kv, nowMs);
+
+ function save(): void {
+ kv.setItem(STORAGE_KEY, JSON.stringify(state));
+ }
+
+ function dinner(): DemoEvent {
+ const found = state.events.find((event) => event.name === DEMO_EVENT_NAME) ?? state.events[0];
+ if (!found) throw new Error('demo event missing');
+ return found;
+ }
+
+ function ticketById(id: string): TicketRecord | null {
+ return state.tickets.find((ticket) => ticket.id === id) ?? null;
+ }
+
+ save();
+
+ return {
+ dinner,
+ events(): DemoEvent[] {
+ return state.events.map((event) => ({ ...event }));
+ },
+ createEvent(input: { name: string; startsAt: string; venue: string; host: string }, at = nowMs): DemoEvent {
+ const event: DemoEvent = {
+ id: crypto.randomUUID(),
+ name: input.name,
+ startsAt: input.startsAt,
+ venue: input.venue,
+ host: input.host,
+ createdAt: new Date(at).toISOString(),
+ };
+ state.events.push(event);
+ save();
+ return { ...event };
+ },
+ tickets(eventId: string): DemoTicket[] {
+ return state.tickets.filter((ticket) => ticket.eventId === eventId).map(toPublic);
+ },
+ transfers(eventId: string): DemoTransfer[] {
+ return state.transfers.filter((transfer) => transfer.eventId === eventId).map((transfer) => ({ ...transfer }));
+ },
+ secretOf(ticketId: string): Uint8Array | null {
+ const ticket = ticketById(ticketId);
+ return ticket ? base64ToBytes(ticket.secret) : null;
+ },
+ importCsv(eventId: string, csv: string, at: number): ImportOutcome {
+ if (!state.events.some((event) => event.id === eventId)) return { ok: false, error: 'not_found' };
+ const read = readGuestCsv(csv);
+ if (!read.ok) return read;
+ const created: DemoTicket[] = [];
+ for (const guest of read.guests) {
+ const record: TicketRecord = {
+ id: crypto.randomUUID(),
+ eventId,
+ guestName: guest.name,
+ email: guest.email,
+ handle: guest.handle,
+ status: 'issued',
+ secret: bytesToBase64(randomSecret()),
+ accessToken: randomToken(),
+ createdAt: new Date(at).toISOString(),
+ checkedInAt: null,
+ };
+ state.tickets.push(record);
+ created.push(toPublic(record));
+ }
+ save();
+ return { ok: true, created, errors: read.errors };
+ },
+ async codeAt(ticketId: string, step: number): Promise {
+ const ticket = ticketById(ticketId);
+ if (!ticket) return null;
+ const mac = await hmacTag(base64ToBytes(ticket.secret), ticket.id, step);
+ return formatCode(ticket.id, step, mac);
+ },
+ async guestPass(ticketId: string, at: number): Promise {
+ const ticket = ticketById(ticketId);
+ if (!ticket) return null;
+ return passFor(ticket, at);
+ },
+ async guestPassByToken(accessToken: string, at: number): Promise {
+ const ticket = state.tickets.find((row) => row.accessToken === accessToken);
+ if (!ticket) return null;
+ return passFor(ticket, at);
+ },
+ async scan(code: string, at: number, eventId = dinner().id): Promise {
+ const parsed = parsePayload(code);
+ if (!parsed) return { result: 'reject', reason: 'invalid_code' };
+ const ticket = ticketById(parsed.ticketId);
+ const secret = ticket ? base64ToBytes(ticket.secret) : DUMMY_SECRET;
+ const mac = await hmacTag(secret, parsed.ticketId, parsed.step);
+ const macOk = Boolean(ticket) && tagsEqual(mac, parsed.mac);
+ const early = rejectBeforeClaim({
+ macOk,
+ inWindow: stepWithinWindow(parsed.step, at),
+ eventMatches: ticket?.eventId === eventId,
+ });
+ if (early) return early;
+ const current = ticketById(parsed.ticketId);
+ const lockedSecret = current ? base64ToBytes(current.secret) : DUMMY_SECRET;
+ const lockedMac = await hmacTag(lockedSecret, parsed.ticketId, parsed.step);
+ const blocked = rejectAtClaim({
+ present: Boolean(current),
+ macOk: Boolean(current) && tagsEqual(lockedMac, parsed.mac),
+ eventMatches: current?.eventId === eventId,
+ status: current?.status ?? null,
+ });
+ if (blocked || !current) return blocked ?? { result: 'reject', reason: 'invalid_code' };
+ current.status = 'checked_in';
+ current.checkedInAt = new Date(at).toISOString();
+ save();
+ return admitTicket({
+ id: current.id,
+ eventId: current.eventId,
+ guestName: current.guestName,
+ status: 'issued',
+ });
+ },
+ requestTransfer(
+ ticketId: string,
+ toName: string,
+ at: number,
+ ): { ok: true; transfer: DemoTransfer } | { ok: false; error: 'not_found' | 'not_transferable' | 'same_name' | 'pending_exists' | 'invalid_name' } {
+ const named = cleanGuestName(toName);
+ if (!named.ok) return { ok: false, error: 'invalid_name' };
+ const ticket = ticketById(ticketId);
+ if (!ticket) return { ok: false, error: 'not_found' };
+ if (ticket.status !== 'issued') return { ok: false, error: 'not_transferable' };
+ if (ticket.guestName === named.name) return { ok: false, error: 'same_name' };
+ if (state.transfers.some((transfer) => transfer.ticketId === ticket.id && transfer.status === 'pending')) {
+ return { ok: false, error: 'pending_exists' };
+ }
+ const transfer: DemoTransfer = {
+ id: crypto.randomUUID(),
+ ticketId: ticket.id,
+ eventId: ticket.eventId,
+ fromName: ticket.guestName,
+ toName: named.name,
+ status: 'pending',
+ createdAt: new Date(at).toISOString(),
+ resolvedAt: null,
+ };
+ state.transfers.push(transfer);
+ save();
+ return { ok: true, transfer: { ...transfer } };
+ },
+ approveTransfer(
+ transferId: string,
+ at: number,
+ ):
+ | { ok: true; transfer: DemoTransfer; ticket: DemoTicket }
+ | { ok: false; error: 'not_found' | 'not_pending' | 'not_transferable' } {
+ const transfer = state.transfers.find((row) => row.id === transferId);
+ if (!transfer) return { ok: false, error: 'not_found' };
+ if (transfer.status !== 'pending') return { ok: false, error: 'not_pending' };
+ const ticket = ticketById(transfer.ticketId);
+ if (!ticket || ticket.status !== 'issued') {
+ transfer.status = 'denied';
+ transfer.resolvedAt = new Date(at).toISOString();
+ save();
+ return { ok: false, error: 'not_transferable' };
+ }
+ ticket.guestName = transfer.toName;
+ ticket.email = null;
+ ticket.handle = null;
+ ticket.secret = bytesToBase64(randomSecret());
+ ticket.accessToken = randomToken();
+ transfer.status = 'approved';
+ transfer.resolvedAt = new Date(at).toISOString();
+ save();
+ return { ok: true, transfer: { ...transfer }, ticket: toPublic(ticket) };
+ },
+ reset(at = Date.now()): DemoEvent {
+ state = emptyState(at);
+ save();
+ return dinner();
+ },
+ };
+
+ async function passFor(ticket: TicketRecord, at: number): Promise {
+ const event = state.events.find((row) => row.id === ticket.eventId);
+ if (!event) throw new Error('ticket event missing');
+ const pending = state.transfers.find((transfer) => transfer.ticketId === ticket.id && transfer.status === 'pending');
+ const step = stepAt(at);
+ const code = ticket.status === 'issued' ? await hmacTag(base64ToBytes(ticket.secret), ticket.id, step).then((mac) => formatCode(ticket.id, step, mac)) : null;
+ return {
+ ticketId: ticket.id,
+ guestName: ticket.guestName,
+ status: ticket.status,
+ event: { ...event },
+ pendingTransfer: pending ? { id: pending.id, toName: pending.toName } : null,
+ step,
+ stepMs: STEP_MS,
+ serverNow: at,
+ stepEndsAt: stepEndsAt(step),
+ code,
+ };
+ }
+}
+
+function readState(kv: Kv, nowMs: number): State {
+ const raw = kv.getItem(STORAGE_KEY);
+ if (!raw) return emptyState(nowMs);
+ try {
+ const parsed = JSON.parse(raw) as Partial;
+ if (!Array.isArray(parsed.events) || !Array.isArray(parsed.tickets) || !Array.isArray(parsed.transfers)) {
+ return emptyState(nowMs);
+ }
+ const state: State = {
+ events: parsed.events as DemoEvent[],
+ tickets: parsed.tickets as TicketRecord[],
+ transfers: parsed.transfers as DemoTransfer[],
+ };
+ if (!state.events.some((event) => event.name === DEMO_EVENT_NAME)) state.events.unshift(seedEvent(nowMs));
+ return state;
+ } catch {
+ return emptyState(nowMs);
+ }
+}
diff --git a/web-demo/styles.css b/web-demo/styles.css
new file mode 100644
index 0000000..9034d26
--- /dev/null
+++ b/web-demo/styles.css
@@ -0,0 +1,193 @@
+:root {
+ color-scheme: dark;
+ --bg: #16130f;
+ --ink: #1c1915;
+ --paper: #f6f1e8;
+ --muted: #5e564c;
+ --line: #e2d8c8;
+ --good: #0f6b45;
+ --bad: #9d2b2b;
+ --lime: #e4ff6a;
+ font-family: Georgia, "Iowan Old Style", Palatino, serif;
+}
+
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+
+body {
+ margin: 0;
+ min-height: 100vh;
+ background:
+ radial-gradient(circle at top left, rgba(228, 255, 106, 0.08), transparent 24rem),
+ var(--bg);
+ color: var(--paper);
+}
+
+button, input { font: inherit; color: inherit; }
+
+button {
+ min-height: 44px;
+ border: 0;
+ border-radius: 999px;
+ padding: 0.55rem 1rem;
+ background: var(--ink);
+ color: var(--paper);
+ cursor: pointer;
+}
+
+button.secondary { background: transparent; color: var(--ink); border: 1px solid var(--line); }
+button.text { background: transparent; color: var(--lime); min-height: 0; padding: 0; }
+button:disabled { opacity: 0.5; cursor: not-allowed; }
+
+input[type="text"], input:not([type="file"]) {
+ width: 100%;
+ font-size: 16px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 0.6rem 0.7rem;
+ background: white;
+ color: var(--ink);
+}
+
+.topbar {
+ width: min(1180px, calc(100% - 1.5rem));
+ margin: 0 auto;
+ padding: 1.1rem 0 0.2rem;
+}
+
+.brand {
+ margin: 0 0 0.35rem;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ font-size: 0.75rem;
+ color: #c8bfb2;
+}
+
+.brand span { color: var(--lime); }
+
+h1 { margin: 0; font-size: clamp(1.7rem, 3vw, 2.5rem); font-weight: 600; letter-spacing: -0.03em; line-height: 1.05; }
+h2 { margin: 0; font-size: 1.35rem; font-weight: 600; }
+
+.meta, .how, .note, .foot { width: min(1180px, calc(100% - 1.5rem)); margin: 0.35rem auto 0; }
+.meta, .how { color: #d9d0c3; }
+.how { margin-top: 0.65rem; line-height: 1.4; }
+.note { min-height: 1.2rem; color: var(--lime); }
+.foot { padding: 0.4rem 0 1.4rem; }
+
+.workspace {
+ width: min(1180px, calc(100% - 1.5rem));
+ margin: 0.8rem auto 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.8rem;
+}
+
+.panel {
+ background: var(--paper);
+ color: var(--ink);
+ border-radius: 18px;
+ padding: 0.9rem 0.95rem 1rem;
+}
+
+.eyebrow {
+ margin: 0 0 0.35rem;
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ font-size: 0.72rem;
+ color: var(--bad);
+}
+
+.muted { color: var(--muted); }
+.stack { display: grid; gap: 0.55rem; }
+.row { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: end; }
+label { display: grid; gap: 0.25rem; font-size: 0.92rem; }
+.file input { font-size: 0.85rem; }
+
+.tally { display: flex; align-items: baseline; gap: 0.55rem; margin: 0.2rem 0 0.7rem; }
+#tally-count {
+ margin: 0;
+ font-size: 3.4rem;
+ line-height: 0.85;
+ font-variant-numeric: tabular-nums;
+}
+
+.report { min-height: 1.2rem; margin: 0.55rem 0 0.2rem; font-weight: 600; }
+#import-errors { margin: 0 0 0.4rem; padding-left: 1.1rem; color: var(--bad); }
+#import-errors:empty { display: none; }
+
+.table-wrap {
+ max-height: 332px;
+ overflow: auto;
+ border: 1px solid var(--line);
+ border-radius: 12px;
+}
+table { width: 100%; border-collapse: collapse; font-size: 0.95rem; }
+th, td { text-align: left; padding: 0.38rem 0.2rem; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { font-size: 0.72rem; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); position: sticky; top: 0; background: var(--paper); }
+tr.guest { cursor: pointer; }
+tr.guest.selected { background: #efe6c8; }
+.sub { color: var(--muted); font-size: 0.82rem; }
+.pill {
+ display: inline-block;
+ border-radius: 999px;
+ padding: 0.1rem 0.45rem;
+ border: 1px solid var(--line);
+ font-size: 0.78rem;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+.pill.checked_in { background: #e5f6ec; color: var(--good); border-color: #b7dfc6; }
+.pill.revoked { background: #fdeceb; color: var(--bad); border-color: #f0c7c2; }
+
+.qr-stage {
+ position: relative;
+ width: min(100%, 280px);
+ margin: 0.7rem auto 0;
+ aspect-ratio: 1;
+}
+.ring { position: absolute; inset: 0; width: 100%; height: 100%; transform: rotate(-90deg); }
+.ring-track, .ring-value { fill: none; stroke-width: 5; }
+.ring-track { stroke: var(--line); }
+.ring-value { stroke: var(--good); stroke-linecap: round; }
+.ring-value.urgent { stroke: var(--bad); }
+.qr-stage img {
+ position: absolute;
+ inset: 11%;
+ width: 78%;
+ height: 78%;
+ object-fit: contain;
+ background: white;
+}
+.countdown { text-align: center; font-variant-numeric: tabular-nums; font-size: 1.15rem; }
+.pending { min-height: 1.2rem; text-align: center; }
+
+.result {
+ margin: 0.4rem 0 0.8rem;
+ border-radius: 16px;
+ padding: 1rem 0.8rem 1.1rem;
+ text-align: center;
+ background: white;
+ border: 1px solid var(--line);
+}
+.result-title {
+ margin: 0;
+ font-size: clamp(2.8rem, 8vw, 4.6rem);
+ line-height: 0.9;
+ letter-spacing: 0.04em;
+}
+.result-detail { margin: 0.45rem 0 0; font-size: 1.35rem; }
+.result.admit { background: var(--good); color: #f4fff8; border-color: var(--good); }
+.result.reject { background: var(--bad); color: #fff6f4; border-color: var(--bad); }
+#reader { overflow: hidden; border-radius: 12px; }
+#reader:empty { display: none; }
+
+@media (min-width: 1040px) {
+ .workspace {
+ display: grid;
+ grid-template-columns: 1.15fr 0.82fr 0.95fr;
+ align-items: start;
+ }
+ .panel-host { order: 1; }
+ .panel-ticket { order: 2; }
+ .panel-door { order: 3; }
+}
diff --git a/web-demo/vite.config.ts b/web-demo/vite.config.ts
new file mode 100644
index 0000000..d963e82
--- /dev/null
+++ b/web-demo/vite.config.ts
@@ -0,0 +1,11 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vite';
+
+const root = fileURLToPath(new URL('.', import.meta.url));
+
+export default defineConfig({
+ root,
+ base: './',
+ server: { port: 4173, strictPort: true, host: '127.0.0.1' },
+ build: { outDir: 'dist', emptyOutDir: true },
+});