diff --git a/CLAUDE.md b/CLAUDE.md index 3c4e65df..1c74390c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,28 +3,30 @@ pnpm + Turbo monorepo - `packages/frontend` - React 19 SPA (Vite, Tailwind CSS 4, shadcn/ui) -- `packages/api` - Core Cloudflare Worker (projects, docs, files) -- `packages/auth` - Auth Cloudflare Worker (login, register, TOTP, WebAuthn) +- `packages/api` - Core Cloudflare Worker (projects, docs, files, Annex sign-in + sessions, billing, preferences) +- `packages/admin` - Admin panel Worker + SPA (`admin.cubityfir.st`) - `packages/mcp` - stdio MCP server over the public `/v1` API, authenticated by one or more site-scoped API keys (see "Public API & Scoped API Keys") ### Auth -Authentication uses `Authorization: Bearer ` headers. JWTs are issued by the Auth Worker and verified by the API Worker via a shared `JWT_SECRET`. The Auth Worker handles all identity concerns (register, login, TOTP, WebAuthn). +Accounts live on the standalone identity service **auth.cubityfir.st** (worker `cubityfirst-auth`, its own repo + D1). Annex is an **OpenID Connect client** of it, like every other service: password, 2FA, passkeys, email changes, sessions on the identity side, account moderation, registration and account deletion all happen there. Annex keeps its own **sessions**, a **users mirror**, and everything Annex-specific (billing/Ink, preferences, handles, badges). See `memories/Identity-Client.md`. -**Verification boundary - read this before touching auth flow:** +**Read this before touching auth flow:** -- **API Worker verifies sessions inline.** It binds the auth D1 as `AUTH_DB` (read-only by convention - no migrations) and calls `loadCurrentSession` from `packages/auth/src/session.ts` directly. One batched read of `sessions` + a `users` row LEFT-JOINed against `user_billing` and `user_preferences`, no service-binding hop. This is what every authenticated API request goes through (`packages/api/src/auth.ts`). -- **Auth Worker owns credential/session writes; the admin worker writes a bounded set of auth-DB tables directly.** Login, register, change-password, session revoke, TOTP/WebAuthn enroll, lookup, etc. are still proxied through the `AUTH` service binding from the API worker. Anything that mutates credentials/sessions or needs rate limiting / email sending stays in the auth worker. The **admin worker** (`packages/admin`), however, binds the auth D1 as `AUTH_DB` read+write and writes these tables directly: `users` (moderation, force_password_change), `user_moderation_events`, `user_preferences` (badges, `handle`/`handle_locked`), `user_billing` (granted-plan columns), `user_deletions` (scheduled account deletion), and `admin_audit_log`. The API worker's `AUTH_DB` binding remains read-only by convention. Migrations still only live in `packages/auth/migrations/`. -- **Cross-package import.** API worker imports `loadCurrentSession`, `sessionResultToResponse`, and `verifyJwt` directly from `packages/auth/src/`. The API tsconfig lists those files in `include`. **A schema change to `users` / `sessions` / `user_billing` / `user_preferences` columns referenced in `loadCurrentSession` requires redeploying auth + api + admin (in that order)**, because all three packages read these tables directly. Migrations themselves still only live in `packages/auth/migrations/`. -- The auth worker's `/verify` endpoint still exists but the API worker no longer calls it - leave it in place for now in case external tooling depends on it. +- **Sign-in** (`packages/api/src/routes/auth.ts`, `src/account/oidc.ts` on oauth4webapi): `GET /api/auth/login` → identity service (PKCE S256, state, nonce in an HMAC-sealed HttpOnly cookie) → `GET /api/auth/callback` (id_token claims + JWKS signature verified, `users` mirror upserted, pending Annex session created, its single-use handoff code set ONLY as an HttpOnly SameSite=Strict `annex_handoff_` cookie - never in a URL, so a crafted link can't sign anyone in; one per sign-in) → SPA `/auth/complete#status=ok&attempt=` → `POST /api/auth/exchange?attempt=` redeems that cookie for the session JWT (kept in localStorage, sent as `Authorization: Bearer`). Sign-out: `POST /api/auth/logout` revokes the session and returns the end-session URL (`id_token_hint` kept on the session row). The admin panel runs the same flow (shared `AuthFlow`) as its own client with session `kind = 'admin'`. +- **Server-side OIDC requests never fetch `https://auth.cubityfir.st` directly.** Annex's workers share the cubityfir.st zone with it, and a Worker's same-zone `fetch()` to another Worker's hostname goes to the origin, not that Worker. Discovery/JWKS/token go through the **`IDENTITY_OIDC`** service binding (`cubityfirst-auth` default export; `identityFetch` in `account/oidc.ts`). Only browser redirects use the public URL. Local dev falls back to the public/local issuer when the binding has no target. +- **Sessions are verified inline** against cubedocs-main (`account/session.ts` `loadCurrentSession(token, env, kind)`: one batch of `sessions` + `users` mirror LEFT JOIN `user_billing`/`user_preferences`/`user_deletions`). The JWT (HS256, Annex-only `JWT_SECRET`) only proves Annex minted the session. **Account standing comes from the identity service** via the **`IDENTITY`** RPC binding (`IdentityService.getUser`, cached ~60s per isolate in `account/identity.ts`, falls back to the mirror's last known standing when unreachable). An admin-scheduled `user_deletions` row blocks the user in Annex regardless. +- **The users mirror** (`users` in cubedocs-main) is refreshed at sign-in and whenever the standing check sees a change; name/email changes are copied to `project_members`/`organization_members` snapshots. `PATCH /me` refuses `name` (owned by the identity service). Invite-by-email asks `IDENTITY.findUserByEmail` and mirrors the result. +- **No `AUTH_DB` / `AUTH` binding, no `packages/auth`.** Don't reintroduce a shared secret or a direct read of the identity DB. ### Database Schemas - **API DB** (`cubedocs-main`): projects, docs (+ `doc_ai_summaries` satellite; `docs.slug` is the doc's custom public-URL segment from the `slug:` frontmatter key - unique per project, normalized + synced by `docOps.syncDocSlug` on every save path incl. collab checkpoints and restores, resolved by `/public/docs/:site/:idOrSlug`), doc_revisions, folders, files, members, site_reports + user_reports (abuse reports: public "Report Site" button → `POST /public/projects/:id/report`, profile-card "Report user" → authenticated `POST /users/:id/report`; both triaged via the admin worker's `/api/reports/{sites,users}` routes + the admin "Reports" page's Sites/Users tabs) - see `packages/api/migrations/`. Bound as `DB` on the API worker. - **Recycle bin** (API DB, `0062_add_trash.sql`, `lib/trash.ts`, `routes/trash.ts`, `components/RecycleBin.tsx` - shown as the "Recycle bin" section of Site Settings, `/projects/:id/trash` redirects there): deleting a doc/file/folder (app, or `/v1` doc DELETE) **moves its rows out of** `docs`/`files`/`folders` into `trash_items` JSON snapshots (one `trash_entries` row per user-visible entry; a folder bins its whole subtree as one entry, except the home doc, which is moved to the root). Because binned rows are physically gone from the live tables, **no reader needs a "not deleted" filter - don't add one, and don't hard-delete docs/files/folders from a route; call `moveToTrash`**. Cascade-lost satellites that aren't derivable (`doc_shares`, the `docs_fts` row, `site_reports.doc_id`) ride in `extra_json` and come back on restore; R2 objects + `asset_revisions` stay until purge. Restore/list = editor+, delete-forever/empty = admin+, auto-purge after 30 days on the daily cron. Site deletion (api + admin) must include `trash_items` ids in its R2 sweep. `trash.test.ts` runs against real SQLite via `src/test/sqliteD1.ts` (all migrations applied) - use that harness for SQL-heavy logic. - **Doc search index** (API DB, `0064_rebuild_docs_fts.sql`, `lib/fts.ts`): `docs_fts` is FTS5 with an indexed `pid` = `hex(project_id)` token column plus a `docs_fts_map(rid, doc_id)` rowid map, so per-doc writes are rowid lookups and search MATCHes `pid:""` (`siteFtsMatch`) instead of scanning every site. **Never write `docs_fts` with raw SQL (`WHERE doc_id = ?` / `WHERE project_id = ?` are full scans, and a bare INSERT gets no `pid` or map row) - use the `fts*Statements` helpers**, which keep exactly one map row per FTS row and compose into a caller's batch (the insert + map statements must stay adjacent: `last_insert_rowid()`). Search weights stay `bm25(docs_fts, 5.0, 1.0, 0.0)` (pid weighted 0). `scripts/repair-docs-fts.sql` reconciles rows written by pre-0064 code. -- **Admin account deletion is always delayed** (auth `0034_add_user_deletions.sql`, admin `lib/userDeletion.ts`, Users page checkboxes → bulk Delete/Disable/Re-enable/Cancel deletion): "Delete" only **schedules** - it disables the account now and writes a `user_deletions` row; the admin worker's hourly cron (`runDueUserDeletions`) performs the delete after 7 days, and any admin can cancel before then (restoring the prior moderation). Owned sites/orgs are deleted **only** when the operator ticked an explicit per-account box in the preview, scheduling refuses unless the confirmed ids exactly match current ownership (`sameIdSet`), and execution refuses if the account owns anything outside them. While a deletion is pending, `PATCH /api/users/:id` moderation is refused - cancel instead (the guard is inside the write, not just a pre-check). The cron claims each schedule by `(user_id, id)` with a lease; cancel is refused while leased or once `started_at` is set (first irreversible step), after which a failed run is retried to completion - a confirmed site/org that no longer exists counts as done. Real-SQLite scenario tests: `userDeletion.sqlite.test.ts`. **Don't add an immediate admin delete path.** Site deletion itself is shared via `lib/projectDelete.ts`. -- **Auth DB** (`cubedocs-auth`): users, sessions, totp, webauthn_credentials, plus the 1:1 satellites `user_billing` (Stripe + plan state) and `user_preferences` (fonts, Ink cosmetics, timezone, bio, badges, opt-in profile `handle`) - see `packages/auth/migrations/`. The `handle` (`0035`, partial unique index, stored lowercase, rules in `packages/auth/src/handle.ts` mirrored by `frontend/src/lib/handle.ts`) powers the `/@` profile link: set/cleared via auth `/update-handle` (proxied as `PATCH /me/handle`), resolved by the API's `GET /users/by-handle/:handle` reading `AUTH_DB` directly. Null = link off. Admins moderate it via the admin worker's `PATCH /api/users/:id/handle` (Users → details → "Profile Link"; may assign reserved names) and can set `handle_locked`, which makes `/update-handle` refuse every user change (403 `reason: "locked"`, guarded inside the write too). Bound as `DB` on the auth worker (read+write), as `AUTH_DB` on the API worker (read-only by convention), and as `AUTH_DB` on the admin worker (read+write for moderation/badges/billing-grants/audit - see the verification-boundary note above). **A schema change to any column these direct readers/writers touch requires redeploying auth + api + admin (in that order).** +- **Admin deletion is always delayed and deletes Annex data only** (api `0065_add_identity_mirror.sql` `user_deletions`, admin `lib/userDeletion.ts`, Users page checkboxes → bulk Delete/Cancel deletion): "Delete" only **schedules** - the `user_deletions` row blocks the person from Annex at once; the admin worker's hourly cron (`runDueUserDeletions`) deletes their Annex data after 7 days (Stripe customer, confirmed sites/orgs, memberships, billing, preferences, sessions) and sets `completed_at`. The users mirror row and schedule stay, so they remain blocked until the operator deletes the **identity account on auth.cubityfir.st** (Annex never deletes it). Any admin can cancel before execution starts. Moderation (disable/suspend) happens on auth.cubityfir.st, not in the Annex admin. Owned sites/orgs are deleted **only** when the operator ticked an explicit per-account box in the preview, scheduling refuses unless the confirmed ids exactly match current ownership (`sameIdSet`), and execution refuses if the account owns anything outside them. The cron claims each schedule by `(user_id, id)` with a lease; cancel is refused while leased or once `started_at` is set (first irreversible step), after which a failed run is retried to completion - a confirmed site/org that no longer exists counts as done; completed rows are never re-run. Real-SQLite scenario tests: `userDeletion.sqlite.test.ts`. **Don't add an immediate admin delete path.** Site deletion itself is shared via `lib/projectDelete.ts`. +- **Account data** (cubedocs-main, `0065_add_identity_mirror.sql`; copied once from the retired `cubedocs-auth` by `scripts/import-auth-data.mjs`): the `users` mirror (`id` = OIDC `sub`, email, name, is_admin, last known `status`/`suspended_until`), Annex `sessions` (`kind` app/admin, `id_token`, single-use `handoff_hash`), and the satellites `user_billing` (Stripe + plan state) and `user_preferences` (fonts, theme, Ink cosmetics, timezone, bio, badges, opt-in profile `handle` + `handle_locked`), plus `webhook_events`, `user_deletions`, `user_moderation_events` (read-only history), `admin_audit_log` and `identity_deletions`. The `handle` (partial unique index, stored lowercase, rules in `packages/api/src/account/handle.ts` mirrored by `frontend/src/lib/handle.ts`) powers the `/@` profile link: set via `PATCH /me/handle`, resolved by `GET /users/by-handle/:handle`; admins moderate it via the admin worker's `PATCH /api/users/:id/handle` and can lock it (`403 reason: "locked"`). +- **Deletion sync** (api `lib/identityDeletions.ts`, hourly cron `23 * * * *`): `IDENTITY.listDeletedUsers` from the newest recorded `identity_deletions.deleted_at`; for each account it deletes the Stripe customer, memberships, API keys, shares, favourites, avatars and the users mirror row (cascading the rest). **Sites/orgs the person owned are kept** (owner rows too) and listed on the admin Projects page ("Owner account deleted") for an operator to delete or leave. Failures stay pending with `last_error` and retry. #### Satellite tables and the resolver @@ -33,9 +35,9 @@ Authentication uses `Authorization: Bearer ` headers. JWTs are issued by th - Satellite row is created lazily - first write does `INSERT … ON CONFLICT(parent_id) DO UPDATE SET …`. A user/doc/etc. that has never had the feature touched has no satellite row at all. - Every reader does `LEFT JOIN ON ._id = .id`. Missing rows return NULL for every satellite column, which the consumer treats as "default." - The satellite declares `REFERENCES (id) ON DELETE CASCADE` so deleting the parent wipes the satellite row automatically. -- Existing satellites: `doc_ai_summaries` (api DB; ai_summary cache), `user_billing` (auth DB; Stripe/plan state), `user_preferences` (auth DB; fonts + cosmetics + timezone + bio + badges). +- Existing satellites: `doc_ai_summaries` (ai_summary cache), `user_billing` (Stripe/plan state), `user_preferences` (fonts + cosmetics + timezone + bio + badges + handle). All in cubedocs-main. -`resolvePersonalPlan` in `packages/auth/src/plan.ts` is fed inputs from multiple tables (billing-state from `user_billing`, cosmetic prefs from `user_preferences`). Callers build a flat `PlanRow` from the LEFT-JOINed query result and hand it to the resolver - see `loadCurrentSession`, `members.ts`, `update-ink-prefs.ts` for the pattern. +`resolvePersonalPlan` in `packages/api/src/account/plan.ts` is fed inputs from multiple tables (billing-state from `user_billing`, cosmetic prefs from `user_preferences`). Callers build a flat `PlanRow` from the LEFT-JOINed query result and hand it to the resolver - see `loadCurrentSession`, `members.ts`, `routes/me/update-ink-prefs.ts` for the pattern. ## Frontend Notes @@ -62,7 +64,7 @@ The landing page's "See a demo" links to **`/demo`**, a local-only sandbox: a se ## Annex Ink + Stripe -Personal supporter subscription ($5/mo) with Stripe billing, comp-grant override, animated avatar ring, admin grant/revoke/cancel controls, and a webhook proxy through the frontend worker. **Anything touching the `user_billing` table (Stripe ids, `personal_plan_*`, `granted_plan_*`), the cosmetic-pref columns on `user_preferences` (`personal_plan_style`, `personal_presence_color`, `personal_crit_sparkles`), `billing.ts`, `stripe-webhook.ts`, the billing UI in user settings or the admin user-details sheet, or the `InkBillingCard` belongs to this system** - see `memories/Ink-Stripe.md` for schema, plan resolution rules, webhook flow, deploy/dev setup, and ops cheatsheet. +Personal supporter subscription ($5/mo) with Stripe billing, comp-grant override, animated avatar ring, admin grant/revoke/cancel controls, and a webhook proxy through the frontend worker. **Anything touching the `user_billing` table (Stripe ids, `personal_plan_*`, `granted_plan_*`), the cosmetic-pref columns on `user_preferences` (`personal_plan_style`, `personal_presence_color`, `personal_crit_sparkles`), `routes/billing.ts`, `routes/stripeWebhook.ts` (api worker), the billing UI in user settings or the admin user-details sheet, or the `InkBillingCard` belongs to this system** - see `memories/Ink-Stripe.md` for schema, plan resolution rules, webhook flow, deploy/dev setup, and ops cheatsheet. ## Realtime Collaboration @@ -92,24 +94,24 @@ A site owner can map their **own domain** (e.g. `docs.example.com`) to their pub Annex is **not** an OpenID Connect provider any more. Since 2026-11-18 the provider is the standalone `cubityfirst-auth` worker at `https://auth.cubityfir.st` -(its own repo and D1). annex-auth no longer serves `/oauth/*` or `/.well-known/*`, -has no `auth.cubityfir.st` routes (that hostname is cubityfirst-auth's Custom -Domain - **never re-add those triggers**), and holds no OIDC signing key. OAuth -clients are managed at `auth.cubityfir.st/admin/clients`. The old -`docs.cubityfir.st/oauth/authorize` URL redirects to the provider. See +(its own repo and D1); Annex is one of its clients (see "Auth" above). The +`auth.cubityfir.st` hostname is cubityfirst-auth's Custom Domain - **never add +routes for it to an Annex worker**. OAuth clients are managed at +`auth.cubityfir.st/admin/clients`. The old `docs.cubityfir.st/oauth/authorize` +URL redirects to the provider (frontend worker + SPA shim). See `docs/oauth/README.md`. ## Tests Tests exist - run them before reporting work as done when changes are testable. -- **Vitest unit tests** live next to source as `*.test.ts(x)` in each package. Run per-package with `pnpm --filter test`, or all packages + e2e with `pnpm test` from the root. Coverage is heaviest in `packages/auth` (login, password, jwt, totp, plan, billing, stripe-webhook) and `packages/frontend/src/lib` (remark plugins, dice, frontmatter, userColor). -- **Playwright e2e tests** live in `e2e/tests/` (one `*.spec.ts` per feature area - list the directory to see current coverage). Run with `pnpm test:e2e` (headless) or `pnpm test:e2e:ui` (UI mode). First run needs `pnpm --filter cubedocs-e2e install:browsers`. +- **Vitest unit tests** live next to source as `*.test.ts(x)` in each package. Run per-package with `pnpm --filter test`, or all packages + e2e with `pnpm test` from the root. Sign-in is covered end to end against a fake OpenID provider (`packages/api/src/test/fakeIdp.ts`, `routes/auth.test.ts`); SQL-heavy logic runs on real SQLite (`src/test/sqliteD1.ts`, `test/session.ts` seeds a mirror user + session). +- **Playwright e2e tests** live in `e2e/tests/` (one `*.spec.ts` per feature area - list the directory to see current coverage). Accounts live on auth.cubityfir.st, so suites sign in with `e2e/signIn.ts` (`devSignIn` via the api worker's localhost-only `POST /api/dev/quick-login`; needs `DEV_QUICK_LOGIN=true` + `APP_ORIGIN=http://localhost:5173` in `packages/api/.dev.vars`). `admin.spec.ts` uses the admin worker's own `POST /api/dev/quick-login` (`DEV_QUICK_LOGIN=true` + `APP_ORIGIN=http://localhost:5174` in `packages/admin/.dev.vars`). Keep `OIDC_ISSUER` in both `.dev.vars` local (see the `.example` files) so sign-out never redirects a test to the real provider. Run with `pnpm test:e2e` (headless) or `pnpm test:e2e:ui` (UI mode). First run needs `pnpm --filter cubedocs-e2e install:browsers`. - When adding behavior with existing test coverage in the same area, extend the corresponding suite rather than leaving it untested. ## Commits -Use Conventional Commits with a type **and** scope: `(): ` (e.g. `feat(frontend): draft-first doc creation`, `fix(auth): ...`). Types/scopes are listed in `CONTRIBUTING.md` - scope is the package (`frontend`, `api`, `auth`, `admin`, `e2e`) or feature area (`files`, `search`, `orgs`, `billing`, `collab`, `oidc`, ...). +Use Conventional Commits with a type **and** scope: `(): ` (e.g. `feat(frontend): draft-first doc creation`, `fix(auth): ...`). Types/scopes are listed in `CONTRIBUTING.md` - scope is the package (`frontend`, `api`, `admin`, `e2e`) or feature area (`files`, `search`, `orgs`, `billing`, `collab`, `oidc`, ...). ## CLI Notes @@ -117,10 +119,10 @@ Use Conventional Commits with a type **and** scope: `(): --persist-to ../../.wrangler/state`, which loads `cloudflare.config.ts` + `wrangler.config.ts` (and `.dev.vars`) directly. Plain `cf dev` isn't used because it can't take a persist dir yet, and all workers must share one state dir (the api reads auth's DB via `AUTH_DB`). The frontend's `pnpm dev` is plain Vite. -- **Local D1 SQL** (no Wrangler config means `wrangler d1 execute --local` can't resolve a database, and `cf d1 query --local` isn't implemented yet): use `node scripts/d1-local.mjs ""` (or `--file`), which runs through the running api dev server's Local Explorer API against the shared state - see "Local D1 State" below. Remote commands (`npx wrangler d1 execute --remote`, `npx wrangler r2 object ... --remote`) work without a config file. +- **Local dev** (`pnpm dev`): api/admin run `wrangler dev --experimental-new-config --port --persist-to ../../.wrangler/state`, which loads `cloudflare.config.ts` + `wrangler.config.ts` (and `.dev.vars`) directly. Plain `cf dev` isn't used because it can't take a persist dir yet, and both workers must share one state dir (they share cubedocs-main). The frontend's `pnpm dev` is plain Vite. **Sign-in locally**: run the identity worker (`G:\scripts\auth`) with `npx wrangler dev --port 8790` (Annex's api owns :8787) and point `OIDC_*` in `packages/{api,admin}/.dev.vars` at it (see the `.dev.vars.example` files), or skip it with the dev quick-login buttons (`DEV_QUICK_LOGIN=true`). +- **Local D1 SQL** (no Wrangler config means `wrangler d1 execute --local` can't resolve a database, and `cf d1 query --local` isn't implemented yet): use `node scripts/d1-local.mjs main ""` (or `--file`), which runs through the running api dev server's Local Explorer API against the shared state - see "Local D1 State" below. Remote commands (`npx wrangler d1 execute --remote`, `npx wrangler r2 object ... --remote`) work without a config file. - D1 migrations: `pnpm migrate` / `node scripts/migrate.mjs ` run `cf d1 migrations apply ` (remote unless `--local`). - `annex-api`'s `DocCollabRoom` is declared as `exports.durableObject({ storage: "legacy-kv" })` - it was created with `new_classes` (KV-backed). Never change it to `"sqlite"`. - The frontend package depends on Vite, so `cf build` would run `vite build` instead of Wrangler; its deploy is `pnpm build && pnpm build:worker (cf-wrangler build) && cf deploy --prebuilt`. @@ -132,10 +134,10 @@ The dev servers use a shared wrangler state at the **monorepo root** (`/.wrangle Local migrations (`pnpm migrate` / `node scripts/migrate.mjs local`) pass `--persist-to ../../.wrangler/state` from the package directory; any manual `cf d1 migrations apply --local` must too, otherwise it hits a state the dev servers never read. -Ad-hoc local queries go through `scripts/d1-local.mjs` (needs `pnpm dev` running - it talks to the api worker on :8787, override with `ANNEX_DEV_API_ORIGIN`). `main` = `cubedocs-main`, `auth` = `cubedocs-auth`; it prints the last statement's rows as JSON. Use it for DML/SELECTs - schema changes belong in migrations. e2e specs use the `e2e/d1Local.ts` wrapper. +Ad-hoc local queries go through `scripts/d1-local.mjs` (needs `pnpm dev` running - it talks to the api worker on :8787, override with `ANNEX_DEV_API_ORIGIN`). `main` = `cubedocs-main` (the only database; accounts live on auth.cubityfir.st); it prints the last statement's rows as JSON. Use it for DML/SELECTs - schema changes belong in migrations. e2e specs use the `e2e/d1Local.ts` wrapper. ``` -node scripts/d1-local.mjs auth "SELECT id, email FROM users LIMIT 5" +node scripts/d1-local.mjs main "SELECT id, email, status FROM users LIMIT 5" node scripts/d1-local.mjs main "UPDATE projects SET features = features | 4 WHERE id = ''" ``` @@ -143,7 +145,7 @@ node scripts/d1-local.mjs main "UPDATE projects SET features = features | 4 WHER For running several feature branches side-by-side (e.g. many agents in parallel, each reviewable in a browser on its own port), use `scripts/worktree.mjs`. The main checkout runs -the full stack via `pnpm dev` (frontend 5173 + api 8787 + auth 8788 + admin 8789 + the shared +the full stack via `pnpm dev` (frontend 5173 + api 8787 + admin 8789 + the shared `.wrangler/state` D1) - that's the **one backend**. Each worktree adds **another frontend** on its own port, and the Vite `/api` proxy (hardcoded to `:8787` in `vite.config.ts`) makes every worktree frontend talk to that single backend and share the one dev DB. No app-code or diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ce73fb5..4e674a00 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ This is a pnpm + Turbo monorepo (`packageManager: pnpm@10`, Node 20+ recommended ```sh pnpm install pnpm migrations:local # apply D1 migrations to the shared local dev state -pnpm dev # frontend :5173, api :8787, auth :8788, admin :8789 +pnpm dev # frontend :5173, api :8787, admin :8789 (+ admin SPA :5174) ``` The dev servers share one local state at the monorepo root (`.wrangler/state`). Worker config lives only in each package's `cloudflare.config.ts` (+ `wrangler.config.ts` for build settings) - there is no `wrangler.toml`. Local migrations (`pnpm migrate`) pass `--persist-to ../../.wrangler/state` from the package directory; for ad-hoc local SQL use `node scripts/d1-local.mjs ""` while `pnpm dev` is running. All wrangler invocations go through `npx wrangler`. @@ -16,7 +16,6 @@ The dev servers share one local state at the monorepo root (`.wrangler/state`). - `packages/frontend` - React 19 SPA (Vite, Tailwind CSS 4, shadcn/ui) - `packages/api` - Core Cloudflare Worker (projects, docs, files) -- `packages/auth` - Auth Cloudflare Worker (login, register, TOTP, WebAuthn, OIDC) - `packages/admin` - Admin Cloudflare Worker + admin frontend - `e2e` - Playwright end-to-end tests @@ -63,5 +62,5 @@ When you add behavior in an area that already has a test suite, extend that suit ## Pull requests - Keep PRs focused on one change; separate refactors from behavior changes. -- Schema changes: migrations live only in `packages/api/migrations/` and `packages/auth/migrations/`. A change to auth-DB columns read by `loadCurrentSession` requires redeploying auth + api + admin, in that order - call this out in the PR description. +- Schema changes: migrations live only in `packages/api/migrations/` (cubedocs-main, shared by the api and admin workers). A change to columns read by `loadCurrentSession` (users mirror, sessions, user_billing, user_preferences, user_deletions) needs both workers redeployed (api first) - call this out in the PR description. Accounts themselves live on auth.cubityfir.st. - If you add or remove a runtime dependency in `packages/frontend`, update `src/lib/acknowledgements.ts` to match. diff --git a/README.md b/README.md index 923c9eb6..7eac1965 100644 --- a/README.md +++ b/README.md @@ -80,18 +80,15 @@ Create local secrets files for each Worker: ```bash cp packages/api/.dev.vars.example packages/api/.dev.vars -cp packages/auth/.dev.vars.example packages/auth/.dev.vars +cp packages/admin/.dev.vars.example packages/admin/.dev.vars ``` -Both Workers need a shared `JWT_SECRET`: - -```ini -# packages/api/.dev.vars -JWT_SECRET=your-secret-here - -# packages/auth/.dev.vars -JWT_SECRET=your-secret-here # must match api -``` +Accounts live on the identity service at auth.cubityfir.st, and Annex signs +in through it with OpenID Connect. Locally you can either run that worker (its +repo, `npx wrangler dev --port 8790`) and register local clients as described +in the `.dev.vars.example` files, or skip it: with `DEV_QUICK_LOGIN=true` (the +default in the example) `/login` shows dev quick-login buttons. See +`memories/Identity-Client.md`. **3. Apply local database migrations** @@ -113,7 +110,7 @@ Starts all packages concurrently. Once running: |---|---| | Frontend | http://localhost:5173 | | API Worker | http://localhost:8787 | -| Auth Worker | http://localhost:8788 | +| Admin Worker | http://localhost:8789 | | Admin Dashboard | http://localhost:5174 | The frontend dev server automatically proxies `/api` requests to the local Workers - no separate configuration needed. @@ -138,7 +135,7 @@ Then `stripe login` once to authorise the CLI against your Stripe account. **2. Add Stripe secrets to `.dev.vars`** ```ini -# packages/auth/.dev.vars +# packages/api/.dev.vars STRIPE_SECRET_KEY=sk_test_... # from Stripe Dashboard → API keys (test mode) STRIPE_WEBHOOK_SECRET=whsec_... # filled in step 3 STRIPE_INK_PRICE_ID=price_... # the test-mode Annex Ink price id @@ -148,18 +145,18 @@ APP_ORIGIN=http://localhost:5173 # so Checkout redirects come back to loc STRIPE_SECRET_KEY=sk_test_... # same value, for admin-driven cancels ``` -**3. Forward Stripe webhooks to the local auth worker** +**3. Forward Stripe webhooks to the local api worker** In a separate terminal alongside `pnpm dev`: ```bash pnpm dev:stripe -# (equivalent to: stripe listen --forward-to http://localhost:8788/stripe/webhook) +# (equivalent to: stripe listen --forward-to http://localhost:8787/stripe/webhook) ``` -The CLI prints a `whsec_...` at startup - paste it into `packages/auth/.dev.vars` as `STRIPE_WEBHOOK_SECRET`, then restart the auth worker dev so it picks up the new value. The `whsec_` printed by the CLI is only valid for events forwarded by that CLI session; it's separate from the live-mode webhook secret in the Stripe Dashboard. +The CLI prints a `whsec_...` at startup - paste it into `packages/api/.dev.vars` as `STRIPE_WEBHOOK_SECRET`, then restart the api worker dev so it picks up the new value. The `whsec_` printed by the CLI is only valid for events forwarded by that CLI session; it's separate from the live-mode webhook secret in the Stripe Dashboard. -Without `pnpm dev:stripe` running, the local auth worker will accept webhook POSTs from the public internet but won't see any. Local checkouts will succeed at Stripe, but local DB state won't update until events are forwarded. +Without `pnpm dev:stripe` running, the local api worker will accept webhook POSTs from the public internet but won't see any. Local checkouts will succeed at Stripe, but local DB state won't update until events are forwarded. ## Direct video streaming via presigned R2 URLs (optional) diff --git a/e2e/d1Local.ts b/e2e/d1Local.ts index 51b3dbcc..2e99192f 100644 --- a/e2e/d1Local.ts +++ b/e2e/d1Local.ts @@ -6,12 +6,12 @@ const SCRIPT = resolve(__dirname, "../scripts/d1-local.mjs"); /** * Run SQL against the local dev D1 (the shared .wrangler/state behind * `pnpm dev`) via scripts/d1-local.mjs - the config-free replacement for - * `npx wrangler d1 execute --local`. `main` = cubedocs-main (api DB), - * `auth` = cubedocs-auth. Needs the api dev server (:8787) running, which every + * `npx wrangler d1 execute --local`. `main` = cubedocs-main (the only + * database). Needs the api dev server (:8787) running, which every * e2e spec already does. Spawned without a shell, so SQL quotes pass through * verbatim. Throws with the helper's error message on failure. */ -export function d1Local(db: "main" | "auth", sql: string): void { +export function d1Local(db: "main", sql: string): void { try { execFileSync(process.execPath, [SCRIPT, db, sql], { stdio: "pipe" }); } catch (err) { diff --git a/e2e/global-teardown.ts b/e2e/global-teardown.ts index cd31c227..c37657a0 100644 --- a/e2e/global-teardown.ts +++ b/e2e/global-teardown.ts @@ -10,12 +10,12 @@ import { d1Local } from "./d1Local"; // so it writes the local D1 directly (scripts/d1-local.mjs, via the running // api dev server). It also runs on Playwright failure exits. // -// FK cascades handle most of the auth-DB tail (sessions, webauthn, backup -// codes, moderation events). email_verification_tokens has no cascade, so we -// delete it explicitly first. On the API DB, deleting projects cascades -// everything below (docs, folders, files, members, invite links). +// Accounts live on auth.cubityfir.st; Annex keeps a users mirror in +// cubedocs-main, where deleting a mirror row cascades its sessions, billing +// and preferences. Deleting projects cascades everything below them (docs, +// folders, files, members, invite links). export default async function globalTeardown() { - const run = (db: "main" | "auth", sql: string) => { + const run = (db: "main", sql: string) => { try { d1Local(db, sql); } catch (err) { @@ -25,12 +25,8 @@ export default async function globalTeardown() { } }; - // Auth DB: orphan tokens first, then users (cascades the rest). - run( - "auth", - "DELETE FROM email_verification_tokens WHERE user_id IN (SELECT id FROM users WHERE email LIKE 'e2e-%@example.com');", - ); - run("auth", "DELETE FROM users WHERE email LIKE 'e2e-%@example.com';"); + // Users mirror (e2e users are dev quick-login users or e2e-* addresses). + run("main", "DELETE FROM users WHERE email LIKE 'e2e-%@example.com';"); // API DB: delete e2e-suite projects by name prefix (cascades everything). // Patterns track the names used in app.spec.ts, invites.spec.ts, and diff --git a/e2e/signIn.ts b/e2e/signIn.ts new file mode 100644 index 00000000..66deb534 --- /dev/null +++ b/e2e/signIn.ts @@ -0,0 +1,28 @@ +import type { Page } from "@playwright/test"; + +/** + * Signs a browser page in as a local-dev Annex user without the identity + * service. Accounts live on auth.cubityfir.st now, so the suites can no + * longer register through Annex's own forms; this uses the api worker's + * localhost-only POST /api/dev/quick-login (packages/api/src/routes/auth.ts), + * which needs `DEV_QUICK_LOGIN=true` and `APP_ORIGIN=http://localhost:5173` + * in packages/api/.dev.vars. + * + * The same email always maps to the same dev user, so a spec can sign the + * same person back in. Use `e2e-…@example.com` addresses so global-teardown + * cleans them up. + */ +export async function devSignIn( + page: Page, + user: { email: string; name?: string; admin?: boolean }, +): Promise<{ token: string; userId: string }> { + const res = await page.request.post("/api/dev/quick-login", { data: user }); + if (!res.ok()) throw new Error(`dev quick-login failed (${res.status()}): is DEV_QUICK_LOGIN=true set for the api worker?`); + const { data } = (await res.json()) as { data: { token: string; userId: string } }; + // The SPA keeps its session JWT in localStorage["token"] (src/lib/auth.ts). + await page.goto("/"); + await page.evaluate(token => window.localStorage.setItem("token", token), data.token); + // Land where a sign-in does. + await page.goto("/dashboard"); + return data; +} diff --git a/e2e/tests/2fa.spec.ts b/e2e/tests/2fa.spec.ts deleted file mode 100644 index eab11f03..00000000 --- a/e2e/tests/2fa.spec.ts +++ /dev/null @@ -1,405 +0,0 @@ -/** - * E2E tests for two-factor authentication. - * - * Covers: - * - TOTP: enable, login with code, disable - * - WebAuthn: register a virtual passkey, login with it, remove it - * - * Prerequisites - run from the monorepo root: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * WEBAUTHN_RP_ID=localhost - * WEBAUTHN_ORIGIN=http://localhost:5173 - * - * A fresh account is registered at the start and deleted in afterAll, so no - * data is left behind even if tests fail mid-way. - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-2fa-${RUN_ID}@example.com`; -const PASSWORD = "2FA-Test-P@ssw0rd!"; -const NAME = "2FA Test User"; -// Offset +1 from app.spec so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 1) % 256}`; - -// ── TOTP secret shared across tests in this file ───────────────────────────── - -// Captured during "enables authenticator app" and reused in subsequent tests. -let totpSecret = ""; - -// ── TOTP helper ─────────────────────────────────────────────────────────────── - -/** - * Computes the current TOTP code for a base32-encoded secret. - * Mirrors the HOTP implementation in packages/auth/src/totp.ts. - * The auth server accepts ±1 time step, so clock drift of up to 30 s is fine. - */ -async function computeTOTP(secret: string): Promise { - const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - const clean = secret.toUpperCase().replace(/[^A-Z2-7]/g, ""); - const bytes: number[] = []; - let bits = 0, value = 0; - for (const char of clean) { - const idx = BASE32.indexOf(char); - if (idx === -1) continue; - value = (value << 5) | idx; - bits += 5; - if (bits >= 8) { - bits -= 8; - bytes.push((value >>> bits) & 255); - } - } - const secretBytes = new Uint8Array(bytes); - const counter = Math.floor(Date.now() / 1000 / 30); - const key = await crypto.subtle.importKey( - "raw", secretBytes.buffer, - { name: "HMAC", hash: "SHA-1" }, - false, ["sign"], - ); - const counterBuf = new ArrayBuffer(8); - new DataView(counterBuf).setBigUint64(0, BigInt(counter), false); - const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBuf)); - const offset = hmac[19] & 0x0f; - const code = ( - ((hmac[offset] & 0x7f) << 24) | - ((hmac[offset + 1] & 0xff) << 16) | - ((hmac[offset + 2] & 0xff) << 8) | - (hmac[offset + 3] & 0xff) - ) % 1_000_000; - return code.toString().padStart(6, "0"); -} - -/** - * Fills a shadcn/ui InputOTP widget. - * input-otp renders a native positioned absolutely over - * the visual slot divs. We click that native input directly to focus it, then - * keyboard.type flows each digit into successive slots automatically. - */ -async function fillOTP(page: Page, code: string) { - const otpInput = page.locator('[data-input-otp]').first(); - await otpInput.click(); - await page.keyboard.type(code); -} - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -let cdpSession: any = null; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - // ?logout=1 tells LoginPage to call clearToken() before checking for an - // existing session, so the user lands on the login form rather than being - // redirected straight to the dashboard. - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function loginWithPassword(p: Page) { - await p.goto("/login"); - await p.getByLabel("Email").fill(EMAIL); - await p.getByLabel("Password").fill(PASSWORD); - await expect(p.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await p.getByRole("button", { name: "Sign in" }).click(); -} - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. The "deletes the account - 2FA -// confirmation required" test exercises the UI delete flow itself. -test.afterAll(async () => { - if (cdpSession) { - await cdpSession.detach().catch(() => {}); - cdpSession = null; - } - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account for 2FA testing", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ════════════════════════════════════════════════════════════════════════════ -// TOTP -// ════════════════════════════════════════════════════════════════════════════ - -test("TOTP - enables authenticator app", async () => { - await page.goto("/settings"); - await page.getByRole("button", { name: "Set up authenticator app" }).click(); - - // The UI shows a QR code and the manual-entry secret in a element. - const secretEl = page.locator("code").first(); - await expect(secretEl).toBeVisible({ timeout: 5000 }); - totpSecret = (await secretEl.textContent())?.trim() ?? ""; - expect(totpSecret.length).toBeGreaterThan(10); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // First sign-in factor on the account, so enrollment asks for the password. - await page.locator("#totp-enrollment-password").fill(PASSWORD); - await page.getByRole("button", { name: "Enable 2FA" }).click(); - - // Setup exits and the disable button appears. - await expect(page.getByRole("button", { name: "Disable authenticator app" })).toBeVisible({ timeout: 10000 }); -}); - -test("TOTP - login prompts for the authenticator code", async () => { - await logout(page); - await loginWithPassword(page); - // Server returns totp_required → login page switches to the TOTP step. - await expect(page.getByText("Two-factor authentication")).toBeVisible({ timeout: 8000 }); - await expect(page.getByText(/authenticator code/i)).toBeVisible({ timeout: 3000 }); -}); - -test("TOTP - entering a valid code completes login", async () => { - // Still on the TOTP challenge screen from the previous test. - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // The 2FA step auto-submits once six digits are entered (no Turnstile here, - // and clicking "Verify" again would replay the now-consumed code), so just - // wait for the redirect off the login page. - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); -}); - -test("TOTP - a parent settings dialog survives the stacked 2FA dialog", async () => { - // Regression: the change-email/change-password dialogs and the use2FA dialog - // are sibling Radix modals. Opening the 2FA dialog used to make the parent - // dismiss itself (resetting its fields), and the focus shuffle could knock - // the 2FA dialog down too. The parent must keep its state through the whole - // 2FA exchange. - await page.goto("/settings"); - await page.getByRole("button", { name: "Change email address" }).click(); - await page.getByLabel("New email address", { exact: true }).fill("stacked-dialogs@example.com"); - await page.getByLabel("Current password", { exact: true }).fill("wrong-on-purpose"); - await page.getByRole("button", { name: "Change email", exact: true }).click(); - - // 2FA dialog stacks on top (the parent is aria-hidden behind it, so it - // disappears from the accessibility tree - that's expected). - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // The wrong password is rejected AFTER 2FA passes - the parent dialog must - // reappear with its fields intact so the user can just fix the password. - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - await expect(page.getByRole("dialog", { name: "Change email address" })).toBeVisible(); - await expect(page.getByLabel("New email address", { exact: true })).toHaveValue("stacked-dialogs@example.com"); - - // And it still closes cleanly on demand. - await page.getByRole("dialog", { name: "Change email address" }).getByRole("button", { name: "Cancel" }).click(); - await expect(page.getByRole("dialog", { name: "Change email address" })).not.toBeVisible(); -}); - -test("TOTP - disables authenticator app (requires TOTP confirmation)", async () => { - await page.goto("/settings"); - // The security-status fetch can get dropped under full-suite load, leaving - // the section without the button - reload and retry rather than hang. - const disableBtn = page.getByRole("button", { name: "Disable authenticator app" }); - await expect(async () => { - if (!(await disableBtn.isVisible().catch(() => false))) await page.reload(); - await expect(disableBtn).toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await disableBtn.click(); - - // use2FA dialog opens in TOTP mode (only TOTP is active on this account). - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // "Set up authenticator app" reappears after disabling. - await expect(page.getByRole("button", { name: "Set up authenticator app" })).toBeVisible({ timeout: 10000 }); - totpSecret = ""; // no longer valid -}); - -test("TOTP - login no longer requires a code after disabling", async () => { - await logout(page); - await loginWithPassword(page); - // Should go straight to the dashboard without a TOTP prompt. - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); - await expect(page.getByText(/two.factor authentication/i)).not.toBeVisible(); -}); - -// ════════════════════════════════════════════════════════════════════════════ -// WebAuthn (Playwright virtual authenticator) -// ════════════════════════════════════════════════════════════════════════════ - -test("WebAuthn - registers a virtual passkey", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - // Chrome DevTools Protocol is the current way to add a virtual authenticator - // (Playwright's high-level addVirtualAuthenticator wrapper is not available in - // this version). The RP ID and origin must match packages/auth/.dev.vars: - // WEBAUTHN_RP_ID=localhost / WEBAUTHN_ORIGIN=http://localhost:5173 - cdpSession = await context.newCDPSession(page); - await cdpSession.send("WebAuthn.enable", { enableUI: false }); - await cdpSession.send("WebAuthn.addVirtualAuthenticator", { - options: { - protocol: "ctap2", - transport: "internal", - hasResidentKey: true, - hasUserVerification: true, - isUserVerified: true, - }, - }); - - await page.goto("/settings"); - await page.getByRole("button", { name: "Add security key" }).click(); - await expect(page.getByLabel(/key name/i)).toBeVisible({ timeout: 3000 }); - await page.getByLabel(/key name/i).fill("Playwright Virtual Key"); - // TOTP was disabled above, so the passkey is a first factor too. - await page.locator("#key-enrollment-password").fill(PASSWORD); - - // "Register key" triggers startRegistration() in the browser; the virtual - // authenticator responds automatically. - await page.getByRole("button", { name: "Register key" }).click(); - - // The credential should appear in the key list. - await expect(page.getByText("Playwright Virtual Key")).toBeVisible({ timeout: 10000 }); -}); - -test("WebAuthn - login triggers the passkey ceremony", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - const finish = page.waitForResponse(r => r.url().includes("/api/webauthn/auth/finish") && r.request().method() === "POST"); - await loginWithPassword(page); - - // The server returns webauthn_required and the login page immediately starts - // the WebAuthn ceremony (startAuthentication). The virtual authenticator - // handles it silently, so we land on the dashboard without manual input. - expect((await finish).ok()).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); -}); - -test("WebAuthn - signs in with the passkey alone (no email or password)", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - await page.goto("/login"); - const finish = page.waitForResponse(r => r.url().includes("/api/webauthn/auth/passkey/finish") && r.request().method() === "POST"); - - // Empty allowCredentials: the virtual authenticator answers with the - // discoverable credential registered above, which names the account. - await page.getByRole("button", { name: "Sign in with a passkey" }).click(); - - expect((await finish).ok()).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); -}); - -test("WebAuthn - removes the passkey (requires WebAuthn confirmation)", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await page.goto("/settings"); - - const keyRow = page.locator("li", { hasText: "Playwright Virtual Key" }); - await expect(keyRow).toBeVisible({ timeout: 5000 }); - - // The delete button (Trash2 icon) is the only button inside the key row. - await keyRow.getByRole("button").click(); - - // use2FA fires a WebAuthn ceremony to confirm the deletion; the virtual - // authenticator handles it automatically. - await expect(page.getByText("Playwright Virtual Key")).not.toBeVisible({ timeout: 10000 }); -}); - -test("WebAuthn - login no longer requires a key after removal", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - const login = page.waitForResponse(r => r.url().endsWith("/api/login") && r.request().method() === "POST"); - await loginWithPassword(page); - // webauthn_required comes back as ok: false - the password alone must succeed now. - expect(((await (await login).json()) as { ok: boolean }).ok).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); -}); - -// ── Cleanup: delete account (2FA-protected) ─────────────────────────────────── - -// Re-enable TOTP so the account deletion itself tests the 2FA confirmation gate. -test("re-enables TOTP before account deletion", async () => { - await page.goto("/settings"); - await page.getByRole("button", { name: "Set up authenticator app" }).click(); - - const secretEl = page.locator("code").first(); - await expect(secretEl).toBeVisible({ timeout: 5000 }); - totpSecret = (await secretEl.textContent())?.trim() ?? ""; - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // The passkey was removed, so this is again the only factor. - await page.locator("#totp-enrollment-password").fill(PASSWORD); - await page.getByRole("button", { name: "Enable 2FA" }).click(); - await expect(page.getByRole("button", { name: "Disable authenticator app" })).toBeVisible({ timeout: 10000 }); -}); - -test("deletes the account - 2FA confirmation required", async () => { - // "Delete account" → confirmation dialog → "Yes, delete my account" - // → runWithTwoFA fires because TOTP is active → "Confirm identity" dialog - await page.getByRole("button", { name: /delete account/i }).click(); - await expect(page.getByRole("alertdialog")).toBeVisible({ timeout: 5000 }); - await page.getByLabel("Current password", { exact: true }).fill(PASSWORD); - await page.getByRole("button", { name: /yes.*delete.*account/i }).click(); - - // use2FA opens the TOTP confirmation dialog. - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // After successful deletion the app navigates to /login. - await expect(page).toHaveURL(/\/(login|register)/, { timeout: 15000 }); -}); diff --git a/e2e/tests/admin.spec.ts b/e2e/tests/admin.spec.ts index a9d18407..fb4afb96 100644 --- a/e2e/tests/admin.spec.ts +++ b/e2e/tests/admin.spec.ts @@ -1,23 +1,22 @@ /** - * Admin panel e2e smoke: login handoff -> auto-loaded user search -> open a - * details sheet -> audited mutation visible in the audit log. + * Admin panel e2e smoke: sign in -> auto-loaded user search -> open a + * details sheet -> audited action visible in the audit log -> sign out. * * Needs the FULL dev stack (`pnpm dev` at the repo root): docs frontend 5173, - * api 8787, auth 8788, admin worker 8789, and the admin frontend on 5174. - * The whole file self-skips when the admin frontend isn't reachable, so the - * standard suite (which only assumes 5173/8787/8788) is unaffected. + * api 8787, admin worker 8789, and the admin frontend on 5174. The whole file + * self-skips when the admin frontend isn't reachable. * - * Auth: mints a dev admin via the auth worker's quick-login (DEV_QUICK_LOGIN), - * then drives the real handoff flow - POST /api/admin/handoff/start on the - * docs origin, follow redirectTo to the admin /auth/callback, and let the SPA - * exchange the single-use code. This exercises the handoff audit rows - * (admin.handoff.start/exchange) end-to-end. + * Auth: the admin panel signs in through auth.cubityfir.st (its own OIDC + * client). Locally the suite skips the identity service with the admin + * worker's localhost-only POST /api/dev/quick-login, which needs + * `DEV_QUICK_LOGIN=true` and `APP_ORIGIN=http://localhost:5174` in + * packages/admin/.dev.vars. It mints an admin dev user and an admin session. */ import { test, expect, request as pwRequest, type Page } from "@playwright/test"; const ADMIN_ORIGIN = "http://localhost:5174"; -const DOCS_ORIGIN = "http://localhost:5173"; +const RUN_ID = Date.now(); async function adminFrontendUp(): Promise { const ctx = await pwRequest.newContext(); @@ -31,44 +30,17 @@ async function adminFrontendUp(): Promise { } } -// Mint a fresh dev admin account and return its bearer token. -async function mintDevAdminToken(): Promise { - const ctx = await pwRequest.newContext({ baseURL: DOCS_ORIGIN }); - try { - const res = await ctx.post("/api/dev/quick-login", { - data: { variant: "admin-free" }, - }); - expect(res.ok(), "dev quick-login must be enabled locally (DEV_QUICK_LOGIN=true)").toBeTruthy(); - const json = (await res.json()) as { data?: { token?: string }; token?: string }; - const token = json.data?.token ?? json.token; - expect(token, "quick-login response should carry a token").toBeTruthy(); - return token!; - } finally { - await ctx.dispose(); - } -} - -// Drive the real handoff: start it as the signed-in docs user, then let the -// admin SPA consume the code at /auth/callback. -async function signInToAdmin(page: Page, token: string): Promise { - const ctx = await pwRequest.newContext({ baseURL: DOCS_ORIGIN }); - let redirectTo: string; - try { - const res = await ctx.post("/api/admin/handoff/start", { - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - data: { returnTo: `${ADMIN_ORIGIN}/auth/callback` }, - }); - expect(res.ok(), "handoff start should succeed for an admin session").toBeTruthy(); - const json = (await res.json()) as { data: { redirectTo: string } }; - redirectTo = json.data.redirectTo; - } finally { - await ctx.dispose(); - } - - await page.goto(redirectTo); - // The SPA exchanges the code, stores the (sessionStorage) token, and lands - // on the Users dashboard. +// Mints an admin session and hands it to the admin SPA, which keeps it in +// sessionStorage["admin_token"] (src/lib/auth.ts). +async function signInToAdmin(page: Page, email: string): Promise<{ token: string; userId: string }> { + const res = await page.request.post(`${ADMIN_ORIGIN}/api/dev/quick-login`, { data: { email, name: "E2E Admin" } }); + expect(res.ok(), "admin dev quick-login must be enabled locally (DEV_QUICK_LOGIN=true in packages/admin/.dev.vars)").toBeTruthy(); + const { data } = (await res.json()) as { data: { token: string; userId: string } }; + await page.goto(ADMIN_ORIGIN); + await page.evaluate(token => window.sessionStorage.setItem("admin_token", token), data.token); + await page.goto(ADMIN_ORIGIN); await expect(page.getByRole("heading", { name: "Users" })).toBeVisible({ timeout: 15_000 }); + return data; } test.describe("admin panel", () => { @@ -76,37 +48,38 @@ test.describe("admin panel", () => { test.skip(!(await adminFrontendUp()), "admin frontend (5174) is not running - start the full dev stack"); }); - test("handoff login → auto-loaded search → details sheet → audited actions in the log", async ({ page }) => { - const token = await mintDevAdminToken(); - await signInToAdmin(page, token); + test("sign in → auto-loaded search → details sheet → audited action in the log", async ({ page }) => { + const email = `e2e-admin-${RUN_ID}-a@example.com`; + const { userId } = await signInToAdmin(page, email); // AF-U1: the user list auto-loads without a search being submitted, and - // the freshly minted dev admin is newest-first on page 1. - const firstRow = page.locator("table tbody tr").first(); - await expect(firstRow).toBeVisible(); - await expect(page.getByText(/dev-[0-9a-f]+@localhost/).first()).toBeVisible(); + // the freshly minted dev admin is on page 1 (newest first). Address this + // run's row by its email: parallel specs mint users too. + const ownRow = page.locator("table tbody tr", { hasText: email }); + await expect(ownRow).toBeVisible(); - // Expand the newest user's row and open the details sheet. - await firstRow.click(); + // Expand this user's row (the only expanded one) and open the details sheet. + await ownRow.click(); await page.getByRole("button", { name: "User details" }).click(); - await expect(page.getByText("Moderation History")).toBeVisible({ timeout: 10_000 }); - await expect(page.getByText("Profile Badges")).toBeVisible(); + await expect(page.getByText("Profile Badges").first()).toBeVisible({ timeout: 10_000 }); await page.keyboard.press("Escape"); - // The handoff itself must be audited (AB-M2): the exchange that signed - // us in is the newest entry in the audit log. + // An audited action shows up in the audit log. + await page.getByRole("button", { name: "Resync display name" }).first().click(); + await expect(page.getByText(/Display name/).first()).toBeVisible({ timeout: 10_000 }); await page.getByRole("link", { name: "Audit" }).click(); await expect(page.getByRole("heading", { name: "Audit Log" })).toBeVisible(); - await expect(page.getByText("Admin · Handoff · Exchange").first()).toBeVisible({ timeout: 10_000 }); - await expect(page.getByText("Admin · Handoff · Start").first()).toBeVisible(); + // This run's entry: this actor, this target, this action. + const entry = page.locator("table tbody tr", { hasText: `user:${userId}` }) + .filter({ hasText: "User · Name · Resync" }) + .filter({ hasText: email }); + await expect(entry.first()).toBeVisible({ timeout: 10_000 }); }); test("sign out revokes the session server-side (AF-S3)", async ({ page }) => { - const token = await mintDevAdminToken(); - await signInToAdmin(page, token); + await signInToAdmin(page, `e2e-admin-${RUN_ID}-b@example.com`); - // Capture the admin token the SPA is actually using (sessionStorage now, - // not localStorage - AF-S1). + // The SPA keeps the admin token in sessionStorage, never localStorage (AF-S1). const adminToken = await page.evaluate(() => window.sessionStorage.getItem("admin_token")); expect(adminToken).toBeTruthy(); expect(await page.evaluate(() => window.localStorage.getItem("admin_token"))).toBeNull(); @@ -120,9 +93,7 @@ test.describe("admin panel", () => { // A copied token must be dead after sign-out, not valid until its TTL. const ctx = await pwRequest.newContext({ baseURL: ADMIN_ORIGIN }); try { - const res = await ctx.get("/api/verify", { - headers: { Authorization: `Bearer ${adminToken}` }, - }); + const res = await ctx.get("/api/verify", { headers: { Authorization: `Bearer ${adminToken}` } }); expect(res.status()).toBe(401); } finally { await ctx.dispose(); diff --git a/e2e/tests/app.spec.ts b/e2e/tests/app.spec.ts index 4baaa4e6..1159ec98 100644 --- a/e2e/tests/app.spec.ts +++ b/e2e/tests/app.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * The suite registers a fresh account, exercises the UI, then deletes both the * project and the account so it leaves no data behind. @@ -15,17 +15,17 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const EMAIL = `e2e-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Test User"; const PROJECT_NAME = `E2E Project ${RUN_ID}`; const PROJECT_DESCRIPTION = "Created by the Playwright E2E suite"; -// Unique fake IP so each run gets its own rate-limit bucket in the auth worker. +// Unique fake IP so each run gets its own rate-limit bucket in the api worker. const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${RUN_ID % 256}`; // ── Shared state ───────────────────────────────────────────────────────────── @@ -37,28 +37,6 @@ let projectSettingsUrl = ""; // ── Helpers ─────────────────────────────────────────────────────────────────── -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -73,7 +51,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -102,18 +79,7 @@ test.afterAll(async () => { // ── Registration ───────────────────────────────────────────────────────────── test("registers a new account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); }); // ── Dashboard ──────────────────────────────────────────────────────────────── diff --git a/e2e/tests/audio-permission-lock.spec.ts b/e2e/tests/audio-permission-lock.spec.ts index f8da0637..a91f349f 100644 --- a/e2e/tests/audio-permission-lock.spec.ts +++ b/e2e/tests/audio-permission-lock.spec.ts @@ -46,10 +46,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-audiolock-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E AudioLock User"; const PROJECT_A_NAME = `E2E AudioLock Site A ${RUN_ID}`; const PROJECT_B_NAME = `E2E AudioLock Site B ${RUN_ID}`; @@ -78,21 +78,6 @@ let fileAId = ""; let fileBId = ""; let docId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -150,7 +135,7 @@ async function uploadAudio(p: Page, projectId: string, name: string): Promise { for (let attempt = 0; attempt < 2; attempt++) { @@ -224,7 +209,6 @@ test.beforeAll(async ({ browser }) => { if (browser.browserType().name() === "chromium") { await context.grantPermissions(["clipboard-read", "clipboard-write"]); } - await mockTurnstile(context); await injectFakeIp(context); await mockExternalAudio(context); page = await context.newPage(); @@ -243,18 +227,7 @@ test.afterAll(async () => { }); test("registers, creates Site A + Site B, uploads audio to each, and a doc in Site B", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectAId = await createSite(page, PROJECT_A_NAME); fileAId = await uploadAudio(page, projectAId, FILE_A_NAME); diff --git a/e2e/tests/avatar-upload.spec.ts b/e2e/tests/avatar-upload.spec.ts index 9fd2b005..1bb161d6 100644 --- a/e2e/tests/avatar-upload.spec.ts +++ b/e2e/tests/avatar-upload.spec.ts @@ -10,17 +10,17 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars must contain DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 (e2e/signIn.ts devSignIn). */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const EMAIL = `e2e-avatar-${RUN_ID}@example.com`; -const PASSWORD = "AvatarTest-P@ssw0rd!"; const NAME = "Avatar Upload Test User"; // Offset +3 from app.spec to keep this run's rate-limit bucket separate from // other suites that may execute in parallel. @@ -69,23 +69,6 @@ let userId = ""; // ── Helpers ────────────────────────────────────────────────────────────────── -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -100,7 +83,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -113,18 +95,7 @@ test.afterAll(async () => { // ── Setup ──────────────────────────────────────────────────────────────────── test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); }); // ── Upload + verify ────────────────────────────────────────────────────────── diff --git a/e2e/tests/big-doc.spec.ts b/e2e/tests/big-doc.spec.ts index b5e15f09..1afecd60 100644 --- a/e2e/tests/big-doc.spec.ts +++ b/e2e/tests/big-doc.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-bigdoc-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Bigdoc User"; const PROJECT_NAME = `E2E Project Bigdoc ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 8) % 256}`; @@ -26,21 +26,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,7 +36,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -76,18 +60,7 @@ test.afterAll(async () => { }); test("creates a project and uploads a ~200 KB markdown doc", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/change-email.spec.ts b/e2e/tests/change-email.spec.ts deleted file mode 100644 index d247587b..00000000 --- a/e2e/tests/change-email.spec.ts +++ /dev/null @@ -1,176 +0,0 @@ -/** - * E2E tests for changing a user's email address from the settings page. - * - * Covers the flag-off (immediate apply) path only: the `email-verification` - * Flagship flag defaults off and local wrangler dev serves the real dashboard - * flag state. The confirm-first (flag-on) path is covered by the auth - * worker's unit tests. - * - * Prerequisites - run from the monorepo root before starting tests: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * - * A fresh account is registered at the start; globalTeardown wipes - * e2e-%@example.com users (both addresses used here match that pattern). - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-em-${RUN_ID}@example.com`; -const NEW_EMAIL = `e2e-em-${RUN_ID}-new@example.com`; -const PASSWORD = "ChangeEmailP@ssw0rd!"; -const NAME = "Email Change Test User"; -// Offset +4 from the other specs so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 4) % 256}`; - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // Real Turnstile re-runs the challenge on reset() and fires the render - // callback with a fresh token; the mock must replay the callback too. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { - setTimeout(() => verify?.("e2e-bypass-token"), 50); - }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function openChangeEmailDialog(p: Page) { - await p.goto("/settings"); - await p.getByRole("button", { name: "Change email address" }).click(); - await expect(p.getByRole("dialog", { name: "Change email address" })).toBeVisible({ timeout: 5000 }); -} - -const newEmailField = (p: Page) => p.getByLabel("New email address", { exact: true }); -const currentPasswordField = (p: Page) => p.getByLabel("Current password", { exact: true }); -const submitButton = (p: Page) => p.getByRole("button", { name: "Change email", exact: true }); - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. -test.afterAll(async () => { - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ── Change-email dialog ─────────────────────────────────────────────────────── - -test("change email button opens the dialog", async () => { - await openChangeEmailDialog(page); - await expect(newEmailField(page)).toBeVisible(); - await expect(currentPasswordField(page)).toBeVisible(); -}); - -test("submit is disabled while fields are empty", async () => { - // Dialog is still open from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows toast when current password is wrong", async () => { - await newEmailField(page).fill(NEW_EMAIL); - await currentPasswordField(page).fill("wrong-password"); - - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - // Dialog stays open after a failed attempt. - await expect(page.getByRole("dialog", { name: "Change email address" })).toBeVisible(); -}); - -test("successfully changes the email address", async () => { - // Retry on transient drops through the local wrangler chain: a failed PATCH - // leaves the dialog open with the fields intact. Success closes the dialog. - await expect(async () => { - await newEmailField(page).fill(NEW_EMAIL); - await currentPasswordField(page).fill(PASSWORD); - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - await expect(page.getByRole("dialog", { name: "Change email address" })).not.toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await expect(page.getByText("Email address updated", { exact: true })).toBeVisible({ timeout: 5000 }); - // The settings page now shows the new address in the (disabled) email field. - await expect(page.locator("#email")).toHaveValue(NEW_EMAIL); -}); - -// ── Verify the new email works for login ────────────────────────────────────── - -test("old email no longer logs in", async () => { - await logout(page); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - // Auth rejected. The page is already on /login, so wait for the error itself. - await expect(page.getByText("Invalid email or password.")).toBeVisible({ timeout: 8000 }); -}); - -test("new email logs in successfully", async () => { - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(NEW_EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); diff --git a/e2e/tests/change-password.spec.ts b/e2e/tests/change-password.spec.ts deleted file mode 100644 index 81030313..00000000 --- a/e2e/tests/change-password.spec.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * E2E tests for changing a user's password from the settings page. - * - * Prerequisites - run from the monorepo root before starting tests: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * - * A fresh account is registered at the start and deleted in afterAll so no - * data is left behind even if tests fail mid-way. - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-pw-${RUN_ID}@example.com`; -const PASSWORD = "OriginalP@ssw0rd!"; -const NEW_PASSWORD = "UpdatedP@ssw0rd!"; -const NAME = "Password Change Test User"; -// Offset +2 from app.spec so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 2) % 256}`; - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // Real Turnstile re-runs the challenge on reset() and fires the render - // callback with a fresh token. The login form relies on that after a - // failed submit (submit stays disabled until a new token arrives), so the - // mock must replay the callback too - a no-op reset() dead-ends the form. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { - setTimeout(() => verify?.("e2e-bypass-token"), 50); - }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function openChangePasswordDialog(p: Page) { - await p.goto("/settings"); - await p.getByRole("button", { name: "Change password" }).click(); - await expect(p.getByRole("dialog", { name: "Change password" })).toBeVisible({ timeout: 5000 }); -} - -// Helpers scoped to the dialog to avoid label-substring ambiguity. -// "New password" is a substring of "Confirm new password", so exact is required. -const currentPasswordField = (p: Page) => p.getByLabel("Current password", { exact: true }); -const newPasswordField = (p: Page) => p.getByLabel("New password", { exact: true }); -const confirmPasswordField = (p: Page) => p.getByLabel("Confirm new password", { exact: true }); -const submitButton = (p: Page) => p.getByRole("button", { name: "Change password", exact: true }).last(); - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. -test.afterAll(async () => { - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ── Change-password dialog ──────────────────────────────────────────────────── - -test("change password button opens the dialog", async () => { - await openChangePasswordDialog(page); - await expect(currentPasswordField(page)).toBeVisible(); - await expect(newPasswordField(page)).toBeVisible(); - await expect(confirmPasswordField(page)).toBeVisible(); -}); - -test("submit is disabled while fields are empty", async () => { - // Dialog is still open from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows inline error when new password is too weak", async () => { - await newPasswordField(page).fill("weak"); - // Strength meter renders a "Very weak" / "Weak" label below the field for low-score passwords. - await expect(page.getByText(/^(Very weak|Weak)$/)).toBeVisible(); -}); - -test("shows inline error when confirm does not match", async () => { - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill("different-value"); - await expect(page.getByText("Passwords do not match.")).toBeVisible(); -}); - -test("submit is disabled when passwords do not match", async () => { - // New password is strong but confirm is still mismatched from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows toast when current password is wrong", async () => { - await currentPasswordField(page).fill("wrong-password"); - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill(NEW_PASSWORD); - - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - // Dialog stays open after a failed attempt. - await expect(page.getByRole("dialog", { name: "Change password" })).toBeVisible(); -}); - -test("successfully changes the password", async () => { - // Retry on transient drops through the local wrangler chain: a failed PATCH - // leaves the dialog open with the fields intact, so re-submitting is safe. - // Success closes the dialog. - await expect(async () => { - await currentPasswordField(page).fill(PASSWORD); - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill(NEW_PASSWORD); - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - await expect(page.getByRole("dialog", { name: "Change password" })).not.toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await expect(page.getByText("Password changed", { exact: true })).toBeVisible({ timeout: 5000 }); -}); - -// ── Verify new password works ───────────────────────────────────────────────── - -test("old password no longer works", async () => { - await logout(page); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - // Auth rejected. The page is already on /login, so wait for the error itself. - await expect(page.getByText("Invalid email or password.")).toBeVisible({ timeout: 8000 }); -}); - -test("new password logs in successfully", async () => { - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(NEW_PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// Account cleanup runs in globalTeardown (e2e/global-teardown.ts). -// The 2FA-gated delete path is covered by 2fa.spec.ts. diff --git a/e2e/tests/collab.spec.ts b/e2e/tests/collab.spec.ts index 04e746c7..f40958ba 100644 --- a/e2e/tests/collab.spec.ts +++ b/e2e/tests/collab.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Covers: * 1. Two pages on the same doc see each other's edits within the editor @@ -25,10 +25,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-collab-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Collab User"; // Prefix matches the "E2E Project %" pattern in global-teardown, so the // safety-net cleanup catches this project even if afterAll never runs. @@ -43,23 +43,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -86,7 +69,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); pageA = await context.newPage(); }); @@ -115,18 +97,7 @@ test.afterAll(async () => { test("sets up a project + doc with the realtime flag enabled", async () => { // Register - await pageA.goto("/register"); - await pageA.getByLabel("Name").fill(NAME); - await pageA.getByLabel("Email").fill(EMAIL); - await pageA.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(pageA.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await pageA.getByRole("button", { name: "Create account" }).click(); - await expect(pageA).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(pageA, { email: EMAIL, name: NAME }); // Create project await pageA.goto("/dashboard"); diff --git a/e2e/tests/excalidraw.spec.ts b/e2e/tests/excalidraw.spec.ts index e94834bf..0a4e829e 100644 --- a/e2e/tests/excalidraw.spec.ts +++ b/e2e/tests/excalidraw.spec.ts @@ -20,10 +20,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-excalidraw-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Excalidraw User"; const PROJECT_NAME = `E2E Excalidraw Site ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 37) % 256}`; @@ -33,21 +33,6 @@ let page: Page; let projectId = ""; let fileId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -100,7 +85,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -111,18 +95,7 @@ test.afterAll(async () => { }); test("registers and creates a site", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectId = await createSite(page, PROJECT_NAME); expect(projectId).toBeTruthy(); diff --git a/e2e/tests/export.spec.ts b/e2e/tests/export.spec.ts index c8937ec4..48bcf557 100644 --- a/e2e/tests/export.spec.ts +++ b/e2e/tests/export.spec.ts @@ -13,10 +13,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { readFile } from "node:fs/promises"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-exp-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Export User"; const PROJECT_NAME = `E2E Project Export ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 11) % 256}`; @@ -26,21 +26,6 @@ let page: Page; let projectId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,7 +36,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -76,18 +60,7 @@ test.afterAll(async () => { }); test("sets up a project with two docs (root + folder)", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/file-permission-lock.spec.ts b/e2e/tests/file-permission-lock.spec.ts index a199c2da..63832016 100644 --- a/e2e/tests/file-permission-lock.spec.ts +++ b/e2e/tests/file-permission-lock.spec.ts @@ -37,10 +37,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-filelock-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E FileLock User"; const PROJECT_A_NAME = `E2E FileLock Site A ${RUN_ID}`; const PROJECT_B_NAME = `E2E FileLock Site B ${RUN_ID}`; @@ -68,21 +68,6 @@ let fileAId = ""; let fileBId = ""; let docId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -140,7 +125,7 @@ async function uploadImage(p: Page, projectId: string, name: string): Promise { for (let attempt = 0; attempt < 2; attempt++) { @@ -214,7 +199,6 @@ test.beforeAll(async ({ browser }) => { if (isChromium) { await context.grantPermissions(["clipboard-read", "clipboard-write"]); } - await mockTurnstile(context); await injectFakeIp(context); await mockExternalImage(context); page = await context.newPage(); @@ -233,18 +217,7 @@ test.afterAll(async () => { }); test("registers, creates Site A + Site B, uploads an image to each, and a doc in Site B", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectAId = await createSite(page, PROJECT_A_NAME); fileAId = await uploadImage(page, projectAId, FILE_A_NAME); diff --git a/e2e/tests/file-settings.spec.ts b/e2e/tests/file-settings.spec.ts index bc1e3787..6c29f112 100644 --- a/e2e/tests/file-settings.spec.ts +++ b/e2e/tests/file-settings.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-docset-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E DocSettings User"; const PROJECT_NAME = `E2E Project DocSettings ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 12) % 256}`; @@ -26,21 +26,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -49,7 +34,7 @@ async function injectFakeIp(ctx: BrowserContext) { async function putDoc(p: Page, id: string, title: string, content: string) { // Local wrangler dev intermittently drops requests through the - // browser → vite → API worker → auth worker chain (per playwright.config.ts). + // browser → vite → API worker chain (per playwright.config.ts). // Retry once on 500 so transient infra hiccups don't cause spurious failures. const result = await p.evaluate(async ({ id, title, content }) => { for (let attempt = 0; attempt < 2; attempt++) { @@ -87,7 +72,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -112,18 +96,7 @@ test.afterAll(async () => { }); test("sets up a project + doc", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/image-paste.spec.ts b/e2e/tests/image-paste.spec.ts index cf8a57e4..12c702d5 100644 --- a/e2e/tests/image-paste.spec.ts +++ b/e2e/tests/image-paste.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-paste-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Paste User"; const PROJECT_NAME = `E2E Project Paste ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 7) % 256}`; @@ -29,21 +29,6 @@ let context: BrowserContext; let page: Page; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -54,7 +39,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -86,18 +70,7 @@ test("pastes a PNG into the editor, uploads to /api/files, inserts markdown, and test.skip(browserName === "firefox", "synthetic clipboard File payloads not supported in Firefox"); // Register + project + doc. - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/ink-features.spec.ts b/e2e/tests/ink-features.spec.ts index 75baee6d..be053f66 100644 --- a/e2e/tests/ink-features.spec.ts +++ b/e2e/tests/ink-features.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Strategy: the Ink section of /settings only renders when the user's plan * resolves to "ink". Two ways to get there in dev: @@ -21,10 +21,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-ink-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Ink User"; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 13) % 256}`; @@ -32,21 +32,6 @@ let context: BrowserContext; let page: Page; let userId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -55,14 +40,13 @@ async function injectFakeIp(ctx: BrowserContext) { function grantInk(uid: string) { const sql = `INSERT INTO user_billing (user_id, granted_plan, granted_plan_started_at) VALUES ('${uid}', 'ink', ${Date.now()}) ON CONFLICT(user_id) DO UPDATE SET granted_plan = 'ink', granted_plan_started_at = ${Date.now()};`; - d1Local("auth", sql); + d1Local("main", sql); } test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -72,18 +56,7 @@ test.afterAll(async () => { }); test("registers a fresh account and grants Annex Ink via the auth DB", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); // Grab the user id so we can write a granted_plan row keyed to it. userId = await page.evaluate(async () => { diff --git a/e2e/tests/invites.spec.ts b/e2e/tests/invites.spec.ts index 23e2809a..3ea93d0e 100644 --- a/e2e/tests/invites.spec.ts +++ b/e2e/tests/invites.spec.ts @@ -3,21 +3,22 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true + APP_ORIGIN=http://localhost:5173 (devSignIn) * * Three accounts are created: owner, email-invitee, link-invitee. * The project and all three accounts are deleted in afterAll even on failure. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const PROJECT_NAME = `Invite Test ${RUN_ID}`; -const OWNER = { name: "Invite Owner", email: `e2e-inv-owner-${RUN_ID}@example.com`, password: "OwnerP@ssw0rd!" }; -const EMAIL_USER = { name: "Email Invitee", email: `e2e-inv-email-${RUN_ID}@example.com`, password: "InviteeP@ssw0rd!" }; +const OWNER = { name: "Invite Owner", email: `e2e-inv-owner-${RUN_ID}@example.com` }; +const EMAIL_USER = { name: "Email Invitee", email: `e2e-inv-email-${RUN_ID}@example.com` }; const LINK_USER = { name: "Link Invitee", email: `e2e-inv-link-${RUN_ID}@example.com`, password: "LinkP@ssw0rd!" }; // Offsets +3/+4/+5 keep each account in its own rate-limit bucket, @@ -39,25 +40,6 @@ let inviteLinkToken = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - verify = opts.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); @@ -65,32 +47,13 @@ async function setupContext(browser: Browser, ip: string): Promise<[BrowserConte } async function register(page: Page, user: typeof OWNER) { - await page.goto("/register"); - await page.getByLabel("Name").fill(user.name); - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } +// The same email always signs the same dev user back in (replacing any +// session this page had). async function login(page: Page, user: typeof OWNER) { - // /login?logout=1 clears any existing token first so this is always reliable. - await page.goto("/login?logout=1"); - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/limited-permissions.spec.ts b/e2e/tests/limited-permissions.spec.ts index b7a03810..2bd3eb0b 100644 --- a/e2e/tests/limited-permissions.spec.ts +++ b/e2e/tests/limited-permissions.spec.ts @@ -10,13 +10,14 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true + APP_ORIGIN=http://localhost:5173 (devSignIn) * * Two accounts are created: owner, limited. Both accounts and the project * are cleaned up in afterAll / globalTeardown even on failure. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── @@ -26,7 +27,7 @@ const DOC_TITLE = "Limited Access Doc"; // A distinct phrase so we can assert the rendered body is what the owner wrote. const DOC_CONTENT_PHRASE = "Limited share content sentinel."; -const OWNER = { name: "Limited Perm Owner", email: `e2e-limited-owner-${RUN_ID}@example.com`, password: "OwnerP@ssw0rd!" }; +const OWNER = { name: "Limited Perm Owner", email: `e2e-limited-owner-${RUN_ID}@example.com` }; const LIMITED = { name: "Limited Perm User", email: `e2e-limited-user-${RUN_ID}@example.com`, password: "LimitedP@ssw0rd!" }; // Offsets +6/+7 keep these accounts in their own rate-limit buckets, separate @@ -47,25 +48,6 @@ let docId = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - verify = opts.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); @@ -73,32 +55,13 @@ async function setupContext(browser: Browser, ip: string): Promise<[BrowserConte } async function register(page: Page, user: typeof OWNER) { - await page.goto("/register"); - await page.getByLabel("Name").fill(user.name); - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } +// The same email always signs the same dev user back in (replacing any +// session this page had). async function login(page: Page, user: typeof OWNER) { - // /login?logout=1 clears any existing token first so this is always reliable. - await page.goto("/login?logout=1"); - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/markdown.spec.ts b/e2e/tests/markdown.spec.ts index 6b7273e0..41f77db8 100644 --- a/e2e/tests/markdown.spec.ts +++ b/e2e/tests/markdown.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Strategy: instead of typing each markdown element through the editor (which * is slow and surfaces typing-time autocomplete behaviours, not rendering), @@ -16,10 +16,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-md-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Markdown User"; const PROJECT_NAME = `E2E Project Markdown ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 6) % 256}`; @@ -31,22 +31,6 @@ let docId = ""; let linkedDocId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -81,7 +65,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -106,18 +89,7 @@ test.afterAll(async () => { }); test("sets up an account, project, and two docs (one as wikilink target)", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/orgs.spec.ts b/e2e/tests/orgs.spec.ts index 1f6d980b..c4f0f9f3 100644 --- a/e2e/tests/orgs.spec.ts +++ b/e2e/tests/orgs.spec.ts @@ -5,15 +5,14 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: DEV_QUICK_LOGIN=true (+ APP_ORIGIN=http://localhost:5173) + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true (+ APP_ORIGIN=http://localhost:5173) * - * Accounts are created via the dev quick-login panel on /login (the project's - * credential-free localhost dev shortcut) rather than the register form, so the - * suite is independent of the Flagship "signup" flag. Both accounts are removed - * in globalTeardown; the site is deleted by the test body / afterAll. + * Accounts are created with e2e/signIn.ts (devSignIn, the localhost-only dev + * quick login). Both accounts are removed in globalTeardown; the site is deleted by the test body / afterAll. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── @@ -39,42 +38,18 @@ let siteId = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); return [ctx, await ctx.newPage()]; } -// Logs in via the DEV-only quick-login panel and returns the freshly-minted dev -// user's email (decoded from the returned JWT — quick-login creates a random -// dev-@localhost account each time). +// Signs in a fresh dev user (localhost-only quick login) and returns its email. +let devUsers = 0; async function devLogin(page: Page): Promise { - await page.goto("/login?logout=1"); - const respPromise = page.waitForResponse( - r => r.url().includes("/api/dev/quick-login") && r.request().method() === "POST", - ); - // First "Free" button is the Standard (non-admin) row. - await page.getByRole("button", { name: "Free", exact: true }).first().click(); - const resp = await respPromise; - const body = await resp.json() as { ok: boolean; data: { token: string } }; - expect(body.ok).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); - const payload = JSON.parse(Buffer.from(body.data.token.split(".")[1], "base64").toString()) as { email: string }; - return payload.email; + const email = `e2e-org-${RUN_ID}-${++devUsers}@example.com`; + await devSignIn(page, { email, name: `Org User ${devUsers}` }); + return email; } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/profile-card.spec.ts b/e2e/tests/profile-card.spec.ts index 6e407cd2..f06768b6 100644 --- a/e2e/tests/profile-card.spec.ts +++ b/e2e/tests/profile-card.spec.ts @@ -17,10 +17,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-prof-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Profile User"; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 14) % 256}`; @@ -28,21 +28,6 @@ let context: BrowserContext; let page: Page; let userId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,14 +36,13 @@ async function injectFakeIp(ctx: BrowserContext) { function grantInk(uid: string) { const sql = `INSERT INTO user_billing (user_id, granted_plan, granted_plan_started_at) VALUES ('${uid}', 'ink', ${Date.now()}) ON CONFLICT(user_id) DO UPDATE SET granted_plan = 'ink', granted_plan_started_at = ${Date.now()};`; - d1Local("auth", sql); + d1Local("main", sql); } test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -68,22 +52,11 @@ test.afterAll(async () => { }); test("registers, grants Ink, and writes a bio + timezone", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); - // Right after register the token is in localStorage but the auth worker's + // Right after sign-in the token is in localStorage but the // session row may still be propagating; retry a few times so we don't race - // on the auth/api worker handshake. + // on the api worker. userId = await page.evaluate(async () => { for (let i = 0; i < 5; i++) { const token = localStorage.getItem("token"); diff --git a/e2e/tests/publishing.spec.ts b/e2e/tests/publishing.spec.ts index 57127c5d..2cacc94b 100644 --- a/e2e/tests/publishing.spec.ts +++ b/e2e/tests/publishing.spec.ts @@ -13,10 +13,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-pub-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Publish User"; const PROJECT_NAME = `E2E Project Publish ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 9) % 256}`; @@ -29,21 +29,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext, ip: string) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); @@ -54,7 +39,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context, FAKE_IP); page = await context.newPage(); }); @@ -80,18 +64,7 @@ test.afterAll(async () => { }); test("creates a project + doc and publishes the site", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/scroll-to-heading.spec.ts b/e2e/tests/scroll-to-heading.spec.ts index cedc0457..f98149f3 100644 --- a/e2e/tests/scroll-to-heading.spec.ts +++ b/e2e/tests/scroll-to-heading.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Covers two flows on the published-doc page: * 1. Loading /s//# scrolls the article viewport @@ -22,10 +22,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-scroll-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Scroll User"; const PROJECT_NAME = `E2E Scroll ${RUN_ID}`; @@ -47,23 +47,6 @@ let appDocUrl = ""; const PUBLIC_SCROLLER = ".public-doc-scroller [data-radix-scroll-area-viewport]"; const APP_SCROLLER = ".app-main-scroller"; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -115,7 +98,6 @@ test.beforeAll(async ({ browser }) => { // Outline rail only renders at the xl breakpoint (1280px+). 1440 gives it // plenty of room and matches a common laptop width. context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -141,18 +123,7 @@ test.afterAll(async () => { test("sets up a published doc with multiple headings", async () => { // Register - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); // Create project await page.goto("/dashboard"); diff --git a/memories/Api-Keys.md b/memories/Api-Keys.md index 6b04eff5..8bff2a76 100644 --- a/memories/Api-Keys.md +++ b/memories/Api-Keys.md @@ -22,10 +22,9 @@ index = lookup index), `key_prefix` (display only), `scope` (`read|readwrite` CHECK), `can_invite` (0/1), `created_at`, `last_used_at`, `expires_at`, `revoked_at`. -**Why the API DB, not auth DB:** keys are project-scoped (real FK + cascade), and -management is a plain API-worker write - keeping them out of the read-only -`AUTH_DB` avoids a new auth-worker write path and the 3-package redeploy coupling -that auth-table schema changes carry. The owner is just a stored user id. +**Why the API DB:** keys are project-scoped (real FK + cascade), and management is +a plain API-worker write. The owner is just a stored user id (= the users +mirror id / OIDC `sub`). ## Security model - the load-bearing invariants @@ -40,8 +39,9 @@ that auth-table schema changes carry. The owner is just a stored user id. **live** `project_members` role (accepted only). A `readwrite` key still needs the owner to be editor+; a `can_invite` key still needs admin+. Removing the owner from the site **instantly neuters all their keys**. `authenticateApiKey` - also reads the owner's `users` row via `AUTH_DB`: a deleted, disabled, - suspended, or force-password-change account's keys 401, same as its JWTs. + also checks the owner's users-mirror row and live standing (identity + service, cached ~60s): a deleted, disabled or suspended account - or one + blocked by a pending admin deletion - gets 401, same as its sessions. 3. **Token discrimination.** Keys are prefixed `annx_`; JWTs are 3 dot-separated segments and never carry the prefix. `isApiKeyToken()` separates them. 4. **Hashing.** Store only `SHA-256(secret)` (fast hash is correct for diff --git a/memories/Collab.md b/memories/Collab.md index 9689848b..3c703a8b 100644 --- a/memories/Collab.md +++ b/memories/Collab.md @@ -20,7 +20,7 @@ Browser ↔ WebSocket `/api/docs/:id/collab?token=` ↔ API Worker (auth + ## WebSocket auth -Token passed as `?token=` (browsers can't set headers on WS); API worker re-wraps it as `Authorization: Bearer` and calls `authenticate()`, which verifies inline against `AUTH_DB` (see CLAUDE.md "Verification boundary"). +Token passed as `?token=` (browsers can't set headers on WS); API worker re-wraps it as `Authorization: Bearer` and calls `authenticate()`, which verifies the Annex session inline against cubedocs-main (see CLAUDE.md "Auth"). Live sockets are re-checked periodically (`revalidateAccess`): session row, admin-deletion block, and identity standing. The API worker hands identity to the DO via `X-User-Id` / `X-User-Name` (URI-encoded) / `X-Project-Id` / `X-Doc-Id` / `X-Session-Id`, always set with `Headers.set` so a client can't smuggle its own copies (a record spread of `request.headers` would *append* them). Sockets are authorized once at upgrade, so `DocCollabRoom.revalidateAccess` (throttled to `AUTH_RECHECK_MS`, driven by traffic) re-checks both effective role (editor+) and the socket's auth session (`sessionStillValid`: revoked / expired / force-password-change / disabled / suspended) and closes failures with 1008. Lookup errors fail open. diff --git a/memories/Identity-Client.md b/memories/Identity-Client.md new file mode 100644 index 00000000..75c35b49 --- /dev/null +++ b/memories/Identity-Client.md @@ -0,0 +1,148 @@ +# Identity: Annex as a client of auth.cubityfir.st + +Accounts live on the standalone identity service at **https://auth.cubityfir.st** +(worker `cubityfirst-auth`, its own repo and D1 `cubityfirst-auth`). It does +registration, sign-in (password, TOTP, passkeys with RP ID `cubityfir.st`), +email changes, sessions on its side, moderation (disable/suspend), the admin +role, account deletion, and OAuth client management (`/admin/clients`). Annex is +an OpenID Connect client like any other service. Annex keeps its own sessions, +a users mirror, and everything Annex-specific (Ink billing, preferences, +handles, badges, sites). + +## Bindings (api + admin workers) + +| Binding | Target | Used for | +| --- | --- | --- | +| `IDENTITY` | `cubityfirst-auth`, entrypoint `IdentityService` | `getUser` (standing, ~60s cache), `findUserByEmail` (invites), `listDeletedUsers` (deletion sync) | +| `IDENTITY_OIDC` | `cubityfirst-auth` default export | discovery, JWKS, token: **every server-side OIDC request** | + +Annex's workers share the cubityfir.st zone with auth.cubityfir.st. A Worker's +`fetch()` to another Worker's hostname on the same zone goes to the origin (a +placeholder record), not to that Worker, so server-side OIDC requests must use +`IDENTITY_OIDC` (`identityFetch` in `packages/api/src/account/oidc.ts`). Only +the browser redirects (authorize, logout) use the public URL. Requests over a +binding carry no `CF-Connecting-IP`, so the provider rate-limits them per +client_id (100/min for token, again for userinfo) - fine at current volume. + +Post-logout URIs are matched byte for byte: they're registered as the bare +origin (no trailing slash), which is the default `APP_ORIGIN` sends. + +Vars: `OIDC_ISSUER`, `OIDC_CLIENT_ID` (docs: `oidc_7369d6d5736d2bea35f1ab47`; +admin: `oidc_07c81f4a5aa63dd2bd0b15cc`), `APP_ORIGIN`; optional `OIDC_REDIRECT_URI`, +`OIDC_POST_LOGOUT_REDIRECT_URI`. Secret: `OIDC_CLIENT_SECRET`. + +## Registering the clients (auth.cubityfir.st/admin/clients) + +| Client | Redirect URI | Post-logout URI | Scopes | First-party | +| --- | --- | --- | --- | --- | +| docs app (`oidc_7369d6d5736d2bea35f1ab47`) | `https://docs.cubityfir.st/api/auth/callback` | `https://docs.cubityfir.st` | `openid profile email roles` | yes | +| admin panel (`oidc_07c81f4a5aa63dd2bd0b15cc`) | `https://admin.cubityfir.st/api/auth/callback` | `https://admin.cubityfir.st` | `openid profile email roles` | yes | + +Local dev clients: `http://localhost:5173/api/auth/callback` (docs) and +`http://localhost:5174/api/auth/callback` (admin), against a local identity +worker on :8790. + +## Flow (packages/api/src/routes/auth.ts, shared by admin via AuthFlow) + +1. `GET /api/auth/login?return_to=` - PKCE S256 verifier, state, nonce sealed + (HMAC with `JWT_SECRET`) into the HttpOnly `annex_oidc_` cookie (one + per sign-in, so two tabs don't clobber each other; path `/api/auth`, 10 min); 302 to the authorize endpoint from discovery. +2. `GET /api/auth/callback` - opens the cookie, `validateAuthResponse` (state, + `iss`), code exchange with `client_secret_basic`, + `processAuthorizationCodeResponse` (iss, aud, exp, nonce, RS256 pinned) and + `validateApplicationLevelSignature` (JWKS). Refuses ids in + `identity_deletions` (`account_deleted`) or `user_deletions` + (`account_disabled`), and non-admins for the admin client (`not_admin`). + Upserts the users mirror (+ member snapshots; every mirror write that + changes the email also updates the Stripe customer's, `refreshMirror`) and creates a session row with a single-use `handoff_hash`. +3. Sets the handoff code as the HttpOnly, SameSite=Strict + `annex_handoff_` cookie (60s; never in a URL, so a leaked/crafted + completion link signs no one in; one cookie per sign-in, so two finishing + at once in one browser don't swap) and 302s to + `/auth/complete#status=ok&attempt=&return_to=…` (or + `#error=`). +4. SPA `POST /api/auth/exchange?attempt=` (no body; the browser sends the cookie) - + redeems it once for the HS256 session JWT. The docs app keeps it in localStorage, the admin panel + in sessionStorage. +5. `POST /api/auth/logout` - revokes the session, returns the end-session URL + with `id_token_hint` + `post_logout_redirect_uri`. + +`loadCurrentSession(token, env, kind)` (`account/session.ts`) re-derives +everything per request; standing comes from `IDENTITY.getUser` (cache ~60s, +mirror fallback when unreachable). `kind` (`app`/`admin`) keeps docs and admin +tokens apart. Tokens last 1h on the provider and there are no refresh tokens; +Annex sessions last 7 days (admin 12h) independently. + +Local dev without the identity worker: `DEV_QUICK_LOGIN=true` + +`APP_ORIGIN=http://localhost:5173` enables `POST /api/dev/quick-login` (dev +users have ids `dev-…`; standing checks skip the RPC for them). + +## Deletion + +- **Identity deletion** (user deletes their account on auth.cubityfir.st, or + an operator does there): hourly api cron `23 * * * *` + (`lib/identityDeletions.ts`) records it in `identity_deletions`, deletes the + Stripe customer, memberships, API keys, shares, favourites, avatars and the + users mirror row. **Owned sites/orgs are kept** and shown on the admin + Projects page ("Owner account deleted") for an operator to resolve. +- **Admin-scheduled deletion** (Annex admin Users page): deletes Annex data + only after 7 days; the person stays blocked from Annex; the operator then + deletes the account on auth.cubityfir.st, and the sync finishes the rest. + +## Cutover (the user runs these; never automatic) + +The identity service went live 2026-11-18 (~16:33 UTC) with a fresh import of +cubedocs-auth and a new signing key. Until this branch ships, annex-auth still +serves Annex logins and **account changes drift** between the two stores. + +1. Ship `chore(auth): retire annex-auth's OIDC provider` before/with any + annex-auth deploy (removes the `auth.cubityfir.st` routes). +2. Register the two clients above on auth.cubityfir.st, **disabled** (they + stay disabled until step 7, so nobody can sign in to Annex before + reconciliation); set + `OIDC_CLIENT_SECRET` on annex-api and annex-admin (`npx wrangler secret put + OIDC_CLIENT_SECRET --name annex-api` / `--name annex-admin`), move + `STRIPE_SECRET_KEY` + `STRIPE_WEBHOOK_SECRET` to annex-api, and fix + `OIDC_CLIENT_ID` in the configs if the registered ids differ. +3. Apply api migration 0065 remotely (`node scripts/migrate.mjs remote`). +4. Freeze, then export and import. cubedocs-auth stays writable until the new + code is live, and anything written there after the export is lost, so keep + the window short and quiet (export, import and step 5 back to back, within + minutes, and not across :17 past the hour when the old admin cron runs + scheduled deletions): turn off sign-ups on the old Annex and let in-flight + registrations finish (an account made between the export and step 5 + misses this import), note the time, don't schedule or cancel admin + deletions or change grants/badges/handles in the admin panel, then + `npx wrangler d1 export cubedocs-auth --remote --output migration-data/cubedocs-auth.sql`, + `node scripts/import-auth-data.mjs migration-data/cubedocs-auth.sql`, + `npx wrangler d1 execute cubedocs-main --remote --file migration-data/annex-import.sql`. + Keep `migration-data/` for the reconciliation in step 7. +5. Deploy api, then admin, then frontend. Everyone signs in again (old Annex + JWTs don't validate against the new sessions table). +6. Replay Stripe: events the old worker handled between the export and the + deploy were applied to cubedocs-auth only. In the Stripe Dashboard + (Developers → Webhooks → the docs.cubityfir.st endpoint) resend every event + since the time noted in step 4. The handler is idempotent + (`webhook_events`), so overlap is harmless. +7. Reconcile, once nothing routes to the old login/register/delete-account + routes (after step 5): take a FINAL export of cubedocs-auth and compare its + user ids with the identity service's actual import snapshot (the + `import.sql` it was loaded from on 2026-11-18). Compare ids, not dates: + accounts created on auth.cubityfir.st since its import are never involved. + - **Deletions** - ids in the snapshot but absent from the final export were + deleted on the old Annex after that import and could otherwise sign back + in. Delete them at auth.cubityfir.st/admin/users. + - **Additions** - ids in the final export but absent from the snapshot + registered on the old Annex after that import. Step 4 already mirrored + them (with their sites and billing) under that id, but auth.cubityfir.st + has no such account: registering there would mint a new id and strand + their Annex data. Add them to cubityfirst-auth **with their original + ids** (users + recovery codes, from the final export). The identity + repo's `import-from-annex.mjs` replaces every user, so it can't be re-run + now; this needs an additions-only import from that repo. If an addition's + email has since been registered on auth.cubityfir.st under a new id, + resolve it by hand. + + Then **enable** the two Annex clients and delete `migration-data/`. +8. Retire annex-auth (`npx wrangler delete annex-auth`) once traffic is on the + new code, and later cubedocs-auth after a backup. diff --git a/memories/Ink-Stripe.md b/memories/Ink-Stripe.md index 898b6e4b..03804d99 100644 --- a/memories/Ink-Stripe.md +++ b/memories/Ink-Stripe.md @@ -44,7 +44,7 @@ Plus `webhook_events (event_id PRIMARY KEY, type, processed_at)` for idempotency ## Plan resolution -**Always go through `resolvePersonalPlan` in `packages/auth/src/plan.ts`.** Never read the columns directly to determine plan state. The resolver is a pure function with this precedence: +**Always go through `resolvePersonalPlan` in `packages/api/src/account/plan.ts`.** Never read the columns directly to determine plan state. The resolver is a pure function with this precedence: 1. `granted_plan` set AND (`granted_plan_expires_at` is NULL OR in the future) → `via: 'granted'`, `status: 'granted'` 2. `personal_plan` set AND `personal_plan_status` ∈ `{active, trialing, past_due}` → `via: 'paid'` @@ -56,13 +56,13 @@ The resolver's input row mixes columns from BOTH satellite tables (`personal_pla ## Cross-package consideration -The API worker reads `users`, `user_billing`, and `user_preferences` directly via the `AUTH_DB` binding (read-only by convention) for `loadCurrentSession`, member-list plan info, and `/users/:id` profile responses. The admin worker also reads them for the user details panel. +`users` (the identity mirror), `user_billing` and `user_preferences` live in cubedocs-main (api migration 0065; copied from the retired cubedocs-auth). The API worker reads them for `loadCurrentSession`, member-list plan info and `/users/:id`; the admin worker reads/writes them for the user details panel and grants. -**A schema change to any column the resolver touches requires redeploying auth + api + admin** in that order, AND every reader must continue to use LEFT JOIN so older code transitioning to a missing-satellite world still behaves. The migrations live in `packages/auth/migrations/` only. +**A schema change to any column the resolver touches requires redeploying api + admin** (api first), AND every reader must continue to use LEFT JOIN so a user without a satellite row still behaves. Migrations live in `packages/api/migrations/`. ## Stripe webhook flow -`packages/auth/src/routes/stripe-webhook.ts`. Public endpoint, signature-verified. Reached via `https://docs.cubityfir.st/stripe/webhook` - the frontend worker proxies `/stripe/webhook` to auth via service binding (see `packages/frontend/worker/index.ts`). Stripe doesn't see the auth worker directly because it has no public hostname. +`packages/api/src/routes/stripeWebhook.ts`. Public endpoint, signature-verified. Reached via `https://docs.cubityfir.st/stripe/webhook` - the frontend worker forwards `/stripe/webhook` verbatim to the api worker via service binding (see `packages/frontend/worker/index.ts`), so the URL registered in the Stripe Dashboard didn't change when billing moved off the retired auth worker. An event for a user Annex no longer has (FK failure on `user_billing`) is acknowledged, not retried. Handler contract (load-bearing): @@ -87,21 +87,21 @@ Admin worker calls Stripe REST directly with its own `STRIPE_SECRET_KEY` (set pe `.dev.vars` files (gitignored) hold local secrets: -- `packages/auth/.dev.vars` needs `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_INK_PRICE_ID`, `APP_ORIGIN=http://localhost:5173` +- `packages/api/.dev.vars` needs `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_INK_PRICE_ID`, `APP_ORIGIN=http://localhost:5173` - `packages/admin/.dev.vars` needs `STRIPE_SECRET_KEY` only -Forward Stripe webhook events to the local auth worker: +Forward Stripe webhook events to the local api worker: ``` -stripe listen --forward-to http://localhost:8788/stripe/webhook +stripe listen --forward-to http://localhost:8787/stripe/webhook ``` -The CLI prints a `whsec_...` at startup - that's what goes in `STRIPE_WEBHOOK_SECRET` for local dev. (Live mode uses a different `whsec_` from the registered webhook in Stripe Dashboard.) Restart the auth worker after editing `.dev.vars` - wrangler only reads it on startup. +The CLI prints a `whsec_...` at startup - that's what goes in `STRIPE_WEBHOOK_SECRET` for local dev. (Live mode uses a different `whsec_` from the registered webhook in Stripe Dashboard.) Restart the api worker after editing `.dev.vars` - wrangler only reads it on startup. ## Production setup -- `STRIPE_INK_PRICE_ID` is a `bindings.text` var in `packages/auth/cloudflare.config.ts` (live price id - committed). `.dev.vars` overrides locally to the test-mode price id. -- `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` set via `wrangler secret put` on the auth worker. `STRIPE_SECRET_KEY` also on admin worker. +- `STRIPE_INK_PRICE_ID` is a `bindings.text` var in `packages/api/cloudflare.config.ts` (live price id - committed). `.dev.vars` overrides locally to the test-mode price id. +- `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` set via `npx wrangler secret put` on annex-api (they used to be on annex-auth - move them at cutover). `STRIPE_SECRET_KEY` also on annex-admin. - Webhook endpoint URL in Stripe Dashboard: `https://docs.cubityfir.st/stripe/webhook`. Subscribed events: `checkout.session.completed`, `customer.subscription.created/updated/deleted`, `invoice.paid`, `invoice.payment_failed`. - Customer Portal must be configured separately in **live** mode (Settings → Billing → Customer portal). Test mode and live mode have different portal configs. diff --git a/memories/Worktree-Dev.md b/memories/Worktree-Dev.md index 43d7de2f..5b7799a9 100644 --- a/memories/Worktree-Dev.md +++ b/memories/Worktree-Dev.md @@ -7,9 +7,9 @@ browser on its own port - while a single shared backend serves them all. Driven ## The model ``` -main checkout G:\Scripts\cubedocs → pnpm dev (frontend 5173 + api 8787 + auth 8788 +main checkout G:\Scripts\cubedocs → pnpm dev (frontend 5173 + api 8787 + admin 8789 + the shared .wrangler/state D1) ── full - stack; the api/auth/admin here are the ONE backend + stack; the api/admin here are the ONE backend worktree A ..\cubedocs-worktrees\feat-x (branch feat-x) → vite --port 5200 ─┐ worktree B ..\cubedocs-worktrees\feat-y (branch feat-y) → vite --port 5201 ─┼─ all proxy /api → :8787 worktree C ... → vite --port 5202 ─┘ diff --git a/package.json b/package.json index 502a1a36..c57386cc 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,15 @@ "private": true, "version": "0.0.2", "scripts": { - "dev": "concurrently \"pnpm --filter frontend dev\" \"pnpm --filter api dev\" \"pnpm --filter auth dev\" \"pnpm --filter @annex/admin dev\"", - "dev:stripe": "stripe listen --forward-to http://localhost:8788/stripe/webhook", - "build": "concurrently \"pnpm --filter frontend build\" \"pnpm --filter api build\" \"pnpm --filter auth build\" \"pnpm --filter @annex/admin build\"", - "deploy": "concurrently \"pnpm --filter frontend deploy\" \"pnpm --filter api deploy\" \"pnpm --filter auth deploy\" \"pnpm --filter @annex/admin deploy\"", - "typecheck": "concurrently \"pnpm --filter frontend typecheck\" \"pnpm --filter api typecheck\" \"pnpm --filter auth typecheck\" \"pnpm --filter @annex/admin typecheck\" \"pnpm --filter @annex/admin-frontend typecheck\" \"pnpm --filter @annex/mcp typecheck\"", - "migrate": "pnpm --filter api migrate && pnpm --filter auth migrate", + "dev": "concurrently \"pnpm --filter frontend dev\" \"pnpm --filter api dev\" \"pnpm --filter @annex/admin dev\"", + "dev:stripe": "stripe listen --forward-to http://localhost:8787/stripe/webhook", + "build": "concurrently \"pnpm --filter frontend build\" \"pnpm --filter api build\" \"pnpm --filter @annex/admin build\"", + "deploy": "concurrently \"pnpm --filter frontend deploy\" \"pnpm --filter api deploy\" \"pnpm --filter @annex/admin deploy\"", + "typecheck": "concurrently \"pnpm --filter frontend typecheck\" \"pnpm --filter api typecheck\" \"pnpm --filter @annex/admin typecheck\" \"pnpm --filter @annex/admin-frontend typecheck\" \"pnpm --filter @annex/mcp typecheck\"", + "migrate": "pnpm --filter api migrate", "migrations:local": "node scripts/migrate.mjs local", "migrations:remote": "node scripts/migrate.mjs remote", - "test": "concurrently \"pnpm --filter api test\" \"pnpm --filter auth test\" \"pnpm --filter frontend test\" \"pnpm --filter @annex/mcp test\" && pnpm test:e2e", + "test": "concurrently \"pnpm --filter api test\" \"pnpm --filter frontend test\" \"pnpm --filter @annex/admin test\" \"pnpm --filter @annex/admin-frontend test\" \"pnpm --filter @annex/mcp test\" && pnpm test:e2e", "test:e2e": "pnpm --filter cubedocs-e2e test", "test:e2e:ui": "pnpm --filter cubedocs-e2e test:ui" }, diff --git a/packages/admin/.dev.vars.example b/packages/admin/.dev.vars.example new file mode 100644 index 00000000..aeb504ca --- /dev/null +++ b/packages/admin/.dev.vars.example @@ -0,0 +1,23 @@ +# Copy to packages/admin/.dev.vars (gitignored). + +# Signs the admin panel's own session JWTs. Any random string locally. +JWT_SECRET=change-me + +# The admin SPA's origin (its Vite dev server proxies /api to :8789). +APP_ORIGIN=http://localhost:5174 + +# The admin panel is its own OIDC client of the identity service. With a local +# identity worker on :8790 (see packages/api/.dev.vars.example), register a +# client with redirect URI http://localhost:5174/api/auth/callback and +# post-logout URI http://localhost:5174 (no trailing slash), scopes `openid profile email roles`, +# first-party. Sign-in requires an account with the admin role. +OIDC_ISSUER=http://localhost:8790 +OIDC_CLIENT_ID=annex-admin-local +OIDC_CLIENT_SECRET= + +# Skip the identity service: POST /api/dev/quick-login mints an admin dev +# session (the e2e admin suite uses it). Localhost APP_ORIGIN only. +DEV_QUICK_LOGIN=true + +# Admin-driven Stripe actions (test mode). +# STRIPE_SECRET_KEY=sk_test_... diff --git a/packages/admin/cloudflare.config.ts b/packages/admin/cloudflare.config.ts index 07c024d3..28d9b14d 100644 --- a/packages/admin/cloudflare.config.ts +++ b/packages/admin/cloudflare.config.ts @@ -44,11 +44,12 @@ export default defineConfig({ // Sign in with auth.cubityfir.st: the admin panel is its own first-party // OIDC client (scopes `openid profile email roles`, sign-in requires the // admin role), registered with redirect URI APP_ORIGIN/api/auth/callback - // and post-logout redirect URI APP_ORIGIN/. OIDC_CLIENT_ID must be the id + // and post-logout redirect URI APP_ORIGIN (no trailing slash; matched byte + // for byte). OIDC_CLIENT_ID must be the id // it was registered with at auth.cubityfir.st/admin/clients; // OIDC_CLIENT_SECRET is a secret. OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), - OIDC_CLIENT_ID: bindings.text("annex-admin"), + OIDC_CLIENT_ID: bindings.text("oidc_07c81f4a5aa63dd2bd0b15cc"), APP_ORIGIN: bindings.text("https://admin.cubityfir.st"), // Identity service RPC (live standing + admin role, user lookups). IDENTITY: bindings.worker({ diff --git a/packages/admin/frontend/src/App.test.tsx b/packages/admin/frontend/src/App.test.tsx index e4adbd82..ec203323 100644 --- a/packages/admin/frontend/src/App.test.tsx +++ b/packages/admin/frontend/src/App.test.tsx @@ -38,7 +38,7 @@ vi.mock("@/lib/api", () => { }); import { App } from "./App"; -import { TransientVerifyError, verifyAdminSession } from "@/lib/api"; +import { TransientVerifyError, exchangeAdminCode, verifyAdminSession } from "@/lib/api"; import { getToken, setToken } from "@/lib/auth"; const SESSION = { @@ -101,4 +101,15 @@ describe("App session gating", () => { expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(getToken()).toBeNull(); }); + + it("lands a completed sign-in on its deep link, through the verification screen", async () => { + vi.mocked(exchangeAdminCode).mockResolvedValue({ token: "fresh" }); + // A real verify round-trips the network, so App's verification screen + // replaces (unmounts) the completion page meanwhile. + vi.mocked(verifyAdminSession).mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(SESSION), 30))); + window.history.replaceState(null, "", "/auth/complete#status=ok&return_to=%2Faudit"); + renderApp("/auth/complete"); + expect(await screen.findByRole("heading", { name: "Audit Log" })).toBeInTheDocument(); + expect(getToken()).toBe("fresh"); + }); }); diff --git a/packages/admin/frontend/src/App.tsx b/packages/admin/frontend/src/App.tsx index 08353907..d5b78b6f 100644 --- a/packages/admin/frontend/src/App.tsx +++ b/packages/admin/frontend/src/App.tsx @@ -6,6 +6,7 @@ import { ADMIN_AUTH_INVALIDATED_EVENT, clearToken, getToken } from "@/lib/auth"; import { type AdminAuthSession, TransientVerifyError, logoutAdminSession, verifyAdminSession } from "@/lib/api"; import { AuthCallbackPage } from "./pages/AuthCallbackPage"; import { LoginPage } from "./pages/LoginPage"; +import { postSignInPath } from "@/lib/signIn"; import { ProjectsPage } from "./pages/ProjectsPage"; import { UsersPage } from "./pages/UsersPage"; import { AuditPage } from "./pages/AuditPage"; @@ -253,7 +254,10 @@ export function App() { ); } - if (location.pathname === "/login" || location.pathname === "/auth/complete") { + if (location.pathname === "/auth/complete") { + return ; + } + if (location.pathname === "/login") { return ; } diff --git a/packages/admin/frontend/src/lib/api.ts b/packages/admin/frontend/src/lib/api.ts index 5e6be99c..a94761f3 100644 --- a/packages/admin/frontend/src/lib/api.ts +++ b/packages/admin/frontend/src/lib/api.ts @@ -659,29 +659,27 @@ export class AdminSignInError extends Error { } } -async function exchangeAdminCodeUncached(code: string): Promise { - const res = await fetch("/api/auth/exchange", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ code }), - }); +async function exchangeAdminCodeUncached(attempt: string): Promise { + // Same-origin POST: the browser sends this attempt's single-use handoff + // cookie the callback set (HttpOnly - the code never appears in a URL). + const res = await fetch(`/api/auth/exchange?attempt=${encodeURIComponent(attempt)}`, { method: "POST" }); const json = (await res.json()) as { ok: boolean; data?: AdminCodeExchange; error?: string }; if (!json.ok || !json.data) throw new AdminSignInError(json.error ?? "unknown"); return json.data; } -// The sign-in code from /api/auth/callback is single-use and redeemed -// atomically server-side, so two concurrent exchanges of the same code (React -// StrictMode's dev double-mount) would race: the loser gets "invalid_code" and -// paints an error over a successful sign-in. Cache the in-flight/settled -// promise per code so every caller observes the SAME exchange outcome. +// The handoff cookie is single-use and redeemed atomically server-side, so two +// concurrent exchanges (React StrictMode's dev double-mount) would race: the +// loser gets "invalid_code" and paints an error over a successful sign-in. +// Share one in-flight/settled promise per sign-in attempt (the id the +// callback put in the fragment) so every caller observes the SAME outcome. const exchangePromises = new Map>(); -export function exchangeAdminCode(code: string): Promise { - let promise = exchangePromises.get(code); +export function exchangeAdminCode(attempt: string): Promise { + let promise = exchangePromises.get(attempt); if (!promise) { - promise = exchangeAdminCodeUncached(code); - exchangePromises.set(code, promise); + promise = exchangeAdminCodeUncached(attempt); + exchangePromises.set(attempt, promise); } return promise; } diff --git a/packages/admin/frontend/src/lib/signIn.ts b/packages/admin/frontend/src/lib/signIn.ts index 5d87ff6a..dbc2ac71 100644 --- a/packages/admin/frontend/src/lib/signIn.ts +++ b/packages/admin/frontend/src/lib/signIn.ts @@ -1,6 +1,7 @@ // The admin panel signs in through auth.cubityfir.st as its own OIDC client: // /api/auth/login (admin worker) -> identity service -> /api/auth/callback -> -// /auth/complete#code=... (AuthCallbackPage) -> POST /api/auth/exchange. +// /auth/complete#status=ok (AuthCallbackPage) -> POST /api/auth/exchange +// (redeems the HttpOnly handoff cookie the callback set). export function normalizeAdminNextPath(nextPath: string | null | undefined): string { if (!nextPath || !nextPath.startsWith("/")) { @@ -24,6 +25,27 @@ export function adminSignInUrl(nextPath: string, opts: { prompt?: "login" } = {} return `/api/auth/login${qs ? `?${qs}` : ""}`; } +// Where to land after a completed sign-in. The completion page records it; +// App reads it once the session is verified (the page itself is unmounted by +// App's verification screen, so it can't navigate there itself). +const POST_SIGN_IN_KEY = "admin_post_sign_in"; + +export function rememberPostSignIn(nextPath: string): void { + try { + window.sessionStorage.setItem(POST_SIGN_IN_KEY, normalizeAdminNextPath(nextPath)); + } catch { + /* storage unavailable - fall back to "/" */ + } +} + +export function postSignInPath(): string { + try { + return normalizeAdminNextPath(window.sessionStorage.getItem(POST_SIGN_IN_KEY)); + } catch { + return "/"; + } +} + export function signInErrorMessage(code: string | null): string { switch (code) { case "not_admin": diff --git a/packages/admin/frontend/src/pages/AuthCallbackPage.test.tsx b/packages/admin/frontend/src/pages/AuthCallbackPage.test.tsx index 6ecafd7a..a8455668 100644 --- a/packages/admin/frontend/src/pages/AuthCallbackPage.test.tsx +++ b/packages/admin/frontend/src/pages/AuthCallbackPage.test.tsx @@ -39,11 +39,12 @@ function renderComplete(fragment: string, onAuthenticated = vi.fn()) { describe("AuthCallbackPage (/auth/complete)", () => { it("exchanges the code ONCE despite StrictMode's dev double-mount (AF-C3), stores the token, navigates", async () => { fetchMock.mockImplementation(async () => jsonResponse({ ok: true, data: { token: "minted-token" } })); - const onAuthenticated = renderComplete("code=cb-success"); + const onAuthenticated = renderComplete("status=ok&attempt=a1"); await waitFor(() => expect(screen.getByText("HOME")).toBeInTheDocument()); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(fetchMock).toHaveBeenCalledWith("/api/auth/exchange", expect.objectContaining({ method: "POST", body: JSON.stringify({ code: "cb-success" }) })); + // No code in the request or the URL: the HttpOnly handoff cookie carries it. + expect(fetchMock).toHaveBeenCalledWith("/api/auth/exchange?attempt=a1", { method: "POST" }); expect(getToken()).toBe("minted-token"); expect(onAuthenticated).toHaveBeenCalled(); expect(screen.queryByText(/didn't complete/)).not.toBeInTheDocument(); @@ -51,15 +52,14 @@ describe("AuthCallbackPage (/auth/complete)", () => { it("goes to the return path carried in the fragment, but never off-site", async () => { fetchMock.mockImplementation(async () => jsonResponse({ ok: true, data: { token: "t" } })); - renderComplete("code=cb-next&return_to=%2Faudit"); + renderComplete("status=ok&attempt=a2&return_to=%2Faudit"); await waitFor(() => expect(screen.getByText("AUDIT")).toBeInTheDocument()); }); - it("strips the one-time code from the address bar", async () => { + it("cleans the fragment from the address bar", async () => { fetchMock.mockImplementation(async () => jsonResponse({ ok: true, data: { token: "t" } })); - renderComplete("code=cb-strip"); + renderComplete("status=ok&attempt=a3&return_to=%2Fsecret"); await waitFor(() => expect(window.location.hash).toBe("")); - expect(window.location.href).not.toContain("cb-strip"); }); it("explains a missing admin role and offers a fresh sign-in", async () => { @@ -71,7 +71,7 @@ describe("AuthCallbackPage (/auth/complete)", () => { it("explains a consumed/expired code", async () => { fetchMock.mockImplementation(async () => jsonResponse({ ok: false, error: "invalid_code" }, 400)); - renderComplete("code=cb-consumed"); + renderComplete("status=ok&attempt=a4"); expect(await screen.findByText(/took too long or was already used/)).toBeInTheDocument(); expect(getToken()).toBeNull(); }); diff --git a/packages/admin/frontend/src/pages/AuthCallbackPage.tsx b/packages/admin/frontend/src/pages/AuthCallbackPage.tsx index b130ce8b..1d10e548 100644 --- a/packages/admin/frontend/src/pages/AuthCallbackPage.tsx +++ b/packages/admin/frontend/src/pages/AuthCallbackPage.tsx @@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { AdminSignInError, exchangeAdminCode } from "@/lib/api"; import { setToken } from "@/lib/auth"; -import { adminSignInUrl, normalizeAdminNextPath, signInErrorMessage } from "@/lib/signIn"; +import { adminSignInUrl, normalizeAdminNextPath, rememberPostSignIn, signInErrorMessage } from "@/lib/signIn"; interface AuthCallbackPageProps { onAuthenticated: () => Promise | void; @@ -13,8 +13,10 @@ interface AuthCallbackPageProps { // /auth/complete - where the admin worker's /api/auth/callback sends the // browser. The outcome is in the URL fragment (never sent to servers): -// #code=&return_to=/path -> redeem for the admin session JWT -// #error= -> explain and offer a retry +// #status=ok&attempt=&return_to=/path +// -> redeem this attempt's single-use HttpOnly +// handoff cookie for the admin session JWT +// #error= -> explain and offer a retry // Read once at module level of the effect, before the address bar is cleaned. function readFragment(): URLSearchParams { return new URLSearchParams(window.location.hash.slice(1)); @@ -24,7 +26,10 @@ export function AuthCallbackPage({ onAuthenticated }: AuthCallbackPageProps) { const navigate = useNavigate(); const [error, setError] = useState(null); const [nextPath] = useState(() => normalizeAdminNextPath(readFragment().get("return_to"))); - const [code] = useState(() => readFragment().get("code")); + const [ok] = useState(() => readFragment().get("status") === "ok"); + // The sign-in attempt to redeem; also keys one exchange per attempt + // (StrictMode re-runs the effect; see exchangeAdminCode). + const [attempt] = useState(() => readFragment().get("attempt") ?? ""); const [errorCode] = useState(() => readFragment().get("error")); useEffect(() => { @@ -32,7 +37,7 @@ export function AuthCallbackPage({ onAuthenticated }: AuthCallbackPageProps) { // before (and regardless of) the exchange. window.history.replaceState(null, "", window.location.pathname); - if (!code) { + if (!ok) { setError(signInErrorMessage(errorCode)); return; } @@ -40,8 +45,11 @@ export function AuthCallbackPage({ onAuthenticated }: AuthCallbackPageProps) { let cancelled = false; (async () => { try { - const { token } = await exchangeAdminCode(code); + const { token } = await exchangeAdminCode(attempt); setToken(token); + // App shows its verification screen (unmounting this page) and then + // redirects /auth/complete to this destination. + rememberPostSignIn(nextPath); await onAuthenticated(); if (!cancelled) navigate(nextPath, { replace: true }); } catch (err) { @@ -52,7 +60,7 @@ export function AuthCallbackPage({ onAuthenticated }: AuthCallbackPageProps) { return () => { cancelled = true; }; - }, [code, errorCode, navigate, nextPath, onAuthenticated]); + }, [ok, attempt, errorCode, navigate, nextPath, onAuthenticated]); return (
diff --git a/packages/admin/src/index.test.ts b/packages/admin/src/index.test.ts index 969d5e1c..56a3674e 100644 --- a/packages/admin/src/index.test.ts +++ b/packages/admin/src/index.test.ts @@ -223,6 +223,29 @@ describe("logout (AF-S3)", () => { }); }); +describe("dev quick-login", () => { + const post = (env: ReturnType) => request(env, "/api/dev/quick-login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: "e2e-admin@example.com" }), + }); + + it("404s unless DEV_QUICK_LOGIN is on AND the panel runs on localhost", async () => { + const { db } = createSqliteD1(); + expect((await post(makeEnv({ DB: db, APP_ORIGIN: "http://localhost:5174" }))).status).toBe(404); + expect((await post(makeEnv({ DB: db, DEV_QUICK_LOGIN: "true", APP_ORIGIN: "https://admin.cubityfir.st" }))).status).toBe(404); + }); + + it("mints an admin session for an admin dev user locally", async () => { + const { db, sqlite } = createSqliteD1(); + const res = await post(makeEnv({ DB: db, DEV_QUICK_LOGIN: "true", APP_ORIGIN: "http://localhost:5174" })); + expect(res.status).toBe(200); + const { data } = (await res.json()) as { data: { userId: string } }; + expect(sqlite.prepare("SELECT is_admin FROM users WHERE id = ?").get(data.userId)).toEqual({ is_admin: 1 }); + expect(sqlite.prepare("SELECT kind FROM sessions WHERE user_id = ?").get(data.userId)).toEqual({ kind: "admin" }); + }); +}); + describe("invalid cursors 400 at the HTTP layer", () => { it.each([ "/api/users/search?q=&cursor=garbage", diff --git a/packages/admin/src/index.ts b/packages/admin/src/index.ts index a1b876e3..3204e585 100644 --- a/packages/admin/src/index.ts +++ b/packages/admin/src/index.ts @@ -1,7 +1,7 @@ import { Hono } from "hono"; import type { MiddlewareHandler } from "hono"; import { adminAuthFlow, requireAdminSession, verifySession, type AdminSession } from "./auth"; -import { handleCallback, handleExchange, handleLogin, handleLogout } from "../../api/src/routes/auth"; +import { handleCallback, handleDevQuickLogin, handleExchange, handleLogin, handleLogout } from "../../api/src/routes/auth"; import type { IdentityService } from "../../api/src/account/identity"; import { usersRouter } from "./routes/users"; import { projectsRouter } from "./routes/projects"; @@ -32,6 +32,9 @@ export interface Env { OIDC_REDIRECT_URI?: string; OIDC_POST_LOGOUT_REDIRECT_URI?: string; APP_ORIGIN?: string; + // Local dev only: POST /api/dev/quick-login mints an admin dev session + // (needs "true" AND a localhost APP_ORIGIN; the e2e admin suite uses it). + DEV_QUICK_LOGIN?: string; // IP-keyed rate limiters (Cloudflare ratelimit bindings - see cloudflare.config.ts). // RATE_LIMITER_ADMIN gates every authenticated admin API route and the // sign-in endpoints; RATE_LIMITER_AVATAR gates the public avatar route on @@ -94,6 +97,9 @@ app.post("/api/auth/exchange", async (c) => (await limited(c)) ?? handleExchange // account was disabled) must still be able to kill the session. app.post("/api/auth/logout", async (c) => (await limited(c)) ?? handleLogout(adminAuthFlow(c.env), c.env, c.req.raw)); +// Local dev only (404 unless DEV_QUICK_LOGIN=true and APP_ORIGIN is localhost). +app.post("/api/dev/quick-login", async (c) => (await limited(c)) ?? handleDevQuickLogin(c.req.raw, c.env, "admin")); + app.get("/api/verify", async (c) => { // Same IP limiter as the authenticated routes: this is otherwise the one // unauthenticated endpoint where anyone holding an expired-but-signed JWT diff --git a/packages/admin/src/lib/userDeletion.sqlite.test.ts b/packages/admin/src/lib/userDeletion.sqlite.test.ts index af15287c..6b92cd55 100644 --- a/packages/admin/src/lib/userDeletion.sqlite.test.ts +++ b/packages/admin/src/lib/userDeletion.sqlite.test.ts @@ -387,6 +387,21 @@ describe("delayed deletion (real SQLite)", () => { expect((await t.cancelDeletion("u-1")).status).toBe(200); }); + it("a Stripe customer linked after the preflight read blocks the point of no return (retried, nothing deleted)", async () => { + const t = setup(); + t.addUser("u-1"); + at(T0); + await t.scheduleDeletion("u-1"); + // A checkout webhook links a customer right after the run read billing. + interleave(t, "LEFT JOIN user_billing b ON b.user_id = u.id", () => { + t.sqlite.prepare("INSERT INTO user_billing (user_id, stripe_customer_id) VALUES ('u-1', 'cus_late')").run(); + }); + expect(await t.runAt(T0 + 7 * DAY + 60)).toEqual({ deleted: 0, failed: 1 }); + expect(t.schedule("u-1")!.started_at).toBeNull(); + expect(String(t.schedule("u-1")!.last_error)).toContain("billing changed"); + expect(t.count("SELECT COUNT(*) AS n FROM user_billing WHERE stripe_customer_id = 'cus_late'")).toBe(1); + }); + it("two admins scheduling the same account at once: the loser gets a clean 409", async () => { const t = setup(); t.addUser("u-1"); diff --git a/packages/admin/src/lib/userDeletion.test.ts b/packages/admin/src/lib/userDeletion.test.ts index cb960991..b370e91a 100644 --- a/packages/admin/src/lib/userDeletion.test.ts +++ b/packages/admin/src/lib/userDeletion.test.ts @@ -100,6 +100,22 @@ describe("executeUserDeletion", () => { expect(completed(env)).toBe(false); }); + it("refuses an account the identity service reports as admin, even when the mirror says otherwise", async () => { + const env = { ...makeEnv(), IDENTITY: { getUser: vi.fn(async () => ({ isAdmin: true })) } }; + env.DB.firstQueue.push(plainUser()); + const res = await run(env as never, "u-1"); + expect(res).toEqual({ ok: false, error: "Admin accounts can't be deleted from the admin panel" }); + expect(env.DB.calls.some(c => c.sql.includes("started_at"))).toBe(false); + }); + + it("leaves the schedule for a retry when the identity service can't be reached", async () => { + const env = { ...makeEnv(), IDENTITY: { getUser: vi.fn(async () => { throw new Error("down"); }) } }; + env.DB.firstQueue.push(plainUser()); + const res = await run(env as never, "u-1"); + expect(res.ok).toBe(false); + expect(env.DB.calls.some(c => c.sql.includes("started_at"))).toBe(false); + }); + it("refuses (and touches nothing, not even started_at) when an owned site wasn't confirmed", async () => { const env = makeEnv(); env.DB.firstQueue.push(plainUser("cus_1")); @@ -133,7 +149,8 @@ describe("executeUserDeletion", () => { const res = await run(env, "u-1"); expect(res.ok).toBe(false); const started = env.DB.calls.find(c => c.sql.includes("SET started_at")); - expect(started?.binds.slice(1)).toEqual(["u-1", "sched-1"]); + // Tied to this schedule AND to the Stripe customer the preflight checked. + expect(started?.binds.slice(1)).toEqual(["u-1", "sched-1", "u-1", "cus_1"]); // Only the read-only preflight ran - the customer was never deleted. expect(fetchMock).toHaveBeenCalledTimes(1); expect((fetchMock.mock.calls[0][1] as RequestInit).method).toBeUndefined(); diff --git a/packages/admin/src/lib/userDeletion.ts b/packages/admin/src/lib/userDeletion.ts index 1e905db9..1e73257f 100644 --- a/packages/admin/src/lib/userDeletion.ts +++ b/packages/admin/src/lib/userDeletion.ts @@ -200,6 +200,19 @@ export async function executeUserDeletion( // Re-checked here, not just at scheduling: the account may have been made // an admin during the grace window. if (user.is_admin) return { ok: false, error: "Admin accounts can't be deleted from the admin panel" }; + // The mirror's admin flag can be stale: the schedule blocks the person, so + // no sign-in or session check refreshes it during the grace window. Ask the + // identity service before anything irreversible, and retry later if it + // can't be reached. + if (env.IDENTITY) { + let live; + try { + live = await env.IDENTITY.getUser(userId); + } catch { + return { ok: false, error: "Couldn't verify the account with auth.cubityfir.st; it will be retried" }; + } + if (live?.isAdmin) return { ok: false, error: "Admin accounts can't be deleted from the admin panel" }; + } const before = await checkExecutionOwnership(env, userId, user.email, confirm); if (before.error) return { ok: false, error: before.error }; @@ -232,11 +245,17 @@ export async function executeUserDeletion( // Point of no return: from here the deletion can only be finished, not // cancelled. Tied to this schedule id, so it no-ops if the schedule was // replaced (the claim normally prevents that already). + // Also tied to the Stripe customer the preflight saw: a webhook linking a + // new customer before this point would otherwise be deleted from billing + // without its customer being cancelled. (After it, the webhook's own + // started_at guard routes late events to customer deletion.) const started = await env.DB.prepare( - "UPDATE user_deletions SET started_at = COALESCE(started_at, ?) WHERE user_id = ? AND id = ?", - ).bind(Math.floor(Date.now() / 1000), userId, scheduleId).run(); + `UPDATE user_deletions SET started_at = COALESCE(started_at, ?) + WHERE user_id = ? AND id = ? + AND (SELECT stripe_customer_id FROM user_billing WHERE user_id = ?) IS ?`, + ).bind(Math.floor(Date.now() / 1000), userId, scheduleId, userId, user.stripe_customer_id).run(); if ((started.meta?.changes ?? 0) !== 1) { - return { ok: false, error: "The schedule was cancelled or replaced; nothing was deleted" }; + return { ok: false, error: "The schedule was cancelled or replaced, or billing changed during the run; nothing was deleted (retried later)" }; } // Stripe first, and fatal on failure: a deleted account with a live diff --git a/packages/admin/src/routes/audit.test.ts b/packages/admin/src/routes/audit.test.ts index 814db4f3..3bdcad2d 100644 --- a/packages/admin/src/routes/audit.test.ts +++ b/packages/admin/src/routes/audit.test.ts @@ -1,10 +1,7 @@ import { describe, it, expect } from "vitest"; -import { fileURLToPath } from "node:url"; import { buildAuditListQuery, AUDIT_ACTIONS_SQL } from "./audit"; import { createSqliteD1 } from "../../../api/src/test/sqliteD1"; -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../../auth/migrations", import.meta.url)); - const CURSOR = { ts: "2026-05-17 12:34:56", id: "a1b2-c3d4" }; const NO_FILTERS = { actions: [] as string[], q: null }; @@ -80,7 +77,7 @@ describe("buildAuditListQuery", () => { // the distinct actions, sorted. describe("audit queries against the real schema", () => { function seed() { - const { sqlite } = createSqliteD1(AUTH_MIGRATIONS); + const { sqlite } = createSqliteD1(); const ins = sqlite.prepare( "INSERT INTO admin_audit_log (id, actor_user_id, actor_email, action, target_type, created_at) VALUES (?, 'a', 'a@x.com', ?, 'user', ?)", ); @@ -129,7 +126,7 @@ describe("audit queries against the real schema", () => { }); it("lists no actions for an empty log", () => { - const { sqlite } = createSqliteD1(AUTH_MIGRATIONS); + const { sqlite } = createSqliteD1(); expect(sqlite.prepare(AUDIT_ACTIONS_SQL).all()).toEqual([]); }); }); diff --git a/packages/admin/src/routes/users.test.ts b/packages/admin/src/routes/users.test.ts index f813068d..7fa39411 100644 --- a/packages/admin/src/routes/users.test.ts +++ b/packages/admin/src/routes/users.test.ts @@ -470,6 +470,13 @@ describe("POST /:id/deletion - schedule (never deletes)", () => { [...env.DB.calls, ...env.DB.batches.flat()] .some(c => /DELETE FROM (users|projects|organizations|project_members)/.test(c.sql)); + it("refuses (503, nothing written) when the live admin role can't be checked", async () => { + const env = { ...makeEnv(), IDENTITY: { getUser: vi.fn(async () => { throw new Error("identity down"); }) } }; + const res = await schedule(env as unknown as ReturnType, "u-1"); + expect(res.status).toBe(503); + expect(scheduled(env as unknown as ReturnType)).toBe(false); + }); + it("refuses the caller's own account", async () => { const env = makeEnv(); expect((await schedule(env, "admin-1")).status).toBe(400); diff --git a/packages/admin/src/routes/users.ts b/packages/admin/src/routes/users.ts index 282e6987..f739aa2f 100644 --- a/packages/admin/src/routes/users.ts +++ b/packages/admin/src/routes/users.ts @@ -354,7 +354,7 @@ async function loadUserDetails(env: Env, id: string): Promise { if (c.env.IDENTITY) { try { const user = await c.env.IDENTITY.getUser(id); - if (user) refreshed = await refreshMirror(c.env.DB, user, Date.now()); + if (user) refreshed = await refreshMirror(c.env, user, Date.now()); } catch (err) { console.error("[admin] resync-name: identity getUser failed; using the mirror", String(err)); } @@ -753,6 +753,22 @@ usersRouter.post("/:id/deletion", async (c) => { return c.json({ ok: false, error: "You can't delete your own account from the admin panel" }, 400); } + // Scheduling blocks the person from Annex at once, so refresh the mirror's + // admin flag from the identity service first: a stale "not admin" would + // lock out a newly promoted admin. Refuse rather than guess when it can't + // be checked. + if (c.env.IDENTITY) { + try { + const live = await c.env.IDENTITY.getUser(id); + if (live?.isAdmin) { + return c.json({ ok: false, error: "Admin accounts can't be deleted from the admin panel" }, 409); + } + if (live) await refreshMirror(c.env, live, Date.now()); + } catch (err) { + console.error("[admin] schedule deletion: identity check failed", String(err)); + return c.json({ ok: false, error: "Couldn't check this account on auth.cubityfir.st - try again shortly" }, 503); + } + } const user = await c.env.DB.prepare( `SELECT u.id, u.email, u.is_admin, d.user_id IS NOT NULL AS scheduled FROM users u LEFT JOIN user_deletions d ON d.user_id = u.id diff --git a/packages/admin/wrangler.config.ts b/packages/admin/wrangler.config.ts index 1f639c01..8b93ed29 100644 --- a/packages/admin/wrangler.config.ts +++ b/packages/admin/wrangler.config.ts @@ -6,7 +6,7 @@ import { defineWranglerConfig } from "wrangler/experimental-config"; // There is no wrangler.toml. Local dev (`pnpm dev`) runs // `wrangler dev --experimental-new-config --persist-to ../../.wrangler/state`, // which reads this file + cloudflare.config.ts directly: every worker must share -// one local state dir (the api worker reads the auth DB via AUTH_DB), and +// one local state dir (the api and admin workers share cubedocs-main), and // `cf dev` cannot set a persist directory yet. export default defineWranglerConfig({ // Built by `pnpm build` (the admin SPA in ./frontend). diff --git a/packages/api/.dev.vars.example b/packages/api/.dev.vars.example new file mode 100644 index 00000000..08fd5169 --- /dev/null +++ b/packages/api/.dev.vars.example @@ -0,0 +1,29 @@ +# Copy to packages/api/.dev.vars (gitignored). Values here override the vars in +# cloudflare.config.ts for `wrangler dev`. + +# Signs Annex's own session JWTs. Any random string locally. +JWT_SECRET=change-me + +# The SPA's origin (Vite dev server). Also gates the dev quick login. +APP_ORIGIN=http://localhost:5173 + +# Sign in with a local identity worker (G:\scripts\auth). Annex's api owns +# :8787, so run it on another port: `npx wrangler dev --port 8790`, with +# ISSUER=http://localhost:8790 in its own .dev.vars. Register a client there +# with redirect URI http://localhost:5173/api/auth/callback and post-logout +# URI http://localhost:5173 (no trailing slash), scopes `openid profile email roles`, first-party. +# The IDENTITY/IDENTITY_OIDC bindings reach it through wrangler's dev registry; +# without it running, server-side OIDC falls back to OIDC_ISSUER directly and +# account standing falls back to the users mirror. +OIDC_ISSUER=http://localhost:8790 +OIDC_CLIENT_ID=annex-docs-local +OIDC_CLIENT_SECRET= + +# Skip the identity service entirely: "Dev quick login" buttons on /login and +# POST /api/dev/quick-login (the e2e helper). Localhost APP_ORIGIN only. +DEV_QUICK_LOGIN=true + +# Annex Ink (test mode). See memories/Ink-Stripe.md. +# STRIPE_SECRET_KEY=sk_test_... +# STRIPE_WEBHOOK_SECRET=whsec_... (printed by `pnpm dev:stripe`) +# STRIPE_INK_PRICE_ID=price_... diff --git a/packages/api/cloudflare.config.ts b/packages/api/cloudflare.config.ts index df3937be..db48bb5f 100644 --- a/packages/api/cloudflare.config.ts +++ b/packages/api/cloudflare.config.ts @@ -23,7 +23,7 @@ export default defineConfig({ }), // Hourly deletion sync: accounts deleted on auth.cubityfir.st have their // Annex data removed (owned sites/orgs are kept for an operator). The - // schedule string must match DELETION_SYNC_CRON in src/index.ts. + // schedule string must match DELETION_SYNC_CRON in src/lib/identityDeletions.ts. triggers.scheduled({ schedule: "23 * * * *", }), @@ -59,13 +59,15 @@ export default defineConfig({ // Sign in with auth.cubityfir.st (src/routes/auth.ts). Annex is a // first-party OIDC client with scopes `openid profile email roles`, // redirect URI APP_ORIGIN/api/auth/callback and post-logout redirect - // URI APP_ORIGIN/ (override with OIDC_REDIRECT_URI / + // URI APP_ORIGIN, no trailing slash - the provider matches byte for byte + // (override with OIDC_REDIRECT_URI / // OIDC_POST_LOGOUT_REDIRECT_URI). OIDC_CLIENT_ID must be the id the // client was registered with at auth.cubityfir.st/admin/clients; // OIDC_CLIENT_SECRET is a secret. Local dev overrides all of these in // .dev.vars (see .dev.vars.example). OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), - OIDC_CLIENT_ID: bindings.text("annex-docs"), + // Registered at auth.cubityfir.st/admin/clients (not a secret). + OIDC_CLIENT_ID: bindings.text("oidc_7369d6d5736d2bea35f1ab47"), APP_ORIGIN: bindings.text("https://docs.cubityfir.st"), // Stripe price id for the Annex Ink supporter tier ($5/mo recurring). // Not a secret - safe to commit. (Billing moved here from annex-auth.) @@ -142,7 +144,8 @@ export default defineConfig({ // Secrets (set via `npx wrangler secret put --name annex-api`; // existing secrets are kept across `cf deploy`): // JWT_SECRET (signs Annex's own session JWTs; Annex-only) - // OIDC_CLIENT_SECRET (the annex-docs client's secret from auth.cubityfir.st) + // OIDC_CLIENT_SECRET (the docs client's secret from auth.cubityfir.st; + // prefixed sk_ - never commit or log it) // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - moved from annex-auth) // STRIPE_WEBHOOK_SECRET (whsec_... for the docs.cubityfir.st/stripe/webhook // endpoint; the frontend worker forwards it here, so diff --git a/packages/api/src/account/identity.test.ts b/packages/api/src/account/identity.test.ts new file mode 100644 index 00000000..11f60c2d --- /dev/null +++ b/packages/api/src/account/identity.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { createSqliteD1, type SqliteD1 } from "../test/sqliteD1"; + +const { syncStripeCustomerEmail } = vi.hoisted(() => ({ syncStripeCustomerEmail: vi.fn(async () => undefined) })); +vi.mock("./stripe-client", () => ({ syncStripeCustomerEmail })); + +import { accountStanding, clearIdentityCache, findUserByEmail, refreshMirror, type IdentityService, type IdentityUser, type MirrorUser } from "./identity"; + +let db: SqliteD1; +const user = (over: Partial = {}): IdentityUser => ({ + id: "u1", email: "new@example.com", name: "U", emailVerified: true, isAdmin: false, + status: "active", suspendedUntil: null, createdAt: "2025-01-01", ...over, +}); + +beforeEach(() => { + db = createSqliteD1(); + clearIdentityCache(); + syncStripeCustomerEmail.mockClear(); + db.sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES ('u1', 'old@example.com', 'U', '2025-01-01', 0, 0)").run(); +}); + +describe("findUserByEmail", () => { + const down = { findUserByEmail: vi.fn(async () => { throw new Error("identity down"); }) } as unknown as IdentityService; + + it("fails rather than guessing from the (non-unique, possibly stale) mirror when the identity service is down", async () => { + await expect(findUserByEmail({ DB: db.db, IDENTITY: down, APP_ORIGIN: "https://docs.cubityfir.st" }, "old@example.com")).rejects.toThrow("identity down"); + }); + + it("syncs the Stripe email when the invite lookup is the first to see a new address", async () => { + const env = { DB: db.db, IDENTITY: { findUserByEmail: vi.fn(async () => user()) } as unknown as IdentityService, STRIPE_SECRET_KEY: "sk" }; + await findUserByEmail(env, "new@example.com"); + expect(syncStripeCustomerEmail).toHaveBeenCalledWith(env, "u1", "new@example.com"); + // A later refresh (sign-in, standing check) sees nothing new and doesn't repeat it. + syncStripeCustomerEmail.mockClear(); + await refreshMirror(env, user(), 9, { login: true }); + expect(syncStripeCustomerEmail).not.toHaveBeenCalled(); + }); + + it("falls back to the mirror in local dev", async () => { + expect(await findUserByEmail({ DB: db.db, IDENTITY: down, APP_ORIGIN: "http://localhost:5173" }, "OLD@example.com")) + .toEqual({ id: "u1", email: "old@example.com", name: "U" }); + }); +}); + +describe("accountStanding", () => { + it("keeps the Stripe customer's email in step when the standing check sees a new identity email", async () => { + const mirror = db.sqlite.prepare("SELECT * FROM users WHERE id = 'u1'").get() as unknown as MirrorUser; + const env = { DB: db.db, IDENTITY: { getUser: vi.fn(async () => user()) } as unknown as IdentityService, STRIPE_SECRET_KEY: "sk" }; + expect((await accountStanding(env, mirror)).ok).toBe(true); + expect(db.sqlite.prepare("SELECT email FROM users WHERE id = 'u1'").get()).toEqual({ email: "new@example.com" }); + expect(syncStripeCustomerEmail).toHaveBeenCalledWith(env, "u1", "new@example.com"); + }); +}); + +describe("refreshMirror", () => { + it("can't revive an account recorded as deleted, nor rewrite its scrubbed member rows", async () => { + db.sqlite.prepare("INSERT INTO projects (id, name, owner_id, created_at) VALUES ('p1', 'P', 'u1', 't')").run(); + db.sqlite.prepare("INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at) VALUES ('m1', 'p1', 'u1', '', 'Deleted account', 'owner', 'u1', 't')").run(); + db.sqlite.prepare("INSERT INTO identity_deletions (user_id, deleted_at, deleted_by) VALUES ('u1', 1, 'self')").run(); + await refreshMirror({ DB: db.db }, user({ name: "Late" }), 5); + expect(db.sqlite.prepare("SELECT name FROM users WHERE id = 'u1'").get()).toEqual({ name: "U" }); + expect(db.sqlite.prepare("SELECT name, email FROM project_members WHERE id = 'm1'").get()).toEqual({ name: "Deleted account", email: "" }); + + db.sqlite.prepare("DELETE FROM identity_deletions").run(); + db.sqlite.prepare("UPDATE users SET status = 'deleted' WHERE id = 'u1'").run(); + await refreshMirror({ DB: db.db }, user(), 6); + expect(db.sqlite.prepare("SELECT status FROM users WHERE id = 'u1'").get()).toEqual({ status: "deleted" }); + }); + + it("doesn't re-insert a mirror row the deletion sync already removed", async () => { + db.sqlite.prepare("INSERT INTO identity_deletions (user_id, deleted_at, deleted_by) VALUES ('u1', 1, 'self')").run(); + db.sqlite.prepare("DELETE FROM users WHERE id = 'u1'").run(); + await refreshMirror({ DB: db.db }, user(), 7); + expect(db.sqlite.prepare("SELECT COUNT(*) AS n FROM users").get()).toEqual({ n: 0 }); + }); +}); diff --git a/packages/api/src/account/identity.ts b/packages/api/src/account/identity.ts index b7966f81..130e5530 100644 --- a/packages/api/src/account/identity.ts +++ b/packages/api/src/account/identity.ts @@ -25,10 +25,15 @@ export interface IdentityService { listDeletedUsers(sinceMs: number, limit?: number): Promise>; } +import { syncStripeCustomerEmail, type StripeEnv } from "./stripe-client"; + // What every consumer of this module needs from its worker's Env. export interface IdentityEnv { DB: D1Database; IDENTITY?: IdentityService; + // Keeps a linked Stripe customer's receipt address in step when the + // identity email changes (see refreshMirror). + STRIPE_SECRET_KEY?: string; // Local-dev quick login: dev-* users exist only in the mirror (see // routes/auth.ts handleDevQuickLogin), so standing checks skip the RPC. DEV_QUICK_LOGIN?: string; @@ -44,8 +49,15 @@ export interface MirrorUser { status: string; suspended_until: number | null; created_at: string; + // Set by callers that join identity_deletions: the identity service has + // reported this account deleted (cleanup may still be pending). + identity_deleted?: number | null; } +// SQL fragment for readers of the users mirror (alias `u`): whether the +// deletion sync has recorded the account as deleted. +export const IDENTITY_DELETED_SQL = "EXISTS (SELECT 1 FROM identity_deletions x WHERE x.user_id = u.id) AS identity_deleted"; + export type Standing = | { ok: true; isAdmin: boolean } | { ok: false; reason: "disabled" } @@ -105,6 +117,7 @@ export function standingFromIdentity(user: IdentityUser | null, nowMs: number): } export function standingFromMirror(row: Pick, nowMs: number): Standing { + if (row.status === "deleted") return { ok: false, reason: "deleted" }; if (row.status === "disabled") return { ok: false, reason: "disabled" }; if (row.status === "suspended" && row.suspended_until && Math.floor(nowMs / 1000) < row.suspended_until) { return { ok: false, reason: "suspended", until: row.suspended_until }; @@ -123,6 +136,9 @@ export async function accountStanding( nowMs: number = Date.now(), ctx?: { waitUntil(p: Promise): void }, ): Promise { + // A deletion Annex already knows about wins over any cached or fallback + // answer (cleanup by the deletion sync may not have run yet). + if (mirror.identity_deleted || mirror.status === "deleted") return { ok: false, reason: "deleted" }; if (isLocalDevUser(env, mirror.id)) return standingFromMirror(mirror, nowMs); const hit = cache.get(mirror.id); @@ -138,10 +154,16 @@ export async function accountStanding( return standingFromMirror(mirror, nowMs); } remember(mirror.id, user, nowMs); - if (user && mirrorDiffers(mirror, user)) { - const write = refreshMirror(env.DB, user, nowMs).catch(err => - console.error("[identity] mirror refresh failed", { userId: user.id, err: String(err) }), - ); + if (!user) { + // Authoritative "no such account": persist it, so an identity outage + // later can't fall back to a mirror row that still says active. + const write = env.DB.prepare("UPDATE users SET status = 'deleted', synced_at = ? WHERE id = ?").bind(nowMs, mirror.id).run() + .catch(err => console.error("[identity] marking deleted user failed", { userId: mirror.id, err: String(err) })); + if (ctx) ctx.waitUntil(write); + else await write; + } else if (mirrorDiffers(mirror, user)) { + const write = refreshMirror(env, user, nowMs) + .catch(err => console.error("[identity] mirror refresh failed", { userId: user.id, err: String(err) })); if (ctx) ctx.waitUntil(write); else await write; } @@ -166,7 +188,8 @@ export function mirrorUpsertStatements(db: D1Database, user: IdentityUser, nowMs return [ db.prepare( `INSERT INTO users (id, email, name, email_verified, is_admin, status, suspended_until, created_at, first_seen_at, last_login_at, synced_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11 + WHERE NOT EXISTS (SELECT 1 FROM identity_deletions x WHERE x.user_id = ?1) ON CONFLICT(id) DO UPDATE SET email = excluded.email, name = excluded.name, @@ -176,7 +199,10 @@ export function mirrorUpsertStatements(db: D1Database, user: IdentityUser, nowMs suspended_until = excluded.suspended_until, created_at = excluded.created_at, last_login_at = COALESCE(excluded.last_login_at, users.last_login_at), - synced_at = excluded.synced_at`, + synced_at = excluded.synced_at + -- A deletion (recorded by the sync, or a null getUser) is final: an + -- in-flight refresh that read the account earlier must not revive it. + WHERE users.status <> 'deleted' AND NOT EXISTS (SELECT 1 FROM identity_deletions x WHERE x.user_id = excluded.id)`, ).bind( user.id, user.email, @@ -190,21 +216,34 @@ export function mirrorUpsertStatements(db: D1Database, user: IdentityUser, nowMs opts.login ? nowMs : null, nowMs, ), - db.prepare("UPDATE project_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?)") - .bind(user.name, user.email, user.id, user.name, user.email), - db.prepare("UPDATE organization_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?)") - .bind(user.name, user.email, user.id, user.name, user.email), + db.prepare(`UPDATE project_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?) AND NOT EXISTS (SELECT 1 FROM identity_deletions x WHERE x.user_id = ?)`) + .bind(user.name, user.email, user.id, user.name, user.email, user.id), + db.prepare(`UPDATE organization_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?) AND NOT EXISTS (SELECT 1 FROM identity_deletions x WHERE x.user_id = ?)`) + .bind(user.name, user.email, user.id, user.name, user.email, user.id), ]; } // Returns how many member-row snapshots were out of date (and fixed). +// +// Every mirror write goes through here, so this is also where a changed +// email reaches the linked Stripe customer's receipt address: whichever +// refresh (sign-in, standing check, invite lookup, admin) first writes the +// new address is the one that sees the change. The leading SELECT runs in the +// same batch, so it reads the address the upsert replaces. export async function refreshMirror( - db: D1Database, + env: StripeEnv, user: IdentityUser, nowMs: number, opts: { login?: boolean } = {}, ): Promise<{ project_members: number; organization_members: number }> { - const [, projects, orgs] = await db.batch(mirrorUpsertStatements(db, user, nowMs, opts)); + const [before, upsert, projects, orgs] = await env.DB.batch([ + env.DB.prepare("SELECT email FROM users WHERE id = ?").bind(user.id), + ...mirrorUpsertStatements(env.DB, user, nowMs, opts), + ]); + const previous = (before?.results?.[0] as { email?: string } | undefined)?.email; + if (previous && previous !== user.email && (upsert?.meta?.changes ?? 0) > 0) { + await syncStripeCustomerEmail(env, user.id, user.email); + } return { project_members: projects?.meta?.changes ?? 0, organization_members: orgs?.meta?.changes ?? 0 }; } @@ -222,15 +261,18 @@ export async function findUserByEmail(env: IdentityEnv, email: string, nowMs: nu try { user = await env.IDENTITY.findUserByEmail(normalized); } catch (err) { + // The mirror can hold a stale address (it isn't unique), so outside + // local dev an outage must not resolve an invite to the wrong person. + if (!isLocalDeploy(env)) throw err; reached = false; - console.error("[identity] findUserByEmail failed; using mirror", { err: String(err) }); + console.error("[identity] findUserByEmail failed; using mirror (local dev)", { err: String(err) }); } if (reached) { if (!user) return null; // Never resurrect an account Annex has already processed as deleted. const gone = await env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(user.id).first(); if (gone) return null; - await refreshMirror(env.DB, user, nowMs); + await refreshMirror(env, user, nowMs); return { id: user.id, email: user.email, name: user.name }; } } diff --git a/packages/api/src/account/session.ts b/packages/api/src/account/session.ts index e7402a68..bba7b565 100644 --- a/packages/api/src/account/session.ts +++ b/packages/api/src/account/session.ts @@ -9,7 +9,7 @@ import { verifyJwt, signJwt, sha256b64url, randomToken } from "./jwt"; import { resolvePersonalPlan } from "./plan"; -import { accountStanding, type IdentityEnv, type MirrorUser } from "./identity"; +import { accountStanding, IDENTITY_DELETED_SQL, type IdentityEnv, type MirrorUser } from "./identity"; export type SessionKind = "app" | "admin"; @@ -97,6 +97,7 @@ export async function loadCurrentSession( const [userResult, sessionResult] = await db.batch([ db.prepare( `SELECT u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at, + ${IDENTITY_DELETED_SQL}, d.id AS pending_deletion, p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, p.reading_font, p.editing_font, p.ui_font, diff --git a/packages/api/src/collab/DocCollabRoom.ts b/packages/api/src/collab/DocCollabRoom.ts index 567aa526..168c9018 100644 --- a/packages/api/src/collab/DocCollabRoom.ts +++ b/packages/api/src/collab/DocCollabRoom.ts @@ -7,7 +7,7 @@ import type { Env } from "../index"; import { ROLE_RANK } from "../lib"; import { resolveAccess } from "../lib/access"; import { latestDocRevisionContent, snapshotDocRevision } from "../lib/docOps"; -import { accountStanding, standingFromMirror, type MirrorUser } from "../account/identity"; +import { accountStanding, IDENTITY_DELETED_SQL, standingFromMirror, type MirrorUser } from "../account/identity"; const MSG_SYNC = 0; const MSG_AWARENESS = 1; @@ -347,7 +347,8 @@ export class DocCollabRoom implements DurableObject { try { const row = await this.env.DB.prepare( `SELECT s.expires_at, s.revoked_at, s.kind, (d.user_id IS NOT NULL) AS blocked, - u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at + u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at, + ${IDENTITY_DELETED_SQL} FROM sessions s JOIN users u ON u.id = s.user_id LEFT JOIN user_deletions d ON d.user_id = u.id diff --git a/packages/api/src/entrypoint.test.ts b/packages/api/src/entrypoint.test.ts new file mode 100644 index 00000000..7a682440 --- /dev/null +++ b/packages/api/src/entrypoint.test.ts @@ -0,0 +1,14 @@ +import { describe, it, expect } from "vitest"; +import * as worker from "./index"; + +// workerd loads every named export of the main module as an entrypoint; a +// non-handler export (e.g. a string constant) stops the worker from starting +// ("Incorrect type for map entry ..."). +describe("worker main module", () => { + it("exports only handlers and classes", () => { + for (const [name, value] of Object.entries(worker)) { + if (name === "default") continue; + expect(typeof value, name).toBe("function"); + } + }); +}); diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index acaaa14d..c906766c 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -27,10 +27,7 @@ import { resolveAvatar, parseVariant, avatarKey, deleteAllAvatarVariants } from import { resolveAccess } from "./lib/access"; import type { IdentityService } from "./account/identity"; import { sweepSessions } from "./account/session"; -import { syncIdentityDeletions } from "./lib/identityDeletions"; - -// Must match the hourly trigger in cloudflare.config.ts. -export const DELETION_SYNC_CRON = "23 * * * *"; +import { DELETION_SYNC_CRON, syncIdentityDeletions } from "./lib/identityDeletions"; import { handleAuthCallback, handleAuthExchange, handleAuthLogin, handleAuthLogout, handleDevQuickLogin } from "./routes/auth"; import { handleBillingCheckout, handleBillingPortal } from "./routes/billing"; import { handleStripeWebhook } from "./routes/stripeWebhook"; @@ -60,7 +57,7 @@ export interface Env { IDENTITY_OIDC?: Fetcher; // OIDC client settings (see routes/auth.ts). OIDC_CLIENT_SECRET is a secret; // the rest are vars. Redirect URIs default to APP_ORIGIN/api/auth/callback - // and APP_ORIGIN/. + // and APP_ORIGIN (no trailing slash). OIDC_ISSUER?: string; OIDC_CLIENT_ID?: string; OIDC_CLIENT_SECRET?: string; diff --git a/packages/api/src/lib/apiKeys.ts b/packages/api/src/lib/apiKeys.ts index c6762cd4..7ccfa445 100644 --- a/packages/api/src/lib/apiKeys.ts +++ b/packages/api/src/lib/apiKeys.ts @@ -1,6 +1,6 @@ import { ROLE_RANK, type Role } from "../lib"; import type { Env } from "../index"; -import { accountStanding, type MirrorUser } from "../account/identity"; +import { accountStanding, IDENTITY_DELETED_SQL, type MirrorUser } from "../account/identity"; // ── Scoped API keys for the public /v1 API ────────────────────────────────── // @@ -145,6 +145,7 @@ export async function authenticateApiKey(token: string, env: Env): Promise { // Membership elsewhere gone; owner rows on owned site/org kept. expect(count("SELECT COUNT(*) AS n FROM project_members WHERE id = 'm3'")).toBe(0); expect(count("SELECT COUNT(*) AS n FROM project_members WHERE id IN ('m1', 'm2')")).toBe(2); + // ...but the deleted owner's name/email are scrubbed from them. + expect(db.sqlite.prepare("SELECT name, email FROM project_members WHERE id = 'm1'").get()).toEqual({ name: "Deleted account", email: "" }); + expect(db.sqlite.prepare("SELECT name, email FROM organization_members WHERE id = 'om1'").get()).toEqual({ name: "Deleted account", email: "" }); + expect(db.sqlite.prepare("SELECT name FROM project_members WHERE id = 'm2'").get()).toEqual({ name: "O" }); expect(count("SELECT COUNT(*) AS n FROM organization_members WHERE id = 'om1'")).toBe(1); expect(count("SELECT COUNT(*) AS n FROM projects WHERE id = 's1'")).toBe(1); expect(count("SELECT COUNT(*) AS n FROM organizations WHERE id = 'o1'")).toBe(1); @@ -150,6 +154,20 @@ describe("recordIdentityDeletions cursor", () => { for (let i = 1; i <= 150; i++) deletions.push({ userId: `u${i}`, deletedAt: i * 10, deletedBy: "self" }); expect(await recordIdentityDeletions(env())).toBe(150); expect(listDeletedUsers).toHaveBeenCalledTimes(2); - expect(listDeletedUsers).toHaveBeenNthCalledWith(2, 1000, 100); + expect(listDeletedUsers).toHaveBeenNthCalledWith(2, 999, 100); + }); + + it("re-reads a page that can't advance (all one millisecond) at the RPC cap instead of stalling", async () => { + for (let i = 1; i <= 120; i++) deletions.push({ userId: `same${i}`, deletedAt: 700, deletedBy: "admin:bulk" }); + deletions.push({ userId: "later", deletedAt: 800, deletedBy: "self" }); + expect(await recordIdentityDeletions(env())).toBe(121); + expect(listDeletedUsers).toHaveBeenCalledWith(699, 500); + }); + + it("doesn't skip deletions sharing a millisecond across a page boundary", async () => { + for (let i = 1; i <= 99; i++) deletions.push({ userId: `a${i}`, deletedAt: i, deletedBy: "self" }); + for (const id of ["tie1", "tie2", "tie3"]) deletions.push({ userId: id, deletedAt: 500, deletedBy: "self" }); + expect(await recordIdentityDeletions(env())).toBe(102); + expect(count("SELECT COUNT(*) AS n FROM identity_deletions WHERE user_id LIKE 'tie%'")).toBe(3); }); }); diff --git a/packages/api/src/lib/identityDeletions.ts b/packages/api/src/lib/identityDeletions.ts index 15b3a4f3..3642cead 100644 --- a/packages/api/src/lib/identityDeletions.ts +++ b/packages/api/src/lib/identityDeletions.ts @@ -10,7 +10,8 @@ // - memberships, API keys, doc shares, favourites and avatars go, and the // users mirror row is deleted (cascading sessions, billing, preferences, // moderation history and any admin-scheduled deletion); -// - sites and organizations they OWNED are kept, with their owner rows, and +// - sites and organizations they OWNED are kept, with their owner rows +// (name/email snapshots scrubbed to "Deleted account"), and // recorded on the identity_deletions row for an operator to delete or // reassign from the admin panel. Owned sites usually have other members, // and the identity service gave the person no warning about them. @@ -28,30 +29,50 @@ export interface DeletionSyncEnv { STRIPE_SECRET_KEY?: string; } +// Must match the hourly trigger in cloudflare.config.ts. Lives here, not in +// src/index.ts: every named export of the worker's main module is loaded as +// an entrypoint, and a non-handler export stops the worker from starting. +export const DELETION_SYNC_CRON = "23 * * * *"; + const PAGE_SIZE = 100; +// IdentityService.listDeletedUsers' maximum page size. +const MAX_PAGE_SIZE = 500; const MAX_PAGES_PER_RUN = 10; const PROCESS_PER_RUN = 20; // Pulls new deletions from the identity service into identity_deletions. -// The first request re-reads the newest recorded millisecond (`deleted_at > -// cursor - 1`) so deletions sharing it that a previous page cut off aren't -// skipped; INSERT OR IGNORE dedupes. Later pages are strictly after. +// Every request re-reads the newest millisecond seen so far (`deleted_at > +// cursor - 1`), so deletions sharing it that a full page cut off aren't +// skipped; INSERT OR IGNORE dedupes the overlap. export async function recordIdentityDeletions(env: DeletionSyncEnv): Promise { if (!env.IDENTITY) return 0; const row = await env.DB.prepare("SELECT MAX(deleted_at) AS cursor FROM identity_deletions") .first<{ cursor: number | null }>(); let since = row?.cursor != null ? row.cursor - 1 : 0; let recorded = 0; + let limit = PAGE_SIZE; for (let page = 0; page < MAX_PAGES_PER_RUN; page++) { - const deleted = await env.IDENTITY.listDeletedUsers(since, PAGE_SIZE); + const deleted = await env.IDENTITY.listDeletedUsers(since, limit); if (deleted.length === 0) break; const results = await env.DB.batch(deleted.map(d => env.DB.prepare("INSERT OR IGNORE INTO identity_deletions (user_id, deleted_at, deleted_by) VALUES (?, ?, ?)") .bind(d.userId, d.deletedAt, d.deletedBy ?? "unknown"), )); recorded += results.reduce((n, r) => n + (r.meta?.changes ?? 0), 0); - if (deleted.length < PAGE_SIZE) break; - since = deleted[deleted.length - 1].deletedAt; + if (deleted.length < limit) break; + const next = deleted[deleted.length - 1].deletedAt - 1; + if (next <= since) { + // A whole page within one millisecond can't advance the cursor: read + // it again at the RPC's maximum page size. + if (limit < MAX_PAGE_SIZE) { + limit = MAX_PAGE_SIZE; + continue; + } + console.error(`[deletion-sync] more than ${MAX_PAGE_SIZE} deletions share deleted_at ${since + 1}; reconcile by hand`); + break; + } + since = next; + limit = PAGE_SIZE; } return recorded; } @@ -94,6 +115,9 @@ export async function processIdentityDeletion(env: DeletionSyncEnv, userId: stri env.DB.prepare("DELETE FROM api_keys WHERE user_id = ?").bind(userId), env.DB.prepare("DELETE FROM doc_shares WHERE user_id = ?").bind(userId), env.DB.prepare("DELETE FROM user_favourite_projects WHERE user_id = ?").bind(userId), + // The kept owner rows mustn't go on showing the person's name and email. + env.DB.prepare("UPDATE project_members SET name = 'Deleted account', email = '' WHERE user_id = ?").bind(userId), + env.DB.prepare("UPDATE organization_members SET name = 'Deleted account', email = '' WHERE user_id = ?").bind(userId), ]); await deleteAllAvatarVariants(env.ASSETS, userId); diff --git a/packages/api/src/routes/auth.test.ts b/packages/api/src/routes/auth.test.ts index e0159725..65f1fc11 100644 --- a/packages/api/src/routes/auth.test.ts +++ b/packages/api/src/routes/auth.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { createSqliteD1, type SqliteD1 } from "../test/sqliteD1"; import { createFakeIdp, type FakeIdp, type FakeUser } from "../test/fakeIdp"; -import { setOidcFetchForTests, STATE_COOKIE } from "./auth"; +import { setOidcFetchForTests, STATE_COOKIE, handoffCookieName, stateCookieName } from "./auth"; import { clearOidcCaches, identityFetch } from "../account/oidc"; import { clearIdentityCache, type IdentityService, type IdentityUser } from "../account/identity"; import worker, { type Env } from "../index"; @@ -49,8 +49,10 @@ function call(method: string, path: string, init: { token?: string; cookie?: str }), env()); } -function cookieFrom(res: Response): string { - const set = res.headers.get("Set-Cookie") ?? ""; +function cookieFrom(res: Response, name = STATE_COOKIE): string { + // The login-state cookie is named per sign-in (annex_oidc_). + const prefix = name === STATE_COOKIE ? `${STATE_COOKIE}_` : `${name}=`; + const set = res.headers.getSetCookie().find(c => c.startsWith(prefix)) ?? ""; return set.split(";")[0]; } @@ -60,6 +62,15 @@ function fragment(res: Response): URLSearchParams { return new URLSearchParams(loc.slice(loc.indexOf("#") + 1)); } +// The completion page's exchange for a callback response: its attempt id +// (from the fragment) and that attempt's handoff cookie. +function handoff(cb: Response): { path: string; cookie: string; name: string } { + const attempt = fragment(cb).get("attempt")!; + expect(attempt).toMatch(/^[0-9a-f]{32}$/); + const name = handoffCookieName(attempt); + return { path: `/auth/exchange?attempt=${attempt}`, cookie: cookieFrom(cb, name), name }; +} + // login -> authorize at the IdP -> callback; returns the callback response. async function signIn(user: FakeUser = ALICE, returnTo = "/projects"): Promise { const login = await call("GET", `/auth/login?return_to=${encodeURIComponent(returnTo)}`); @@ -70,8 +81,9 @@ async function signIn(user: FakeUser = ALICE, returnTo = "/projects"): Promise { const cb = await signIn(user); - const code = fragment(cb).get("code")!; - const ex = await call("POST", "/auth/exchange", { body: { code } }); + expect(fragment(cb).get("status")).toBe("ok"); + const h = handoff(cb); + const ex = await call("POST", h.path, { cookie: h.cookie }); expect(ex.status).toBe(200); return ((await ex.json()) as { data: { token: string } }).data.token; } @@ -106,7 +118,7 @@ describe("GET /auth/login", () => { expect(loc.searchParams.get("state")).toBeTruthy(); expect(loc.searchParams.get("nonce")).toBeTruthy(); const cookie = res.headers.get("Set-Cookie")!; - expect(cookie).toContain(`${STATE_COOKIE}=`); + expect(cookie).toContain(`${stateCookieName(loc.searchParams.get("state")!)}=`); expect(cookie).toContain("HttpOnly"); expect(cookie).toContain("SameSite=Lax"); expect(cookie).toContain("Secure"); @@ -127,14 +139,22 @@ describe("GET /auth/login", () => { }); describe("GET /auth/callback", () => { - it("verifies the id_token, upserts the users mirror and hands the SPA a single-use code", async () => { + it("verifies the id_token, upserts the users mirror and hands the browser a single-use code in a cookie", async () => { const res = await signIn(ALICE, "/projects/p1"); expect(res.status).toBe(302); - expect(res.headers.get("Set-Cookie")).toContain("Max-Age=0"); + expect(res.headers.getSetCookie().find(c => c.startsWith(`${STATE_COOKIE}_`))).toContain("Max-Age=0"); const frag = fragment(res); expect(frag.get("return_to")).toBe("/projects/p1"); - const code = frag.get("code")!; - expect(code.length).toBeGreaterThan(20); + // The code never appears in a URL: only in an HttpOnly, SameSite=Strict cookie. + expect(frag.get("code")).toBeNull(); + expect(res.headers.get("Location")).not.toContain("code="); + const h = handoff(res); + const set = res.headers.getSetCookie().find(c => c.startsWith(`${h.name}=`))!; + expect(set).toContain("HttpOnly"); + expect(set).toContain("SameSite=Strict"); + expect(set).toContain("Path=/api/auth"); + const cookie = h.cookie; + expect(cookie.length).toBeGreaterThan(60); expect(db.sqlite.prepare("SELECT email, name, is_admin, status FROM users WHERE id = ?").get(ALICE.sub)) .toEqual({ email: ALICE.email, name: ALICE.name, is_admin: 0, status: "active" }); @@ -143,16 +163,38 @@ describe("GET /auth/callback", () => { expect(session.id_token.split(".")).toHaveLength(3); expect(session.handoff_hash).toBeTruthy(); - const ex = await call("POST", "/auth/exchange", { body: { code } }); + const ex = await call("POST", h.path, { cookie }); expect(ex.status).toBe(200); + expect(ex.headers.getSetCookie().find(c => c.startsWith(`${h.name}=`))).toContain("Max-Age=0"); const token = ((await ex.json()) as { data: { token: string } }).data.token; // The code is single use. - expect((await call("POST", "/auth/exchange", { body: { code } })).status).toBe(400); + expect((await call("POST", h.path, { cookie })).status).toBe(400); const me = await call("GET", "/me/favourite-sites", { token }); expect(me.status).toBe(200); }); + it("signs nobody in from a completion link or a code in the body - only the browser holding the cookie", async () => { + const res = await signIn(); + const h = handoff(res); + const value = h.cookie.split("=")[1]; + expect((await call("POST", h.path)).status).toBe(400); + expect((await call("POST", h.path, { body: { code: value } })).status).toBe(400); + // The rightful browser still can (the failed attempts didn't burn it). + expect((await call("POST", h.path, { cookie: h.cookie })).status).toBe(200); + }); + + it("redeems each of two sign-ins finishing at once in one browser as its own session", async () => { + const BOB: FakeUser = { sub: "user-bob", email: "bob@example.com", name: "Bob", roles: ["user"] }; + const a = handoff(await signIn(ALICE)); + const b = handoff(await signIn(BOB)); + const jar = `${a.cookie}; ${b.cookie}`; + const tokenFor = async (path: string) => ((await (await call("POST", path, { cookie: jar })).json()) as { data: { token: string } }).data.token; + const userOf = (t: string) => JSON.parse(atob(t.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))).userId; + expect(userOf(await tokenFor(a.path))).toBe(ALICE.sub); + expect(userOf(await tokenFor(b.path))).toBe(BOB.sub); + }); + it("refreshes name/email on the mirror and the member snapshots at sign-in", async () => { await signInToken(); db.sqlite.prepare("INSERT INTO projects (id, name, owner_id, created_at) VALUES ('p1', 'P', 'x', 't')").run(); @@ -184,11 +226,12 @@ describe("GET /auth/callback", () => { expect(fragment(res).get("error")).toBe("login_expired"); }); - it("refuses a state mismatch (callback from another login)", async () => { + it("refuses a state mismatch (another login's sealed state under this login's cookie name)", async () => { const first = await call("GET", "/auth/login"); const second = await call("GET", "/auth/login"); const cb = new URL(idp.authorize(first.headers.get("Location")!, ALICE)); - const res = await call("GET", `/auth/callback${cb.search}`, { cookie: cookieFrom(second) }); + const secondValue = cookieFrom(second).split("=")[1]; + const res = await call("GET", `/auth/callback${cb.search}`, { cookie: `${stateCookieName(cb.searchParams.get("state")!)}=${secondValue}` }); expect(fragment(res).get("error")).toBeTruthy(); expect(fragment(res).get("code")).toBeNull(); expect(idp.tokenRequests).toBe(0); @@ -222,9 +265,23 @@ describe("GET /auth/callback", () => { expect(db.sqlite.prepare("SELECT COUNT(*) AS n FROM users").get()).toEqual({ n: 0 }); }); + it("keeps two sign-ins started in different tabs apart until both callbacks land", async () => { + const BOB: FakeUser = { sub: "user-bob", email: "bob@example.com", name: "Bob", roles: ["user"] }; + const first = await call("GET", "/auth/login?return_to=/a"); + const second = await call("GET", "/auth/login?return_to=/b"); + const jar = `${cookieFrom(first)}; ${cookieFrom(second)}`; + const cbA = await call("GET", `/auth/callback${new URL(idp.authorize(first.headers.get("Location")!, ALICE)).search}`, { cookie: jar }); + // The first callback clears only its own state cookie. + expect(cbA.headers.getSetCookie().filter(c => c.includes("Max-Age=0")).map(c => c.split("=")[0])).toEqual([cookieFrom(first).split("=")[0]]); + const cbB = await call("GET", `/auth/callback${new URL(idp.authorize(second.headers.get("Location")!, BOB)).search}`, { cookie: jar }); + expect([fragment(cbA).get("return_to"), fragment(cbB).get("return_to")]).toEqual(["/a", "/b"]); + expect([fragment(cbA).get("status"), fragment(cbB).get("status")]).toEqual(["ok", "ok"]); + }); + it("passes an OAuth error code through, never the description", async () => { const login = await call("GET", "/auth/login"); - const res = await call("GET", "/auth/callback?error=access_denied&error_description=%3Cscript%3E", { cookie: cookieFrom(login) }); + const state = new URL(login.headers.get("Location")!).searchParams.get("state")!; + const res = await call("GET", `/auth/callback?error=access_denied&error_description=%3Cscript%3E&state=${state}`, { cookie: cookieFrom(login) }); const frag = fragment(res); expect(frag.get("error")).toBe("access_denied"); expect([...frag.keys()]).toEqual(["error"]); @@ -326,6 +383,24 @@ describe("session standing", () => { expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); }); + it("persists a deleted-account answer, so a later identity outage can't fall back to an active mirror row", async () => { + const token = await signInToken(); + clearIdentityCache(); + identity.getUser.mockResolvedValue(null); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + expect(db.sqlite.prepare("SELECT status FROM users WHERE id = ?").get(ALICE.sub)).toEqual({ status: "deleted" }); + clearIdentityCache(); + identity.getUser.mockRejectedValue(new Error("identity down")); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + }); + + it("a deletion recorded by the sync wins over a cached active answer", async () => { + const token = await signInToken(); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(200); // caches "active" + db.sqlite.prepare("INSERT INTO identity_deletions (user_id, deleted_at, deleted_by) VALUES (?, 1, 'self')").run(ALICE.sub); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + }); + it("caches standing per isolate instead of calling the identity service on every request", async () => { const token = await signInToken(); identity.getUser.mockClear(); @@ -364,7 +439,7 @@ describe("POST /auth/logout", () => { const url = new URL(((await res.json()) as { data: { logoutUrl: string } }).data.logoutUrl); expect(`${url.origin}${url.pathname}`).toBe(`${idp.issuer}/oauth/logout`); expect(url.searchParams.get("id_token_hint")).toBe(idToken); - expect(url.searchParams.get("post_logout_redirect_uri")).toBe(`${APP}/`); + expect(url.searchParams.get("post_logout_redirect_uri")).toBe(APP); expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); }); diff --git a/packages/api/src/routes/auth.ts b/packages/api/src/routes/auth.ts index d73454ef..510d83db 100644 --- a/packages/api/src/routes/auth.ts +++ b/packages/api/src/routes/auth.ts @@ -2,9 +2,11 @@ // // GET /auth/login?return_to=/path -> 302 to the identity service // GET /auth/callback -> verifies, upserts the users mirror, -// creates an Annex session, 302 to the -// SPA's /auth/complete#code=... -// POST /auth/exchange { code } -> { token } (single use, 60s) +// creates an Annex session, sets the +// single-use handoff cookie, 302 to the +// SPA's /auth/complete#status=ok&attempt= +// POST /auth/exchange?attempt= -> { token } (redeems that attempt's +// handoff cookie once, within 60s) // POST /auth/logout -> revokes the Annex session and returns // the identity service's end-session URL // POST /dev/quick-login -> local dev only (DEV_QUICK_LOGIN) @@ -28,7 +30,6 @@ import { } from "../account/oidc"; import { createPendingSession, createSessionToken, redeemHandoff, revokeSessionByToken, type SessionEnv, type SessionKind } from "../account/session"; import { DEV_USER_PREFIX, isLocalDeploy, refreshMirror, type IdentityUser } from "../account/identity"; -import { syncStripeCustomerEmail } from "../account/stripe-client"; export interface AuthRouteEnv extends SessionEnv { OIDC_ISSUER?: string; @@ -42,7 +43,26 @@ export interface AuthRouteEnv extends SessionEnv { IDENTITY_OIDC?: { fetch(input: string, init?: RequestInit): Promise }; } +// One login-state cookie per sign-in, named by its OAuth `state`, so sign-ins +// started in two tabs don't overwrite (or clear) each other's. export const STATE_COOKIE = "annex_oidc"; +const OAUTH_STATE_RE = /^[A-Za-z0-9_-]{16,128}$/; + +export function stateCookieName(state: string): string { + return `${STATE_COOKIE}_${state}`; +} +// The single-use handoff code travels ONLY in this HttpOnly, SameSite=Strict +// cookie - never in a URL - so it can be redeemed only by the browser that +// completed the sign-in (a leaked or crafted /auth/complete link carries +// nothing that signs anyone in). Each sign-in gets its own cookie, named by a +// non-secret attempt id the completion page passes back, so two sign-ins +// finishing at once in one browser each redeem their own session. +export const HANDOFF_COOKIE = "annex_handoff"; +const ATTEMPT_RE = /^[0-9a-f]{32}$/; + +export function handoffCookieName(attempt: string): string { + return `${HANDOFF_COOKIE}_${attempt}`; +} const STATE_COOKIE_PATH = "/api/auth"; export const APP_SCOPE = "openid profile email roles"; @@ -79,7 +99,9 @@ export function oidcConfigFor(env: AuthRouteEnv, origin: string): OidcClientConf clientId: env.OIDC_CLIENT_ID, clientSecret: env.OIDC_CLIENT_SECRET || undefined, redirectUri: env.OIDC_REDIRECT_URI || `${base}/api/auth/callback`, - postLogoutRedirectUri: env.OIDC_POST_LOGOUT_REDIRECT_URI || `${base}/`, + // The provider matches this byte for byte against the registration, + // which is the bare origin (no trailing slash). + postLogoutRedirectUri: env.OIDC_POST_LOGOUT_REDIRECT_URI || base, scope: APP_SCOPE, binding: env.IDENTITY_OIDC, allowPublicFallback: isLocalDeploy({ APP_ORIGIN: base }), @@ -123,15 +145,18 @@ export async function handleLogin(flow: AuthFlow, env: SessionEnv, url: URL): Pr return toComplete(flow, { error: "identity_unavailable" }, []); } const sealed = await sealLoginState(login.state, env.JWT_SECRET); - return redirect(login.url, [stateCookie(STATE_COOKIE, sealed, cookieOpts(flow, LOGIN_STATE_TTL_MS / 1000))]); + return redirect(login.url, [stateCookie(stateCookieName(login.state.state), sealed, cookieOpts(flow, LOGIN_STATE_TTL_MS / 1000))]); } export async function handleCallback(flow: AuthFlow, env: SessionEnv & { STRIPE_SECRET_KEY?: string }, request: Request, url: URL): Promise { const cfg = flow.oidc; if (!cfg) return Response.json({ ok: false, error: "sign_in_not_configured" }, { status: 503 }); - const clear = stateCookie(STATE_COOKIE, "", cookieOpts(flow, 0)); + const oauthState = url.searchParams.get("state") ?? ""; + if (!OAUTH_STATE_RE.test(oauthState)) return toComplete(flow, { error: "login_expired" }, []); + const name = stateCookieName(oauthState); + const clear = stateCookie(name, "", cookieOpts(flow, 0)); - const login = await openLoginState(readCookie(request, STATE_COOKIE), env.JWT_SECRET); + const login = await openLoginState(readCookie(request, name), env.JWT_SECRET); if (!login) return toComplete(flow, { error: "login_expired" }, [clear]); // The user cancelled or the identity service refused: pass the OAuth error @@ -159,15 +184,24 @@ export async function handleCallback(flow: AuthFlow, env: SessionEnv & { STRIPE_ const outcome = await startSession(env, request, identity, flow.kind); if ("error" in outcome) return toComplete(flow, { error: outcome.error }, [clear]); - return toComplete(flow, { code: outcome.handoffCode, return_to: login.returnTo }, [clear]); + const attempt = [...crypto.getRandomValues(new Uint8Array(16))].map(b => b.toString(16).padStart(2, "0")).join(""); + const handoff = handoffCookie(flow, attempt, outcome.handoffCode, 60); + return toComplete(flow, { status: "ok", attempt, return_to: login.returnTo }, [clear, handoff]); +} + +function handoffCookie(flow: AuthFlow, attempt: string, value: string, maxAgeSec: number): string { + return stateCookie(handoffCookieName(attempt), value, cookieOpts(flow, maxAgeSec)).replace("SameSite=Lax", "SameSite=Strict"); } export async function handleExchange(flow: AuthFlow, env: SessionEnv, request: Request): Promise { - const body = await request.json<{ code?: unknown }>().catch(() => null); - const code = typeof body?.code === "string" ? body.code : ""; - const token = await redeemHandoff(env, code, flow.kind); - if (!token) return Response.json({ ok: false, error: "invalid_code" }, { status: 400 }); - return okResponse({ token }); + const attempt = new URL(request.url).searchParams.get("attempt") ?? ""; + const headers = new Headers({ "Cache-Control": "no-store" }); + if (!ATTEMPT_RE.test(attempt)) return Response.json({ ok: false, error: "invalid_code" }, { status: 400, headers }); + const code = readCookie(request, handoffCookieName(attempt)) ?? ""; + const token = code ? await redeemHandoff(env, code, flow.kind) : null; + headers.append("Set-Cookie", handoffCookie(flow, attempt, "", 0)); + if (!token) return Response.json({ ok: false, error: "invalid_code" }, { status: 400, headers }); + return Response.json({ ok: true, data: { token } }, { headers }); } export async function handleLogout(flow: AuthFlow, env: SessionEnv, request: Request): Promise { @@ -195,7 +229,7 @@ export async function startSession( const [gone, blocked, existing] = await env.DB.batch([ env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(identity.sub), env.DB.prepare("SELECT 1 AS x FROM user_deletions WHERE user_id = ?").bind(identity.sub), - env.DB.prepare("SELECT created_at, email FROM users WHERE id = ?").bind(identity.sub), + env.DB.prepare("SELECT created_at FROM users WHERE id = ?").bind(identity.sub), ]); if (gone.results.length > 0) return { error: "account_deleted" }; if (blocked.results.length > 0) return { error: "account_disabled" }; @@ -214,11 +248,7 @@ export async function startSession( suspendedUntil: null, createdAt: (existing.results[0] as { created_at?: string } | undefined)?.created_at ?? new Date(now).toISOString(), }; - await refreshMirror(env.DB, user, now, { login: true }); - // The email is changed on the identity service now; keep the Stripe - // customer's receipt address in step when a sign-in brings a new one. - const previousEmail = (existing.results[0] as { email?: string } | undefined)?.email; - if (previousEmail && previousEmail !== user.email) await syncStripeCustomerEmail(env, user.id, user.email); + await refreshMirror(env, user, now, { login: true }); const { handoffCode } = await createPendingSession(env.DB, { userId: user.id, kind, request, idToken: identity.idToken, nowMs: now }); return { handoffCode }; } @@ -233,7 +263,9 @@ type DevVariant = "standard-free" | "standard-ink" | "admin-free" | "admin-ink"; // // Body: { variant } for a fresh dev user, or { email, name?, admin? } to sign // in as (or create) a specific dev user - the e2e suites use the latter. -export async function handleDevQuickLogin(request: Request, env: AuthRouteEnv & { DEV_QUICK_LOGIN?: string }): Promise { +// The admin worker serves the same route with kind "admin" (always an admin +// dev user, an admin session). +export async function handleDevQuickLogin(request: Request, env: AuthRouteEnv & { DEV_QUICK_LOGIN?: string }, kind: SessionKind = "app"): Promise { if (env.DEV_QUICK_LOGIN !== "true" || !isLocalDeploy(env)) return errorResponse(Errors.NOT_FOUND); const body = await request.json<{ variant?: DevVariant; email?: string; name?: string; admin?: boolean }>().catch(() => null); @@ -262,7 +294,8 @@ export async function handleDevQuickLogin(request: Request, env: AuthRouteEnv & name = `${isAdmin ? "Dev Admin" : "Dev User"}${hasInk ? " (Ink)" : ""}`; } - await refreshMirror(env.DB, { + if (kind === "admin") isAdmin = true; + await refreshMirror(env, { id, email, name, emailVerified: true, isAdmin, status: "active", suspendedUntil: null, createdAt: new Date(now).toISOString(), }, now, { login: true }); if (hasInk) { @@ -270,6 +303,6 @@ export async function handleDevQuickLogin(request: Request, env: AuthRouteEnv & "INSERT OR IGNORE INTO user_billing (user_id, granted_plan, granted_plan_reason, granted_plan_started_at) VALUES (?, 'ink', 'dev', ?)", ).bind(id, now).run(); } - const token = await createSessionToken(env, { userId: id, email, isAdmin, kind: "app", request }); + const token = await createSessionToken(env, { userId: id, email, isAdmin, kind, request }); return okResponse({ token, userId: id }); } diff --git a/packages/api/src/routes/stripeWebhook.test.ts b/packages/api/src/routes/stripeWebhook.test.ts index 59c0385c..b2a9757e 100644 --- a/packages/api/src/routes/stripeWebhook.test.ts +++ b/packages/api/src/routes/stripeWebhook.test.ts @@ -68,6 +68,17 @@ function makeRequest(body: string, sig = "valid-sig") { // subscriptions.retrieve returns the live subscription; by default it matches // the event payload, `liveSub` overrides it (e.g. a stale event). +const customersDel = vi.fn().mockResolvedValue({ deleted: true }); + +// Wraps a MockDB's prepare so the identity_deletions lookup finds the user. +function withDeletedUser(prepare: MockDB["prepare"]) { + const original = prepare.getMockImplementation() as (sql: string) => unknown; + return (sql: string) => { + if (!sql.startsWith("SELECT 1 AS x FROM identity_deletions")) return original(sql); + return { bind: () => ({ first: vi.fn().mockResolvedValue({ x: 1 }) }) }; + }; +} + function mockConstructEvent(event: unknown, liveSub?: unknown) { const evObj = (event as { data?: { object?: unknown } } | null)?.data?.object; vi.mocked(getStripe).mockReturnValue({ @@ -77,6 +88,7 @@ function mockConstructEvent(event: unknown, liveSub?: unknown) { subscriptions: { retrieve: vi.fn().mockResolvedValue(liveSub ?? evObj), }, + customers: { del: customersDel }, } as unknown as ReturnType); } @@ -148,16 +160,59 @@ describe("handleStripeWebhook - checkout.session.completed", () => { expect(db._statements[2]).toContain("INSERT OR IGNORE INTO webhook_events"); }); - it("acknowledges (200) an event for a user Annex no longer has instead of retrying forever", async () => { + it("acknowledges (200) an event for a user Annex no longer has, deleting its Stripe customer", async () => { mockConstructEvent({ id: "evt_gone", type: "checkout.session.completed", data: { object: { id: "cs_9", client_reference_id: "deleted-user", customer: "cus_abc", subscription: "sub_xyz" } }, }); + // first() answers both the idempotency check (falsy = not processed) and, + // after the FK failure, the identity_deletions lookup (truthy = deleted). const db = makeDB([new Error("D1_ERROR: FOREIGN KEY constraint failed: SQLITE_CONSTRAINT")]); + db.prepare.mockImplementation(withDeletedUser(db.prepare)); const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); expect(res.status).toBe(200); expect(db._statements[2]).toContain("INSERT OR IGNORE INTO webhook_events"); + // ...and the customer it carries is deleted, so the account isn't billed. + expect(customersDel).toHaveBeenCalledWith("cus_abc"); + }); + + it("routes an event blocked by a tombstone (deletion racing the write) to customer deletion, then acknowledges", async () => { + mockConstructEvent({ + id: "evt_race", + type: "checkout.session.completed", + data: { object: { id: "cs_13", client_reference_id: "being-deleted", customer: "cus_race", subscription: "sub_race" } }, + }); + // The guarded upsert writes nothing: identity_deletions / a started admin deletion blocked it. + const db = makeDB([{ meta: { changes: 0 } }]); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + expect(db._statements[1]).toContain("NOT EXISTS (SELECT 1 FROM identity_deletions"); + expect(db._statements[1]).toContain("started_at IS NOT NULL"); + expect(customersDel).toHaveBeenCalledWith("cus_race"); + }); + + it("never deletes a customer without evidence: an unknown (not deleted) user is retried, not cleaned up", async () => { + mockConstructEvent({ + id: "evt_new_user", + type: "checkout.session.completed", + data: { object: { id: "cs_12", client_reference_id: "registered-after-export", customer: "cus_live", subscription: "sub_live" } }, + }); + const db = makeDB([new Error("D1_ERROR: FOREIGN KEY constraint failed: SQLITE_CONSTRAINT")]); + expect((await handleStripeWebhook(makeRequest("{}"), makeEnv(db))).status).toBe(500); + expect(customersDel).not.toHaveBeenCalled(); + }); + + it("500s (so Stripe retries) when deleting a gone user's customer fails", async () => { + mockConstructEvent({ + id: "evt_gone2", + type: "checkout.session.completed", + data: { object: { id: "cs_11", client_reference_id: "deleted-user", customer: "cus_x", subscription: "sub_x" } }, + }); + customersDel.mockRejectedValueOnce(Object.assign(new Error("stripe down"), { statusCode: 500 })); + const db = makeDB([new Error("D1_ERROR: FOREIGN KEY constraint failed: SQLITE_CONSTRAINT")]); + db.prepare.mockImplementation(withDeletedUser(db.prepare)); + expect((await handleStripeWebhook(makeRequest("{}"), makeEnv(db))).status).toBe(500); }); it("still 500s (so Stripe retries) on any other write failure", async () => { diff --git a/packages/api/src/routes/stripeWebhook.ts b/packages/api/src/routes/stripeWebhook.ts index ae789c5f..f21bf388 100644 --- a/packages/api/src/routes/stripeWebhook.ts +++ b/packages/api/src/routes/stripeWebhook.ts @@ -119,27 +119,46 @@ async function handleCheckoutCompleted(env: Env, sessionObj: Stripe.Checkout.Ses // - stripe_subscription_id: prefer the INCOMING value. A new checkout // means a new subscription; the old sub id (if any) is by definition // stale at this point. - await ignoreUnknownUser(userId, env.DB.prepare( + await applyBillingWrite(env, userId, customerId, env.DB.prepare( `INSERT INTO user_billing (user_id, stripe_customer_id, stripe_subscription_id) - VALUES (?, ?, ?) + SELECT ?1, ?2, ?3 + WHERE NOT EXISTS (SELECT 1 FROM identity_deletions WHERE user_id = ?1) + AND NOT EXISTS (SELECT 1 FROM user_deletions WHERE user_id = ?1 AND started_at IS NOT NULL) ON CONFLICT(user_id) DO UPDATE SET stripe_customer_id = COALESCE(user_billing.stripe_customer_id, excluded.stripe_customer_id), stripe_subscription_id = COALESCE(excluded.stripe_subscription_id, user_billing.stripe_subscription_id)`, ).bind(userId, customerId, subscriptionId).run()); } -// user_billing references the users mirror. An event for a user Annex no -// longer has (their account was deleted) can't be applied and never will be, -// so acknowledge it instead of 500ing into Stripe's retry loop. -async function ignoreUnknownUser(userId: string, write: Promise): Promise { +// The billing upserts are guarded in the same statement against a tombstone: +// the account deleted on the identity service (identity_deletions, written +// before the deletion sync cleans up) or an admin deletion past its point of +// no return (user_deletions.started_at). Outcomes: +// - applied: done; +// - blocked by the tombstone (0 rows): the account is gone, so delete the +// Stripe customer the event carries (it must never be billed) and +// acknowledge - this also covers an event racing the cleanup; +// - FK failure (no users-mirror row): if tombstoned, as above; otherwise +// (e.g. registered on the old auth worker after the cutover export, not +// signed in to Annex yet) throw, so Stripe redelivers and the event +// applies once the row exists. Never delete without evidence. +async function applyBillingWrite(env: Env, userId: string, customerId: string | null, write: Promise): Promise { try { - await write; + const res = await write; + if ((res?.meta?.changes ?? 1) > 0) return; } catch (err) { - if (err instanceof Error && err.message.includes("FOREIGN KEY constraint failed")) { - console.warn(`Stripe event for unknown user ${userId}; ignoring`); - return; + if (!(err instanceof Error && err.message.includes("FOREIGN KEY constraint failed"))) throw err; + const deleted = await env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(userId).first(); + if (!deleted) throw new Error(`Stripe event for user ${userId}, who has no users-mirror row yet; retry later`); + } + console.warn(`Stripe event for deleted user ${userId}; removing its customer`); + if (customerId) { + try { + await getStripe(env.STRIPE_SECRET_KEY!).customers.del(customerId); + } catch (delErr) { + const code = (delErr as { code?: string; statusCode?: number }) ?? {}; + if (code.code !== "resource_missing" && code.statusCode !== 404) throw delErr; } - throw err; } } @@ -196,12 +215,14 @@ async function handleSubscriptionUpsert(env: Env, eventSub: Stripe.Subscription) // Only set personal_plan_started_at if it's not already populated - // preserves the original supporter date across cancel/resub cycles. - await ignoreUnknownUser(userId, env.DB.prepare( + await applyBillingWrite(env, userId, customerId, env.DB.prepare( `INSERT INTO user_billing ( user_id, stripe_customer_id, stripe_subscription_id, personal_plan, personal_plan_status, personal_period_end, personal_plan_cancel_at, personal_plan_started_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ) SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8 + WHERE NOT EXISTS (SELECT 1 FROM identity_deletions WHERE user_id = ?1) + AND NOT EXISTS (SELECT 1 FROM user_deletions WHERE user_id = ?1 AND started_at IS NOT NULL) ON CONFLICT(user_id) DO UPDATE SET stripe_customer_id = excluded.stripe_customer_id, stripe_subscription_id = excluded.stripe_subscription_id, diff --git a/packages/api/wrangler.config.ts b/packages/api/wrangler.config.ts index 4ce6473d..8f56fd74 100644 --- a/packages/api/wrangler.config.ts +++ b/packages/api/wrangler.config.ts @@ -6,7 +6,7 @@ import { defineWranglerConfig } from "wrangler/experimental-config"; // There is no wrangler.toml. Local dev (`pnpm dev`) runs // `wrangler dev --experimental-new-config --persist-to ../../.wrangler/state`, // which reads this file + cloudflare.config.ts directly: every worker must share -// one local state dir (the api worker reads the auth DB via AUTH_DB), and +// one local state dir (the api and admin workers share cubedocs-main), and // `cf dev` cannot set a persist directory yet. export default defineWranglerConfig({ // Match the previous `wrangler deploy` default (no source map upload). diff --git a/packages/auth/cloudflare.config.ts b/packages/auth/cloudflare.config.ts deleted file mode 100644 index c3d2470f..00000000 --- a/packages/auth/cloudflare.config.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { bindings, defineConfig, triggers } from "cf/config"; - -// D1 migrations for `DB` live in ./migrations (the `cf d1 migrations apply` -// default `--dir`). Apply them with `pnpm migrate` (local) or -// `node scripts/migrate.mjs remote` from the repo root. - -export default defineConfig({ - accountId: "d843ae90cab33e54f4d284bc65d2fd6a", - worker: { - name: "annex-auth", - compatibilityDate: "2026-02-24", - compatibilityFlags: [ - "nodejs_compat", - ], - entrypoint: "src/index.ts", - workersDev: false, - triggers: [ - // Weekly sweep of long-dead session rows (see scheduled handler). - triggers.scheduled({ - schedule: "0 3 * * SUN", - }), - ], - env: { - JWT_ISSUER: bindings.text("https://auth.cubedocs.com"), - ADMIN_APP_ORIGIN: bindings.text("https://admin.cubityfir.st"), - APP_ORIGIN: bindings.text("https://docs.cubityfir.st"), - WEBAUTHN_RP_ID: bindings.text("docs.cubityfir.st"), - WEBAUTHN_RP_NAME: bindings.text("Annex"), - WEBAUTHN_ORIGIN: bindings.text("https://docs.cubityfir.st"), - // Stripe price id for the Annex Ink supporter tier ($5/mo recurring). - // Not a secret - safe to commit. - STRIPE_INK_PRICE_ID: bindings.text("price_1TVJk5Rckd4Ls9nPHpnY4tAN"), - DB: bindings.d1({ - name: "cubedocs-auth", - id: "db327d85-b8c2-4fed-adaa-25e748778c86", - }), - // Cloudflare Flagship feature flags. Shares the same app as the API - // worker so a single source governs both. Flags in use: - // signup (default on) - when false, /register is refused (handleRegister). - // email-verification (default off) - gates registration verification emails, - // blocks unverified logins, and selects the - // confirm-first email-change flow (register.ts / - // login.ts / change-email.ts). - // NOTE: local dev DOES serve this binding with the real flag state, so a - // flag flipped in the Flagship dashboard affects local dev too (e.g. a - // disabled `signup` flag blocks the e2e suites, which register accounts). - // The per-call code defaults only apply when the binding itself is missing. - // Exception: `email-verification` is never enforced on a localhost - // deployment - isEmailVerificationEnabled (verification.ts) bypasses it so - // dashboard flips can't break local login/e2e; set - // DEV_EMAIL_VERIFICATION=true in .dev.vars to opt back in. - FLAGS: bindings.flagship({ - id: "08fb610f-b8ed-4a60-afcf-7f5fe6b9f948", - }), - EMAIL: bindings.sendEmail({ - allowedSenderAddresses: [ - "noreply@docs.cubityfir.st", - ], - }), - // Rate limiters use the GA ratelimit binding: simulated locally in dev - // instead of proxying to Cloudflare - the remote proxy breaks requests - // that arrive via cross-process service bindings. - // Coarse abuse cap, IP-keyed. Per-user limiting for authenticated callers - // happens on the API worker (see RATE_LIMITER_INVITE_LOOKUP there). - RATE_LIMITER_LOOKUP: bindings.rateLimit({ - namespace: "1001", - simple: { - limit: 30, - period: 60, - }, - }), - RATE_LIMITER_AUTH: bindings.rateLimit({ - namespace: "1002", - simple: { - limit: 10, - period: 60, - }, - }), - RATE_LIMITER_EMAIL_VERIFY: bindings.rateLimit({ - namespace: "1003", - simple: { - limit: 3, - period: 60, - }, - }), - // Secrets (set via `npx wrangler secret put --name annex-auth`; - // existing secrets are kept across `cf deploy`): - // JWT_SECRET - // TURNSTILE_SECRET - // STRIPE_SECRET_KEY (sk_test_... or sk_live_...) - // STRIPE_WEBHOOK_SECRET (whsec_... - generated by Stripe when you - // register the /stripe/webhook endpoint) - }, - }, -}); diff --git a/packages/auth/migrations/0001_init.sql b/packages/auth/migrations/0001_init.sql deleted file mode 100644 index 960261c8..00000000 --- a/packages/auth/migrations/0001_init.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE IF NOT EXISTS users ( - id TEXT PRIMARY KEY, - email TEXT NOT NULL UNIQUE, - name TEXT NOT NULL, - password_hash TEXT NOT NULL, - created_at TEXT NOT NULL -); diff --git a/packages/auth/migrations/0002_add_disabled.sql b/packages/auth/migrations/0002_add_disabled.sql deleted file mode 100644 index fc3c8d91..00000000 --- a/packages/auth/migrations/0002_add_disabled.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users ADD COLUMN moderation INTEGER NOT NULL DEFAULT 0; diff --git a/packages/auth/migrations/0003_add_totp.sql b/packages/auth/migrations/0003_add_totp.sql deleted file mode 100644 index 833ac5d9..00000000 --- a/packages/auth/migrations/0003_add_totp.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users ADD COLUMN totp_secret TEXT; diff --git a/packages/auth/migrations/0004_add_webauthn.sql b/packages/auth/migrations/0004_add_webauthn.sql deleted file mode 100644 index b160207a..00000000 --- a/packages/auth/migrations/0004_add_webauthn.sql +++ /dev/null @@ -1,17 +0,0 @@ -CREATE TABLE webauthn_credentials ( - id TEXT PRIMARY KEY, -- base64url credential ID - user_id TEXT NOT NULL, - name TEXT NOT NULL DEFAULT 'Security Key', - public_key TEXT NOT NULL, -- base64url COSE public key - counter INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE -); - -CREATE TABLE webauthn_challenges ( - id TEXT PRIMARY KEY, -- random UUID, used as lookup key - user_id TEXT NOT NULL, - challenge TEXT NOT NULL, -- base64url random bytes - type TEXT NOT NULL, -- 'registration' | 'authentication' - created_at INTEGER NOT NULL -- Unix ms, enforce 5-min TTL at verification -); diff --git a/packages/auth/migrations/0005_add_backup_codes.sql b/packages/auth/migrations/0005_add_backup_codes.sql deleted file mode 100644 index 9528b11a..00000000 --- a/packages/auth/migrations/0005_add_backup_codes.sql +++ /dev/null @@ -1,8 +0,0 @@ -CREATE TABLE backup_codes ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - code_hash TEXT NOT NULL, - used_at TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); -CREATE INDEX backup_codes_user_id ON backup_codes(user_id); diff --git a/packages/auth/migrations/0006_add_force_password_change.sql b/packages/auth/migrations/0006_add_force_password_change.sql deleted file mode 100644 index a90749a7..00000000 --- a/packages/auth/migrations/0006_add_force_password_change.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users ADD COLUMN force_password_change INTEGER NOT NULL DEFAULT 0; diff --git a/packages/auth/migrations/0007_add_user_moderation_events.sql b/packages/auth/migrations/0007_add_user_moderation_events.sql deleted file mode 100644 index b691fc11..00000000 --- a/packages/auth/migrations/0007_add_user_moderation_events.sql +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE user_moderation_events ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - action TEXT NOT NULL, - moderation_value INTEGER NOT NULL, - reason TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - actor_user_id TEXT, - actor_email TEXT -); - -CREATE INDEX user_moderation_events_user_id_created_at - ON user_moderation_events(user_id, created_at DESC); diff --git a/packages/auth/migrations/0008_add_is_admin.sql b/packages/auth/migrations/0008_add_is_admin.sql deleted file mode 100644 index 5e17f473..00000000 --- a/packages/auth/migrations/0008_add_is_admin.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0; diff --git a/packages/auth/migrations/0009_add_admin_handoffs.sql b/packages/auth/migrations/0009_add_admin_handoffs.sql deleted file mode 100644 index 2ba3031e..00000000 --- a/packages/auth/migrations/0009_add_admin_handoffs.sql +++ /dev/null @@ -1,11 +0,0 @@ -CREATE TABLE IF NOT EXISTS admin_handoffs ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - return_to TEXT NOT NULL, - created_at INTEGER NOT NULL, - expires_at INTEGER NOT NULL, - consumed_at INTEGER -); - -CREATE INDEX IF NOT EXISTS idx_admin_handoffs_user_id ON admin_handoffs(user_id); -CREATE INDEX IF NOT EXISTS idx_admin_handoffs_expires_at ON admin_handoffs(expires_at); diff --git a/packages/auth/migrations/0010_add_email_verification.sql b/packages/auth/migrations/0010_add_email_verification.sql deleted file mode 100644 index c9716952..00000000 --- a/packages/auth/migrations/0010_add_email_verification.sql +++ /dev/null @@ -1,15 +0,0 @@ -ALTER TABLE users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 0; -ALTER TABLE users ADD COLUMN email_verified_at TEXT; - --- Existing users are already active - mark them as verified so they aren't locked out. -UPDATE users SET email_verified = 1; - -CREATE TABLE email_verification_tokens ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - created_at INTEGER NOT NULL, - expires_at INTEGER NOT NULL, - consumed_at INTEGER -); - -CREATE INDEX idx_email_verification_tokens_user_id ON email_verification_tokens (user_id); diff --git a/packages/auth/migrations/0011_add_timezone.sql b/packages/auth/migrations/0011_add_timezone.sql deleted file mode 100644 index f09f9963..00000000 --- a/packages/auth/migrations/0011_add_timezone.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users ADD COLUMN timezone TEXT; diff --git a/packages/auth/migrations/0012_add_sessions.sql b/packages/auth/migrations/0012_add_sessions.sql deleted file mode 100644 index 9a40bf8f..00000000 --- a/packages/auth/migrations/0012_add_sessions.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Server-side session records. Each successful login creates one row; the --- JWT carries the row id as the `sid` claim. Per-request validation --- requires a matching, non-revoked, non-expired row, which gives us: --- - per-device revocation ("log out my old laptop") --- - "log out everywhere" via a single UPDATE --- - immediate effect on password change (revoke all-except-current) --- - a list of active sessions surfaced to the user --- We deliberately do NOT store the raw User-Agent string. At session --- creation we derive a coarse device_kind ('phone'|'tablet'|'laptop'| --- 'desktop') and a friendly client_label ('Chrome on macOS') and store --- only those. Less personal data retained, and the values are already --- in the shape we render to the user. -CREATE TABLE sessions ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - created_at INTEGER NOT NULL, - expires_at INTEGER NOT NULL, - last_used_at INTEGER NOT NULL, - device_kind TEXT, - client_label TEXT, - ip TEXT, - revoked_at INTEGER -); - -CREATE INDEX idx_sessions_user_id ON sessions(user_id); -CREATE INDEX idx_sessions_expires_at ON sessions(expires_at); diff --git a/packages/auth/migrations/0013_add_change_token_id.sql b/packages/auth/migrations/0013_add_change_token_id.sql deleted file mode 100644 index c08cdefa..00000000 --- a/packages/auth/migrations/0013_add_change_token_id.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Tracks the most-recently-issued forced-password-change token for a user. --- Each successful login of a flagged user generates a fresh UUID stored --- here and embedded in the JWT as the `cti` claim. /force-change-password --- accepts the token only if the claim still matches the row, so: --- - re-logging in invalidates any prior unused token immediately --- - successful use clears the column, blocking same-token replay -ALTER TABLE users ADD COLUMN change_token_id TEXT; diff --git a/packages/auth/migrations/0014_add_stripe_columns.sql b/packages/auth/migrations/0014_add_stripe_columns.sql deleted file mode 100644 index c1ea5a46..00000000 --- a/packages/auth/migrations/0014_add_stripe_columns.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Per-user subscription state for the Annex Ink supporter tier (and any --- future personal plans). Stripe owns the truth for paid subs; granted_* --- columns are a manual override (comp grants, early-supporter gifts) that --- takes precedence over the Stripe-managed plan in resolvePersonalPlan(). --- --- All nullable so existing users default to free with no migration needed. --- Both the auth and api workers must redeploy after this migration: the --- api worker imports loadCurrentSession from packages/auth/src/session.ts --- which will start reading these columns. -ALTER TABLE users ADD COLUMN stripe_customer_id TEXT; -ALTER TABLE users ADD COLUMN stripe_subscription_id TEXT; -ALTER TABLE users ADD COLUMN personal_plan TEXT; -ALTER TABLE users ADD COLUMN personal_plan_status TEXT; -ALTER TABLE users ADD COLUMN personal_period_end INTEGER; -ALTER TABLE users ADD COLUMN personal_plan_started_at INTEGER; -ALTER TABLE users ADD COLUMN granted_plan TEXT; -ALTER TABLE users ADD COLUMN granted_plan_expires_at INTEGER; -ALTER TABLE users ADD COLUMN granted_plan_reason TEXT; - --- Stripe webhook idempotency. Stripe retries deliveries; we INSERT OR --- IGNORE keyed on event_id and bail out if 0 rows changed (already handled). -CREATE TABLE webhook_events ( - event_id TEXT PRIMARY KEY, - type TEXT NOT NULL, - processed_at INTEGER NOT NULL -); diff --git a/packages/auth/migrations/0015_add_personal_plan_cancel_at.sql b/packages/auth/migrations/0015_add_personal_plan_cancel_at.sql deleted file mode 100644 index 5fde796c..00000000 --- a/packages/auth/migrations/0015_add_personal_plan_cancel_at.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Tracks when an active subscription is scheduled to cancel at the end --- of its current period. Populated from Stripe's sub.cancel_at on every --- customer.subscription.updated event; cleared on resume. NULL when no --- cancellation is pending. Status stays 'active' until Stripe actually --- transitions the sub to canceled, at which point the deletion handler --- clears all per-plan columns. -ALTER TABLE users ADD COLUMN personal_plan_cancel_at INTEGER; diff --git a/packages/auth/migrations/0016_add_granted_plan_started_at.sql b/packages/auth/migrations/0016_add_granted_plan_started_at.sql deleted file mode 100644 index ea500c3c..00000000 --- a/packages/auth/migrations/0016_add_granted_plan_started_at.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Tracks when a manual grant was applied. Lets the resolver surface a --- "Supporter since X" date for gifted users the same way personal_plan_started_at --- does for paid users. Backfills existing grants to "now" since we have no --- prior timestamp - admins can correct individual rows manually if needed. -ALTER TABLE users ADD COLUMN granted_plan_started_at INTEGER; - -UPDATE users - SET granted_plan_started_at = strftime('%s', 'now') * 1000 - WHERE granted_plan IS NOT NULL - AND granted_plan_started_at IS NULL; diff --git a/packages/auth/migrations/0017_add_badges.sql b/packages/auth/migrations/0017_add_badges.sql deleted file mode 100644 index 7ff95d8d..00000000 --- a/packages/auth/migrations/0017_add_badges.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Generic badge bitmask on users. Bit 0 = Developer ("Annex Developer"). --- Add new badges by allocating the next bit; no migration needed per badge. -ALTER TABLE users ADD COLUMN badges INTEGER NOT NULL DEFAULT 0; diff --git a/packages/auth/migrations/0018_add_ink_cosmetic_prefs.sql b/packages/auth/migrations/0018_add_ink_cosmetic_prefs.sql deleted file mode 100644 index f74c66bf..00000000 --- a/packages/auth/migrations/0018_add_ink_cosmetic_prefs.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Annex Ink supporter cosmetic preferences. Both columns are NULL for free --- users and for supporters who haven't customised - the resolver and the UI --- treat NULL as "use the default" (default ring = 'shimmer'; default --- presence colour = the deterministic per-user HSL from userColor()). --- --- These are surfaced through resolvePersonalPlan and loadCurrentSession, --- so a schema change here requires redeploying auth + api workers. -ALTER TABLE users ADD COLUMN personal_plan_style TEXT; -ALTER TABLE users ADD COLUMN personal_presence_color TEXT; diff --git a/packages/auth/migrations/0019_add_user_bio.sql b/packages/auth/migrations/0019_add_user_bio.sql deleted file mode 100644 index 493dd8ce..00000000 --- a/packages/auth/migrations/0019_add_user_bio.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Optional supporter bio shown on the user profile card. Writes are gated to --- Annex Ink members in the auth worker; the column itself stores text from --- anyone who's ever held Ink (so a downgrade preserves the value for if/when --- they re-subscribe). Display gating happens in /users/:id on the API worker. -ALTER TABLE users ADD COLUMN bio TEXT; diff --git a/packages/auth/migrations/0020_add_reading_fonts.sql b/packages/auth/migrations/0020_add_reading_fonts.sql deleted file mode 100644 index febe0b03..00000000 --- a/packages/auth/migrations/0020_add_reading_fonts.sql +++ /dev/null @@ -1,8 +0,0 @@ --- User-selectable reading & editing fonts. NULL means "use the default" --- (sans for reading, sans for editing - the editor's monospace code-line --- rules still apply regardless of this prose-level choice). --- --- Read by loadCurrentSession() and surfaced on the GET /me API response, --- so a schema change here requires redeploying auth + api workers. -ALTER TABLE users ADD COLUMN reading_font TEXT; -ALTER TABLE users ADD COLUMN editing_font TEXT; diff --git a/packages/auth/migrations/0021_add_ui_font.sql b/packages/auth/migrations/0021_add_ui_font.sql deleted file mode 100644 index 32392d13..00000000 --- a/packages/auth/migrations/0021_add_ui_font.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Third tier in the reading-font feature: chrome / UI text (sidebar, settings, --- outline, etc.) gets its own font choice independent of reading and editing. --- NULL means "use the default" same as the other two columns. Same caveat as --- 0020 - read by loadCurrentSession, so a schema change here requires --- redeploying auth + api workers. -ALTER TABLE users ADD COLUMN ui_font TEXT; diff --git a/packages/auth/migrations/0022_add_personal_crit_sparkles.sql b/packages/auth/migrations/0022_add_personal_crit_sparkles.sql deleted file mode 100644 index 0250b551..00000000 --- a/packages/auth/migrations/0022_add_personal_crit_sparkles.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Annex Ink supporter preference: whether to render the sparkle burst on --- dice critical successes. NULL = "use the default" (which is ON), 1 = on, --- 0 = off. Free users get nothing either way; the resolver normalises the --- value to a boolean and forces it false when the user isn't an Ink --- supporter. --- --- Surfaced through resolvePersonalPlan and loadCurrentSession, so a schema --- change here requires redeploying auth + api workers. -ALTER TABLE users ADD COLUMN personal_crit_sparkles INTEGER; diff --git a/packages/auth/migrations/0023_split_user_billing.sql b/packages/auth/migrations/0023_split_user_billing.sql deleted file mode 100644 index 9259e841..00000000 --- a/packages/auth/migrations/0023_split_user_billing.sql +++ /dev/null @@ -1,55 +0,0 @@ --- Move Stripe + plan state off the users table into a 1:1 satellite. --- The users row is read on every authenticated API request via loadCurrentSession; --- pulling 11 plan/Stripe columns inline made every users row much wider than the --- auth-essential columns (id/email/moderation/is_admin/etc.) needed for the hot --- path. Splitting them lets users stay narrow and isolates billing churn from --- the auth fast path. --- --- A user_billing row only exists once a user has interacted with Stripe or --- received a grant; everywhere we read, LEFT JOIN handles the absent-row case. -CREATE TABLE user_billing ( - user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - stripe_customer_id TEXT, - stripe_subscription_id TEXT, - personal_period_end INTEGER, - personal_plan TEXT, - personal_plan_status TEXT, - personal_plan_started_at INTEGER, - personal_plan_cancel_at INTEGER, - granted_plan TEXT, - granted_plan_expires_at INTEGER, - granted_plan_started_at INTEGER, - granted_plan_reason TEXT -); - -INSERT INTO user_billing ( - user_id, stripe_customer_id, stripe_subscription_id, personal_period_end, - personal_plan, personal_plan_status, personal_plan_started_at, personal_plan_cancel_at, - granted_plan, granted_plan_expires_at, granted_plan_started_at, granted_plan_reason -) -SELECT id, stripe_customer_id, stripe_subscription_id, personal_period_end, - personal_plan, personal_plan_status, personal_plan_started_at, personal_plan_cancel_at, - granted_plan, granted_plan_expires_at, granted_plan_started_at, granted_plan_reason -FROM users -WHERE stripe_customer_id IS NOT NULL - OR stripe_subscription_id IS NOT NULL - OR personal_plan IS NOT NULL - OR granted_plan IS NOT NULL - OR personal_plan_started_at IS NOT NULL - OR granted_plan_started_at IS NOT NULL; - --- Webhook event handlers for invoice.paid / payment_failed look up the user by --- stripe_subscription_id, so that lookup needs an index. -CREATE INDEX idx_user_billing_subscription ON user_billing(stripe_subscription_id); - -ALTER TABLE users DROP COLUMN stripe_customer_id; -ALTER TABLE users DROP COLUMN stripe_subscription_id; -ALTER TABLE users DROP COLUMN personal_period_end; -ALTER TABLE users DROP COLUMN personal_plan; -ALTER TABLE users DROP COLUMN personal_plan_status; -ALTER TABLE users DROP COLUMN personal_plan_started_at; -ALTER TABLE users DROP COLUMN personal_plan_cancel_at; -ALTER TABLE users DROP COLUMN granted_plan; -ALTER TABLE users DROP COLUMN granted_plan_expires_at; -ALTER TABLE users DROP COLUMN granted_plan_started_at; -ALTER TABLE users DROP COLUMN granted_plan_reason; diff --git a/packages/auth/migrations/0024_split_user_preferences.sql b/packages/auth/migrations/0024_split_user_preferences.sql deleted file mode 100644 index de87d3f4..00000000 --- a/packages/auth/migrations/0024_split_user_preferences.sql +++ /dev/null @@ -1,49 +0,0 @@ --- Move cosmetic / per-user preference columns off the users table into a 1:1 --- satellite. Same rationale as 0023 (user_billing): the users row is read on --- every authenticated request via loadCurrentSession, and these columns --- (fonts, ring style, presence colour, sparkle toggle, timezone, bio, badges) --- are not auth-essential. bio in particular is potentially long markdown. --- --- A user_preferences row only exists once a user has set at least one --- preference; LEFT JOIN handles the absent-row case throughout the codebase. -CREATE TABLE user_preferences ( - user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - reading_font TEXT, - editing_font TEXT, - ui_font TEXT, - personal_plan_style TEXT, - personal_presence_color TEXT, - personal_crit_sparkles INTEGER, - timezone TEXT, - bio TEXT, - badges INTEGER NOT NULL DEFAULT 0 -); - -INSERT INTO user_preferences ( - user_id, reading_font, editing_font, ui_font, - personal_plan_style, personal_presence_color, personal_crit_sparkles, - timezone, bio, badges -) -SELECT id, reading_font, editing_font, ui_font, - personal_plan_style, personal_presence_color, personal_crit_sparkles, - timezone, bio, COALESCE(badges, 0) -FROM users -WHERE reading_font IS NOT NULL - OR editing_font IS NOT NULL - OR ui_font IS NOT NULL - OR personal_plan_style IS NOT NULL - OR personal_presence_color IS NOT NULL - OR personal_crit_sparkles IS NOT NULL - OR timezone IS NOT NULL - OR bio IS NOT NULL - OR badges != 0; - -ALTER TABLE users DROP COLUMN reading_font; -ALTER TABLE users DROP COLUMN editing_font; -ALTER TABLE users DROP COLUMN ui_font; -ALTER TABLE users DROP COLUMN personal_plan_style; -ALTER TABLE users DROP COLUMN personal_presence_color; -ALTER TABLE users DROP COLUMN personal_crit_sparkles; -ALTER TABLE users DROP COLUMN timezone; -ALTER TABLE users DROP COLUMN bio; -ALTER TABLE users DROP COLUMN badges; diff --git a/packages/auth/migrations/0025_add_theme_prefs.sql b/packages/auth/migrations/0025_add_theme_prefs.sql deleted file mode 100644 index b91a2dae..00000000 --- a/packages/auth/migrations/0025_add_theme_prefs.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Per-user site theme: dark (default) / light / custom. Stored on the --- user_preferences satellite. NULL theme_mode means "use the default" (dark), --- same convention as the font columns (0020/0021). theme_custom_color holds --- the picked #rrggbb base when theme_mode = 'custom', NULL otherwise; the --- frontend derives the full palette from it. --- --- This is gated to global site admins (see routes/update-theme.ts). Same --- caveat as 0020/0021 - read by loadCurrentSession, so a schema change here --- requires redeploying auth + api + admin. -ALTER TABLE user_preferences ADD COLUMN theme_mode TEXT; -ALTER TABLE user_preferences ADD COLUMN theme_custom_color TEXT; diff --git a/packages/auth/migrations/0026_add_admin_audit_log.sql b/packages/auth/migrations/0026_add_admin_audit_log.sql deleted file mode 100644 index 45e5222f..00000000 --- a/packages/auth/migrations/0026_add_admin_audit_log.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Actor-attributed log of privileged admin-worker actions (force --- password change, avatar delete, ink grant/revoke, gift-month, Stripe --- cancel, GDPR export, project feature change / reindex / delete). --- Moderation actions keep their own dedicated history in --- user_moderation_events; everything else lands here. --- --- No FK on actor_user_id / target_id on purpose: audit rows must --- outlive deletion of the actor or the target, and targets span both --- the auth DB (users) and the main DB (projects). -CREATE TABLE admin_audit_log ( - id TEXT PRIMARY KEY, - actor_user_id TEXT NOT NULL, - actor_email TEXT NOT NULL, - action TEXT NOT NULL, - target_type TEXT NOT NULL, - target_id TEXT, - detail TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX admin_audit_log_created_at ON admin_audit_log(created_at DESC); -CREATE INDEX admin_audit_log_actor ON admin_audit_log(actor_user_id, created_at DESC); -CREATE INDEX admin_audit_log_target ON admin_audit_log(target_type, target_id, created_at DESC); diff --git a/packages/auth/migrations/0027_add_webauthn_user_index.sql b/packages/auth/migrations/0027_add_webauthn_user_index.sql deleted file mode 100644 index a0d6a6c1..00000000 --- a/packages/auth/migrations/0027_add_webauthn_user_index.sql +++ /dev/null @@ -1,6 +0,0 @@ --- webauthn_credentials(user_id): the FK declared in 0004_add_webauthn.sql --- was never indexed. Every login does a "do you have any passkeys?" lookup --- keyed by user_id (login.ts), and the passkey register flow + the settings --- credential list + the MFA gate all filter by user_id too. Without this each --- one forces a full scan of every user's credentials. -CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user ON webauthn_credentials(user_id); diff --git a/packages/auth/migrations/0028_add_oauth_clients.sql b/packages/auth/migrations/0028_add_oauth_clients.sql deleted file mode 100644 index 5cc3c283..00000000 --- a/packages/auth/migrations/0028_add_oauth_clients.sql +++ /dev/null @@ -1,49 +0,0 @@ --- "Sign in with Annex" - OIDC identity provider (authorization-code + PKCE). --- Generalizes the single-purpose admin_handoffs flow (0009) into a real --- OAuth2 / OpenID Connect provider so other first-party services can --- authenticate users against their Annex account. --- --- oauth_clients - registry of services allowed to use the flow. One row per --- connected app. `redirect_uris` is a JSON array of EXACT allowed callback --- URLs (no wildcards - the token/authorize paths only ever accept an exact --- string match against this list). `client_secret_hash` is NULL for public --- clients (SPA / native) that authenticate with PKCE alone. --- oauth_codes - short-lived, single-use authorization codes. Generalizes --- admin_handoffs: adds the client binding, the PKCE S256 challenge, the --- granted scope, and the OIDC nonce. Consumed atomically at the token --- endpoint (UPDATE … WHERE consumed_at IS NULL) so a code can't be replayed. - -CREATE TABLE IF NOT EXISTS oauth_clients ( - client_id TEXT PRIMARY KEY, - client_name TEXT NOT NULL, - -- SHA-256 (base64url) of the client secret. NULL => public client (PKCE only). - client_secret_hash TEXT, - -- JSON array of exact allowed redirect URIs. - redirect_uris TEXT NOT NULL, - -- Space-separated scopes this client may request (subset of: openid profile email). - allowed_scopes TEXT NOT NULL DEFAULT 'openid profile email', - -- 1 => first-party: auto-approve and skip the consent screen. 0 => show consent. - trusted INTEGER NOT NULL DEFAULT 0, - -- 1 => disabled (refuses new authorizations) without deleting the row/history. - disabled INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL -); - -CREATE TABLE IF NOT EXISTS oauth_codes ( - code TEXT PRIMARY KEY, - client_id TEXT NOT NULL, - user_id TEXT NOT NULL, - redirect_uri TEXT NOT NULL, - scope TEXT NOT NULL, - -- PKCE S256 challenge: base64url(SHA-256(code_verifier)). Always required. - code_challenge TEXT NOT NULL, - -- OIDC nonce, echoed into the id_token when the client supplied one. - nonce TEXT, - created_at INTEGER NOT NULL, - expires_at INTEGER NOT NULL, - consumed_at INTEGER, - FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_oauth_codes_expires_at ON oauth_codes(expires_at); -CREATE INDEX IF NOT EXISTS idx_oauth_codes_client_id ON oauth_codes(client_id); diff --git a/packages/auth/migrations/0029_add_totp_replay_guard.sql b/packages/auth/migrations/0029_add_totp_replay_guard.sql deleted file mode 100644 index f10268da..00000000 --- a/packages/auth/migrations/0029_add_totp_replay_guard.sql +++ /dev/null @@ -1,7 +0,0 @@ --- TOTP replay guard: the highest 30-second time step whose code has been --- accepted for this user. Verification consumes the step atomically and only --- accepts codes from a strictly later step (RFC 6238 §5.2: the verifier MUST --- NOT accept the same or an earlier OTP), so an observed code cannot be --- replayed within its ±1-step drift window. NULL = no code accepted yet; --- cleared on TOTP disable so a fresh enrollment starts unguarded. -ALTER TABLE users ADD COLUMN totp_last_used_step INTEGER; diff --git a/packages/auth/migrations/0030_add_webauthn_transports.sql b/packages/auth/migrations/0030_add_webauthn_transports.sql deleted file mode 100644 index 8d16b090..00000000 --- a/packages/auth/migrations/0030_add_webauthn_transports.sql +++ /dev/null @@ -1,12 +0,0 @@ --- WebAuthn `transports` hint, persisted at registration and echoed back in --- allowCredentials at authentication. Without it, Chrome on Android defaults to --- the external-authenticator UI (USB / NFC / "use another device") instead of --- offering a synced passkey from a password manager. JSON array of --- AuthenticatorTransportFuture values, e.g. '["internal","hybrid"]'. -ALTER TABLE webauthn_credentials ADD COLUMN transports TEXT; - --- Backfill existing credentials with the platform/synced-passkey hint so they --- benefit immediately without forcing a re-registration. internal+hybrid is the --- combination a password-manager / platform passkey reports; it widens (never --- narrows) the authenticators the browser is willing to offer. -UPDATE webauthn_credentials SET transports = '["internal","hybrid"]' WHERE transports IS NULL; diff --git a/packages/auth/migrations/0031_add_users_created_at_index.sql b/packages/auth/migrations/0031_add_users_created_at_index.sql deleted file mode 100644 index 51629b0d..00000000 --- a/packages/auth/migrations/0031_add_users_created_at_index.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Supports the admin Users list's keyset pagination, which orders by --- (created_at DESC, id DESC). Without this the page scan forces a full sort --- of the users table on every page; with it "newest first" is an index walk. -CREATE INDEX users_created_at ON users(created_at DESC); diff --git a/packages/auth/migrations/0032_add_email_change.sql b/packages/auth/migrations/0032_add_email_change.sql deleted file mode 100644 index f7715416..00000000 --- a/packages/auth/migrations/0032_add_email_change.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Pending new address for an email-change request. --- NULL = plain verification of the account's current email (signup flow). -ALTER TABLE email_verification_tokens ADD COLUMN email TEXT; diff --git a/packages/auth/migrations/0033_index_webauthn_challenge_expiry.sql b/packages/auth/migrations/0033_index_webauthn_challenge_expiry.sql deleted file mode 100644 index a17c8de3..00000000 --- a/packages/auth/migrations/0033_index_webauthn_challenge_expiry.sql +++ /dev/null @@ -1,4 +0,0 @@ --- WebAuthn start is public and lazily removes abandoned ceremonies by age. --- Keep that cleanup bounded as the challenge table grows. -CREATE INDEX IF NOT EXISTS idx_webauthn_challenges_created_at - ON webauthn_challenges(created_at); \ No newline at end of file diff --git a/packages/auth/migrations/0034_add_user_deletions.sql b/packages/auth/migrations/0034_add_user_deletions.sql deleted file mode 100644 index 95241699..00000000 --- a/packages/auth/migrations/0034_add_user_deletions.sql +++ /dev/null @@ -1,38 +0,0 @@ --- Delayed account deletion, scheduled from the admin panel's Users page. --- --- Scheduling disables the account immediately (users.moderation = -1) and --- records a row here; the admin worker's hourly cron performs the permanent --- delete once execute_after has passed. Any admin can cancel before then, --- which restores previous_moderation. The grace window is what makes a --- mistaken (or malicious) delete recoverable. --- --- id identifies THIS schedule: the cron claims a row by (user_id, id), so a --- cancel + reschedule can never be executed on the old schedule's consent. --- lease_until is the cron's short claim (cancel is refused while it is --- live); started_at is set once execution passes its first irreversible step --- (Stripe), after which the deletion can only be finished, not cancelled. --- --- confirm_site_ids / confirm_org_ids are the JSON arrays of sites/orgs the --- operator explicitly agreed to delete along with the account. The cron --- refuses to run (recording last_error) if the account owns anything outside --- them. --- --- Written only by the admin worker (AUTH_DB binding). The row disappears with --- the user (ON DELETE CASCADE); admin_audit_log keeps the history. -CREATE TABLE user_deletions ( - user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - id TEXT NOT NULL, - requested_by TEXT NOT NULL, - requested_by_email TEXT NOT NULL, - requested_at TEXT NOT NULL DEFAULT (datetime('now')), - execute_after INTEGER NOT NULL, - confirm_site_ids TEXT NOT NULL DEFAULT '[]', - confirm_org_ids TEXT NOT NULL DEFAULT '[]', - previous_moderation INTEGER NOT NULL DEFAULT 0, - lease_until INTEGER, - started_at INTEGER, - last_error TEXT, - last_attempt_at TEXT -); - -CREATE INDEX idx_user_deletions_execute_after ON user_deletions(execute_after); diff --git a/packages/auth/migrations/0035_add_user_handle.sql b/packages/auth/migrations/0035_add_user_handle.sql deleted file mode 100644 index 6c6a4c75..00000000 --- a/packages/auth/migrations/0035_add_user_handle.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Opt-in public profile handle, served by the app at /@. Lives on the --- user_preferences satellite: NULL (or no row) means the user hasn't turned --- the profile link on. Stored already-normalized (lowercase, see src/handle.ts) --- so the plain unique index is effectively case-insensitive. --- --- Partial index: SQLite already lets UNIQUE columns hold many NULLs, but the --- WHERE clause keeps the index to just the users who opted in. --- --- Read directly by the API worker's /users/by-handle resolver via AUTH_DB, so --- apply this migration before deploying api. --- --- handle_locked is an admin control (admin worker, PATCH /api/users/:id/handle): --- when 1 the user can't set, change or clear their own handle. Locking with a --- NULL handle bars the user from claiming one (moderation of abusive names); --- locking with a handle set pins an admin-assigned name. -ALTER TABLE user_preferences ADD COLUMN handle TEXT; -ALTER TABLE user_preferences ADD COLUMN handle_locked INTEGER NOT NULL DEFAULT 0; -CREATE UNIQUE INDEX idx_user_preferences_handle ON user_preferences(handle) WHERE handle IS NOT NULL; diff --git a/packages/auth/migrations/0036_perf_indexes.sql b/packages/auth/migrations/0036_perf_indexes.sql deleted file mode 100644 index d9c6cd43..00000000 --- a/packages/auth/migrations/0036_perf_indexes.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Additive performance indexes (no column changes, no drops). None of these --- touch columns read by loadCurrentSession, so no auth -> api -> admin --- redeploy ordering is needed. - --- Retention cleanup by age (DELETE ... WHERE processed_at / expires_at < ?). -CREATE INDEX IF NOT EXISTS idx_webhook_events_processed ON webhook_events(processed_at); -CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_expires ON email_verification_tokens(expires_at); - --- Admin audit log filtered by action (keyset ORDER BY created_at DESC, id DESC), --- and SELECT DISTINCT action for the filter dropdown (covering index scan). -CREATE INDEX IF NOT EXISTS idx_admin_audit_log_action_created - ON admin_audit_log(action, created_at DESC, id DESC); - --- Admin user list "disabled" filter (`u.moderation = -1`). Partial on exactly --- that predicate: SQLite only uses a partial index when the query's WHERE --- contains the index's WHERE term, so a `moderation <> 0` partial would not be --- picked for `= -1` / `> ?`; and a full (moderation, ...) index makes the --- "active" filter read and sort every active user via MULTI-INDEX OR. -CREATE INDEX IF NOT EXISTS idx_users_disabled_created - ON users(created_at DESC, id DESC) WHERE moderation = -1; - --- Case-insensitive email lookup (`WHERE LOWER(email) = LOWER(?)`, routes/lookup.ts). -CREATE INDEX IF NOT EXISTS idx_users_email_lower ON users(lower(email)); diff --git a/packages/auth/package.json b/packages/auth/package.json deleted file mode 100644 index 703b84c8..00000000 --- a/packages/auth/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@annex/auth", - "version": "0.0.1", - "private": true, - "type": "module", - "scripts": { - "dev": "pnpm exec wrangler dev --experimental-new-config --port 8788 --persist-to ../../.wrangler/state", - "migrate": "cf d1 migrations apply db327d85-b8c2-4fed-adaa-25e748778c86 --local --persist-to ../../.wrangler/state", - "build": "tsc", - "deploy": "cf deploy", - "typecheck": "tsc --noEmit", - "test": "vitest run" - }, - "dependencies": { - "@simplewebauthn/server": "^9.0.0", - "stripe": "^17.0.0", - "zxcvbn": "^4.4.2" - }, - "devDependencies": { - "@cloudflare/workers-types": "^4.0.0", - "@types/zxcvbn": "^4.4.5", - "cf": "1.0.0-beta.26", - "typescript": "^5.5.0", - "vitest": "^4.1.6", - "wrangler": "^4.156.0" - } -} diff --git a/packages/auth/schema.sql b/packages/auth/schema.sql deleted file mode 100644 index d616dc4d..00000000 --- a/packages/auth/schema.sql +++ /dev/null @@ -1,20 +0,0 @@ -CREATE TABLE IF NOT EXISTS users ( - id TEXT PRIMARY KEY, - email TEXT NOT NULL UNIQUE, - name TEXT NOT NULL, - password_hash TEXT NOT NULL, - created_at TEXT NOT NULL, - is_admin INTEGER NOT NULL DEFAULT 0 -); - -CREATE TABLE IF NOT EXISTS admin_handoffs ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - return_to TEXT NOT NULL, - created_at INTEGER NOT NULL, - expires_at INTEGER NOT NULL, - consumed_at INTEGER -); - -CREATE INDEX IF NOT EXISTS idx_admin_handoffs_user_id ON admin_handoffs(user_id); -CREATE INDEX IF NOT EXISTS idx_admin_handoffs_expires_at ON admin_handoffs(expires_at); diff --git a/packages/auth/src/admin-handoff.test.ts b/packages/auth/src/admin-handoff.test.ts deleted file mode 100644 index cff3f193..00000000 --- a/packages/auth/src/admin-handoff.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, it, expect, vi } from "vitest"; -import { normalizeAdminCallbackUrl, normalizeNextPath, writeAdminHandoffAudit } from "./admin-handoff"; -import type { Env } from "./index"; - -const PROD_ENV = { - ADMIN_APP_ORIGIN: "https://admin.cubityfir.st", - APP_ORIGIN: "https://docs.cubityfir.st", -} as Env; - -const DEV_ENV = { - ADMIN_APP_ORIGIN: "https://admin.cubityfir.st", - APP_ORIGIN: "http://localhost:5173", -} as Env; - -describe("normalizeNextPath", () => { - it("passes plain absolute paths", () => { - expect(normalizeNextPath("/audit")).toBe("/audit"); - }); - it("rejects non-absolute paths", () => { - expect(normalizeNextPath("audit")).toBeNull(); - expect(normalizeNextPath("https://evil.com")).toBeNull(); - }); - it("rejects protocol-relative forms (AF-S6 twin)", () => { - expect(normalizeNextPath("//evil.com")).toBeNull(); - expect(normalizeNextPath("/\\evil.com")).toBeNull(); - }); -}); - -describe("normalizeAdminCallbackUrl", () => { - it("accepts the production admin origin", () => { - expect(normalizeAdminCallbackUrl("https://admin.cubityfir.st/auth/callback", PROD_ENV)) - .toBe("https://admin.cubityfir.st/auth/callback"); - }); - - it("rejects a // next path even on the production origin", () => { - expect( - normalizeAdminCallbackUrl("https://admin.cubityfir.st/auth/callback?next=%2F%2Fevil.com", PROD_ENV), - ).toBeNull(); - }); - - it("REFUSES localhost callback origins on a production deployment (AB-M6)", () => { - expect(normalizeAdminCallbackUrl("http://localhost:5174/auth/callback", PROD_ENV)).toBeNull(); - expect(normalizeAdminCallbackUrl("http://127.0.0.1:5174/auth/callback", PROD_ENV)).toBeNull(); - }); - - it("allows localhost callback origins only when the deployment itself is local", () => { - expect(normalizeAdminCallbackUrl("http://localhost:5174/auth/callback", DEV_ENV)) - .toBe("http://localhost:5174/auth/callback"); - }); - - it("still rejects arbitrary origins on a local deployment", () => { - expect(normalizeAdminCallbackUrl("https://evil.com/auth/callback", DEV_ENV)).toBeNull(); - }); -}); - -describe("writeAdminHandoffAudit", () => { - it("writes an actor-attributed admin_audit_log row targeting the actor", async () => { - const binds: unknown[][] = []; - const stmt = { - bind: (...args: unknown[]) => { - binds.push(args); - return stmt; - }, - run: vi.fn(async () => ({ meta: { changes: 1 } })), - }; - const env = { DB: { prepare: vi.fn(() => stmt) } } as unknown as Env; - - await writeAdminHandoffAudit(env, { userId: "u-1", email: "a@x.com" }, "admin.handoff.exchange", { sessionId: "s-1" }); - - const prepare = (env.DB.prepare as ReturnType); - expect(prepare.mock.calls[0][0]).toContain("INSERT INTO admin_audit_log"); - const [, actorId, actorEmail, action, targetId, detail] = binds[0]; - expect(actorId).toBe("u-1"); - expect(actorEmail).toBe("a@x.com"); - expect(action).toBe("admin.handoff.exchange"); - expect(targetId).toBe("u-1"); - expect(JSON.parse(detail as string)).toEqual({ sessionId: "s-1" }); - }); -}); diff --git a/packages/auth/src/admin-handoff.ts b/packages/auth/src/admin-handoff.ts deleted file mode 100644 index c838c739..00000000 --- a/packages/auth/src/admin-handoff.ts +++ /dev/null @@ -1,86 +0,0 @@ -import type { Env } from "./index"; - -const LOCAL_ADMIN_ORIGINS = new Set([ - "http://localhost:5174", - "http://127.0.0.1:5174", - "https://localhost:5174", - "https://127.0.0.1:5174", -]); - -export function normalizeNextPath(nextPath: string | null): string | null { - if (nextPath === null) return null; - if (!nextPath.startsWith("/")) return null; - // Reject protocol-relative forms ("//evil.com", "/\evil.com"): they are not - // an open redirect on the admin SPA (React Router refuses the cross-origin - // resolve) but they wedge the callback page after a successful exchange. - if (nextPath.startsWith("//") || nextPath.startsWith("/\\")) return null; - return nextPath; -} - -// Loopback admin origins are for local development only. Gate them on the -// deployment itself being local (same defence as dev-quick-login): otherwise a -// crafted login link + malware listening on a victim admin's localhost:5174 -// could exchange a handoff code for an admin session in production. -function isAllowedLocalAdminOrigin(origin: string, env: Env): boolean { - const isLocalDeploy = /\blocalhost\b|127\.0\.0\.1/.test(env.APP_ORIGIN ?? ""); - return isLocalDeploy && LOCAL_ADMIN_ORIGINS.has(origin); -} - -function buildApprovedCallbackUrl(origin: string, nextPath: string | null): string { - const url = new URL("/auth/callback", origin); - if (nextPath && nextPath !== "/") { - url.searchParams.set("next", nextPath); - } - return url.toString(); -} - -export function normalizeAdminCallbackUrl( - callbackUrl: string, - env: Env, -): string | null { - try { - const url = new URL(callbackUrl); - const nextPath = normalizeNextPath(url.searchParams.get("next")); - if (url.searchParams.has("next") && nextPath === null) return null; - if (url.pathname !== "/auth/callback") return null; - - const productionOrigin = env.ADMIN_APP_ORIGIN; - if (url.origin === productionOrigin) { - return buildApprovedCallbackUrl(productionOrigin, nextPath); - } - - if (isAllowedLocalAdminOrigin(url.origin, env)) { - return buildApprovedCallbackUrl(url.origin, nextPath); - } - - return null; - } catch { - return null; - } -} - -// Audit trail for admin-session minting (admin_audit_log lives in this -// worker's own DB). The admin worker's audit view shows what admins *did*; -// these two rows record *who obtained admin access and when* - the single -// most useful record in an incident. -export async function writeAdminHandoffAudit( - env: Env, - actor: { userId: string; email: string }, - action: "admin.handoff.start" | "admin.handoff.exchange", - detail?: Record, -): Promise { - await env.DB.prepare( - `INSERT INTO admin_audit_log - (id, actor_user_id, actor_email, action, target_type, target_id, detail) - VALUES (?, ?, ?, ?, 'user', ?, ?)`, - ) - .bind( - crypto.randomUUID(), - actor.userId, - actor.email, - action, - actor.userId, - detail ? JSON.stringify(detail) : null, - ) - .run(); -} diff --git a/packages/auth/src/auth-session.ts b/packages/auth/src/auth-session.ts deleted file mode 100644 index 91b1a3a1..00000000 --- a/packages/auth/src/auth-session.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { Env } from "./index"; -import { errorResponse, Errors, type Session } from "./lib"; -import { requireCurrentSessionToken } from "./session"; - -export async function requireAuthenticatedSession( - request: Request, - env: Env, -): Promise { - const authHeader = request.headers.get("Authorization"); - if (!authHeader?.startsWith("Bearer ")) return errorResponse(Errors.UNAUTHORIZED); - - return requireCurrentSessionToken(authHeader.slice(7), env.DB, env.JWT_SECRET); -} diff --git a/packages/auth/src/badges.ts b/packages/auth/src/badges.ts deleted file mode 100644 index 666eca1f..00000000 --- a/packages/auth/src/badges.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Bitmask of per-user "badges" displayed on the profile card. Lives on the -// auth DB users table (column `badges`). Add a new badge by allocating the -// next free bit - no migration required. -// -// Pure module: imported by the api and admin workers via cross-package path -// the same way plan.ts is. - -export const BADGE_DEVELOPER = 1 << 0; -export const BADGE_BETA_TESTER = 1 << 1; - -export const ALL_BADGE_BITS = BADGE_DEVELOPER | BADGE_BETA_TESTER; - -export function hasBadge(bits: number, badge: number): boolean { - return (bits & badge) !== 0; -} - -export function setBadge(bits: number, badge: number, on: boolean): number { - return on ? bits | badge : bits & ~badge; -} diff --git a/packages/auth/src/cleanup.sqlite.test.ts b/packages/auth/src/cleanup.sqlite.test.ts deleted file mode 100644 index a9c5a8dc..00000000 --- a/packages/auth/src/cleanup.sqlite.test.ts +++ /dev/null @@ -1,210 +0,0 @@ -// Real-SQLite scenarios (every auth migration applied) for the cleanup and -// batching paths whose correctness lives in the SQL: the weekly sweep, the -// per-user session GC in createSession, the handoff/OAuth-code GC, and the -// batched lookup-by-id reads. -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../api/src/test/sqliteD1"; - -vi.mock("./auth-session", () => ({ requireAuthenticatedSession: vi.fn() })); -vi.mock("./admin-handoff", () => ({ - normalizeAdminCallbackUrl: vi.fn(() => "https://admin.example/auth/callback"), - writeAdminHandoffAudit: vi.fn(async () => {}), -})); - -import { sweepExpiredRows, SWEEP_RETENTION_MS } from "./cleanup"; -import { createSession, SESSION_TTL_MS } from "./sessions"; -import { handleLookupById } from "./routes/lookup-by-id"; -import { handleAdminHandoffStart } from "./routes/admin-handoff-start"; -import { requireAuthenticatedSession } from "./auth-session"; -import type { Env } from "./index"; - -const AUTH_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url)); -const DAY = 24 * 60 * 60 * 1000; - -function setup() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const env = { - DB: db, - } as unknown as Env; - const addUser = (id: string) => - sqlite.prepare( - "INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, 'U', 'x', datetime('now'))", - ).run(id, `${id}@example.com`); - const ids = (sql: string) => - (sqlite.prepare(sql).all() as Array<{ id: string }>).map(r => r.id).sort(); - return { env, sqlite, addUser, ids }; -} - -function addSession( - sqlite: ReturnType["sqlite"], - id: string, - userId: string, - createdAt: number, - revokedAt: number | null = null, - ttl = SESSION_TTL_MS, -) { - sqlite.prepare( - "INSERT INTO sessions (id, user_id, created_at, expires_at, last_used_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?)", - ).run(id, userId, createdAt, createdAt + ttl, createdAt, revokedAt); -} - -function addToken( - sqlite: ReturnType["sqlite"], - id: string, - userId: string, - expiresAt: number, - email: string | null = null, - consumedAt: number | null = null, -) { - sqlite.prepare( - "INSERT INTO email_verification_tokens (id, user_id, created_at, expires_at, consumed_at, email) VALUES (?, ?, ?, ?, ?, ?)", - ).run(id, userId, expiresAt - DAY, expiresAt, consumedAt, email); -} - -const session = { userId: "u1", email: "u1@example.com", isAdmin: true, expiresAt: Date.now() + DAY }; - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(session as never); -}); - -describe("sweepExpiredRows", () => { - it("deletes only rows past the retention window across every swept table", async () => { - const { env, sqlite, addUser, ids } = setup(); - addUser("u1"); - const now = Date.now(); - const cutoff = now - SWEEP_RETENTION_MS; - - // Sessions: expired before the cutoff, or revoked before it (even when - // it only expired after the cutoff). - addSession(sqlite, "s-expired-old", "u1", cutoff - SESSION_TTL_MS - DAY); - addSession(sqlite, "s-revoked-old", "u1", cutoff - 10 * DAY, cutoff - 9 * DAY); - addSession(sqlite, "s-revoked-old-unexpired-at-cutoff", "u1", cutoff - 2 * DAY, cutoff - DAY); - addSession(sqlite, "s-expired-after-cutoff", "u1", cutoff - 2 * DAY); - addSession(sqlite, "s-expired-recent", "u1", now - SESSION_TTL_MS - DAY); - addSession(sqlite, "s-revoked-recent", "u1", now - DAY, now - DAY / 2); - addSession(sqlite, "s-active", "u1", now - DAY); - addSession(sqlite, "s-admin-old", "u1", cutoff - DAY, null, 12 * 60 * 60 * 1000); - - sqlite.prepare("INSERT INTO webhook_events (event_id, type, processed_at) VALUES (?, 't', ?)").run("evt-old", cutoff - 1); - sqlite.prepare("INSERT INTO webhook_events (event_id, type, processed_at) VALUES (?, 't', ?)").run("evt-recent", now - 3 * DAY); - - addToken(sqlite, "t-expired-old", "u1", cutoff - 1, "new@example.com"); - addToken(sqlite, "t-consumed-old", "u1", cutoff - DAY, null, cutoff - 2 * DAY); - addToken(sqlite, "t-expired-recent", "u1", now - DAY, "new@example.com"); - addToken(sqlite, "t-active", "u1", now + DAY); - - sqlite.prepare("INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, 'u1', 'c', 'authentication', ?)").run("c-old", now - 10 * 60 * 1000); - sqlite.prepare("INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, 'u1', 'c', 'authentication', ?)").run("c-new", now - 1000); - - await sweepExpiredRows(env, now); - - expect(ids("SELECT id FROM sessions")).toEqual(["s-active", "s-expired-after-cutoff", "s-expired-recent", "s-revoked-recent"]); - expect(ids("SELECT event_id AS id FROM webhook_events")).toEqual(["evt-recent"]); - // Recently-expired change tokens survive so verify-email can still - // answer "change_link_expired" for a stale link. - expect(ids("SELECT id FROM email_verification_tokens")).toEqual(["t-active", "t-expired-recent"]); - expect(ids("SELECT id FROM webauthn_challenges")).toEqual(["c-new"]); - }); -}); - -describe("createSession", () => { - it("GCs the user's dead sessions and inserts the new one in one batch", async () => { - const { env, sqlite, addUser, ids } = setup(); - addUser("u1"); - addUser("u2"); - const now = Date.now(); - addSession(sqlite, "u1-expired", "u1", now - SESSION_TTL_MS - DAY); - addSession(sqlite, "u1-revoked", "u1", now - DAY, now - 1000); - addSession(sqlite, "u1-active", "u1", now - DAY); - addSession(sqlite, "u2-expired", "u2", now - SESSION_TTL_MS - DAY); - - const request = new Request("http://auth/login", { - headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0", "CF-Connecting-IP": "203.0.113.1" }, - }); - const sid = await createSession(env, "u1", request, now + SESSION_TTL_MS); - - expect(ids("SELECT id FROM sessions WHERE user_id = 'u1'")).toEqual(["u1-active", sid].sort()); - expect(ids("SELECT id FROM sessions WHERE user_id = 'u2'")).toEqual(["u2-expired"]); - const row = sqlite.prepare("SELECT expires_at, client_label, revoked_at FROM sessions WHERE id = ?").get(sid); - expect(row).toEqual({ expires_at: now + SESSION_TTL_MS, client_label: "Chrome on Windows", revoked_at: null }); - }); -}); - -describe("handleLookupById", () => { - const lookup = (env: Env, userId: string) => - handleLookupById( - new Request("http://auth/lookup-by-id", { method: "POST", body: JSON.stringify({ userId }) }), - env, - ); - - it("returns the user with the newest live pending email", async () => { - const { env, sqlite, addUser } = setup(); - addUser("u1"); - sqlite.prepare("INSERT INTO user_preferences (user_id, timezone, bio) VALUES ('u1', 'Europe/London', 'hi')").run(); - const now = Date.now(); - addToken(sqlite, "t-old", "u1", now + DAY / 2, "older@example.com"); - addToken(sqlite, "t-new", "u1", now + DAY, "newer@example.com"); - addToken(sqlite, "t-expired", "u1", now - 1000, "expired@example.com"); - addToken(sqlite, "t-signup", "u1", now + 2 * DAY, null); - - const res = await lookup(env, "u1"); - expect(res.status).toBe(200); - const json = await res.json<{ ok: boolean; data: Record }>(); - expect(json.data).toEqual({ - userId: "u1", - email: "u1@example.com", - name: "U", - emailVerified: false, - emailVerificationEnabled: false, - pendingEmail: "newer@example.com", - createdAt: expect.any(String), - timezone: "Europe/London", - badges: 0, - bio: "hi", - handle: null, - handleLocked: false, - }); - }); - - it("returns pendingEmail null when no change is in flight", async () => { - const { env, sqlite, addUser } = setup(); - addUser("u1"); - addToken(sqlite, "t-consumed", "u1", Date.now() + DAY, "x@example.com", Date.now()); - - const json = await (await lookup(env, "u1")).json<{ data: { pendingEmail: string | null; timezone: string | null } }>(); - expect(json.data.pendingEmail).toBeNull(); - expect(json.data.timezone).toBeNull(); - }); - - it("404s for an unknown user", async () => { - const { env } = setup(); - expect((await lookup(env, "nobody")).status).toBe(404); - }); -}); - -describe("handoff / authorization-code GC", () => { - it("admin-handoff-start drops expired handoffs and keeps unexpired (incl. consumed) ones", async () => { - const { env, sqlite, addUser, ids } = setup(); - addUser("u1"); - const now = Date.now(); - const add = sqlite.prepare( - "INSERT INTO admin_handoffs (id, user_id, return_to, created_at, expires_at, consumed_at) VALUES (?, 'u1', 'x', ?, ?, ?)", - ); - add.run("h-expired", now - 10 * 60 * 1000, now - 5 * 60 * 1000, null); - add.run("h-expired-consumed", now - 10 * 60 * 1000, now - 5 * 60 * 1000, now - 9 * 60 * 1000); - add.run("h-consumed-live", now - 60 * 1000, now + 4 * 60 * 1000, now - 30 * 1000); - - const res = await handleAdminHandoffStart( - new Request("http://auth/admin/handoff/start", { method: "POST", body: JSON.stringify({ returnTo: "https://admin.example/auth/callback" }) }), - env, - ); - expect(res.status).toBe(200); - const left = ids("SELECT id FROM admin_handoffs"); - expect(left).toHaveLength(2); - expect(left).toContain("h-consumed-live"); - expect(left).not.toContain("h-expired"); - expect(left).not.toContain("h-expired-consumed"); - }); -}); diff --git a/packages/auth/src/cleanup.ts b/packages/auth/src/cleanup.ts deleted file mode 100644 index 3139184a..00000000 --- a/packages/auth/src/cleanup.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { deleteExpiredWebauthnChallenges } from "./webauthn"; -import { SESSION_TTL_MS } from "./sessions"; -import type { Env } from "./index"; - -// Dead rows are kept this long before the weekly sweep removes them - an -// audit cushion for sessions, a replay window far beyond Stripe's ~3-day -// webhook retry schedule, and long enough that a stale email-change link -// still gets verify-email's specific "change_link_expired" answer (that -// lookup needs the expired row to still exist). -export const SWEEP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; - -// Weekly sweep (the `scheduled` cron). Request paths only do per-user -// opportunistic GC, so inactive accounts and global tables are cleaned here. -// Each DELETE is a range predicate on one column so it can be index-backed. -export async function sweepExpiredRows(env: Env, now: number = Date.now()): Promise { - const cutoff = now - SWEEP_RETENTION_MS; - await Promise.all([ - // Expired before the cutoff, or revoked before it. `expires_at` is written - // once at INSERT (createSession: now + at most SESSION_TTL_MS) and never - // extended - the only UPDATEs touch `revoked_at` / `last_used_at` - and - // `revoked_at` >= created_at, so a row revoked before the cutoff has - // `expires_at <= cutoff + SESSION_TTL_MS`. The leading range bound is - // therefore redundant for matching but lets idx_sessions_expires_at - // drive the delete instead of a full SCAN. - env.DB.prepare( - "DELETE FROM sessions WHERE expires_at <= ? AND (expires_at <= ? OR (revoked_at IS NOT NULL AND revoked_at < ?))", - ).bind(cutoff + SESSION_TTL_MS, cutoff, cutoff).run(), - // Stripe idempotency markers (`processed_at` = Date.now() ms). - env.DB.prepare("DELETE FROM webhook_events WHERE processed_at < ?").bind(cutoff).run(), - // Every reader of a token requires `expires_at > now`, so long-expired - // rows are inert (consumed rows expire within VERIFICATION_TTL_MS too). - env.DB.prepare("DELETE FROM email_verification_tokens WHERE expires_at <= ?").bind(cutoff).run(), - deleteExpiredWebauthnChallenges(env, now), - ]); -} diff --git a/packages/auth/src/crypto.ts b/packages/auth/src/crypto.ts deleted file mode 100644 index fefaf8a1..00000000 --- a/packages/auth/src/crypto.ts +++ /dev/null @@ -1,10 +0,0 @@ -export function toArrayBuffer(bytes: Uint8Array): ArrayBuffer { - const { buffer, byteOffset, byteLength } = bytes; - if (buffer instanceof ArrayBuffer) { - return buffer.slice(byteOffset, byteOffset + byteLength); - } - - const copy = new Uint8Array(byteLength); - copy.set(bytes); - return copy.buffer; -} diff --git a/packages/auth/src/email.ts b/packages/auth/src/email.ts deleted file mode 100644 index 005622be..00000000 --- a/packages/auth/src/email.ts +++ /dev/null @@ -1,128 +0,0 @@ -import type { Env } from "./index"; - -// Addresses are user input; escape them before interpolating into HTML bodies. -function escapeHtml(s: string): string { - return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} - -export async function sendVerificationEmail( - env: Env, - toEmail: string, - verifyUrl: string, -): Promise { - try { - await env.EMAIL.send({ - to: toEmail, - from: "noreply@docs.cubityfir.st", - subject: "Verify your Annex email address", - text: [ - "Welcome to Annex!", - "", - "Did you create an account? If so, click the link below to verify your email address:", - "", - verifyUrl, - "", - "This link expires in 24 hours. If you didn't create an account, you can safely ignore this email.", - ].join("\n"), - html: ` - - -

Verify your email address

-

Welcome to Annex!

-

Did you create an account? If so, click the button below to verify your email address.

-

- - Verify email address - -

-

This link expires in 24 hours. If you didn't create an account, you can safely ignore this email.

-

If the button doesn't work, copy and paste this link into your browser:
${verifyUrl}

- -`, - }); - return true; - } catch (err: unknown) { - const code = (err as { code?: string })?.code; - console.error("sendVerificationEmail failed", { code, err }); - return false; - } -} - -// Sent to the NEW address when a signed-in user requests an email change while -// verification is enforced - the change applies only when this link is clicked. -export async function sendEmailChangeConfirmEmail( - env: Env, - toEmail: string, - verifyUrl: string, -): Promise { - try { - await env.EMAIL.send({ - to: toEmail, - from: "noreply@docs.cubityfir.st", - subject: "Confirm your new Annex email address", - text: [ - "You asked to change your Annex account email to this address.", - "", - "Click the link below to confirm the change:", - "", - verifyUrl, - "", - "This link expires in 24 hours. If you didn't request this change, you can safely ignore this email - your account email will stay as it is.", - ].join("\n"), - html: ` - - -

Confirm your new email address

-

You asked to change your Annex account email to this address. Click the button below to confirm the change.

-

- - Confirm email change - -

-

This link expires in 24 hours. If you didn't request this change, you can safely ignore this email - your account email will stay as it is.

-

If the button doesn't work, copy and paste this link into your browser:
${verifyUrl}

- -`, - }); - return true; - } catch (err: unknown) { - const code = (err as { code?: string })?.code; - console.error("sendEmailChangeConfirmEmail failed", { code, err }); - return false; - } -} - -// Security notice to the OLD address once an email change has actually applied. -export async function sendEmailChangedNotice( - env: Env, - oldEmail: string, - newEmail: string, -): Promise { - try { - await env.EMAIL.send({ - to: oldEmail, - from: "noreply@docs.cubityfir.st", - subject: "Your Annex account email was changed", - text: [ - `The email address on your Annex account was changed to ${newEmail}.`, - "", - "If something is wrong with this, contact cubity@cubityfir.st.", - ].join("\n"), - html: ` - - -

Your account email was changed

-

The email address on your Annex account was changed to ${escapeHtml(newEmail)}.

-

If something is wrong with this, contact cubity@cubityfir.st.

- -`, - }); - return true; - } catch (err: unknown) { - const code = (err as { code?: string })?.code; - console.error("sendEmailChangedNotice failed", { code, err }); - return false; - } -} diff --git a/packages/auth/src/fonts.test.ts b/packages/auth/src/fonts.test.ts deleted file mode 100644 index 557ee3e4..00000000 --- a/packages/auth/src/fonts.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { isFontChoice, FONT_CHOICES } from "./fonts"; - -describe("isFontChoice", () => { - it("accepts every value in FONT_CHOICES", () => { - for (const v of FONT_CHOICES) { - expect(isFontChoice(v)).toBe(true); - } - }); - - it("rejects unknown strings", () => { - expect(isFontChoice("comic-sans")).toBe(false); - expect(isFontChoice("")).toBe(false); - expect(isFontChoice("MONO")).toBe(false); - }); - - it("rejects non-strings", () => { - expect(isFontChoice(null)).toBe(false); - expect(isFontChoice(undefined)).toBe(false); - expect(isFontChoice(42)).toBe(false); - expect(isFontChoice({})).toBe(false); - }); -}); diff --git a/packages/auth/src/fonts.ts b/packages/auth/src/fonts.ts deleted file mode 100644 index 1eb358d5..00000000 --- a/packages/auth/src/fonts.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Allowed font-choice ids for the reading_font / editing_font columns on -// users. NULL on the row means "use the default" - the frontend treats -// missing values as the default sans stack. Adding a new choice: append -// the id here, add a CSS stack entry in packages/frontend/src/lib/fonts.ts, -// and add a row to the settings matrix in UserSettingsPage.tsx. -export const FONT_CHOICES = ["mono", "sans", "dyslexic"] as const; -export type FontChoice = typeof FONT_CHOICES[number]; - -export function isFontChoice(value: unknown): value is FontChoice { - return typeof value === "string" && (FONT_CHOICES as readonly string[]).includes(value); -} diff --git a/packages/auth/src/handle.test.ts b/packages/auth/src/handle.test.ts deleted file mode 100644 index 230deecc..00000000 --- a/packages/auth/src/handle.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { normalizeHandle, handleProblem, isValidHandle } from "./handle"; - -describe("normalizeHandle", () => { - it("trims, drops a single leading @ and lowercases", () => { - expect(normalizeHandle(" @Cubity_First ")).toBe("cubity_first"); - expect(normalizeHandle("@@x")).toBe("@x"); - }); -}); - -describe("handleProblem", () => { - it("accepts letters, digits, underscores and inner hyphens", () => { - for (const h of ["abc", "a-b_c", "user123", "9lives", "x".repeat(30)]) { - expect(handleProblem(h), h).toBeNull(); - } - }); - - it("enforces the 3-30 length window", () => { - expect(handleProblem("ab")).toBe("length"); - expect(handleProblem("x".repeat(31))).toBe("length"); - }); - - it("rejects disallowed characters and leading/trailing punctuation", () => { - for (const h of ["has space", "dot.ted", "Upper", "-lead", "trail_", "emoji😀x", "a/b", "..."]) { - expect(handleProblem(h), h).toBe("characters"); - } - }); - - it("rejects reserved names", () => { - expect(handleProblem("admin")).toBe("reserved"); - expect(handleProblem("support")).toBe("reserved"); - expect(isValidHandle("admin")).toBe(false); - expect(isValidHandle("admin2")).toBe(true); - }); -}); diff --git a/packages/auth/src/handle.ts b/packages/auth/src/handle.ts deleted file mode 100644 index dac14fa8..00000000 --- a/packages/auth/src/handle.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Public profile handles (the `/@` link). Pure helpers shared by the -// auth worker's write path (routes/update-handle.ts) and the API worker's -// /users/by-handle resolver. Mirrored for client-side hints in -// packages/frontend/src/lib/handle.ts - keep the rules in sync; the server is -// authoritative. - -export const HANDLE_MIN_LENGTH = 3; -export const HANDLE_MAX_LENGTH = 30; - -// Lowercase letters, digits, `_` and `-`; must start and end with a letter or -// digit. No dots, so a handle can never be `.`/`..` or look like a file path. -const HANDLE_PATTERN = /^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/; - -// Names that would let someone impersonate staff or the product, or that read -// like app routes. Compared against the normalized handle. -const RESERVED_HANDLES = new Set([ - "admin", "administrator", "annex", "annexink", "api", "app", "auth", - "billing", "dashboard", "demo", "dev", "developer", "docs", "everyone", - "help", "here", "ink", "login", "logout", "me", "mod", "moderator", - "moderators", "null", "official", "oauth", "register", "root", "security", - "settings", "staff", "support", "system", "team", "undefined", "user", "users", -]); - -/** Trim, drop one leading `@`, lowercase. Does not validate. */ -export function normalizeHandle(input: string): string { - return input.trim().replace(/^@/, "").toLowerCase(); -} - -export type HandleProblem = "length" | "characters" | "reserved"; - -/** Validate an already-normalized handle. Returns null when it's acceptable. */ -export function handleProblem(handle: string): HandleProblem | null { - if (handle.length < HANDLE_MIN_LENGTH || handle.length > HANDLE_MAX_LENGTH) return "length"; - if (!HANDLE_PATTERN.test(handle)) return "characters"; - if (RESERVED_HANDLES.has(handle)) return "reserved"; - return null; -} - -export function isValidHandle(handle: string): boolean { - return handleProblem(handle) === null; -} diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts deleted file mode 100644 index 2c240d3f..00000000 --- a/packages/auth/src/index.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { clientIp, errorResponse, Errors } from "./lib"; -import { handleRegister } from "./routes/register"; -import { handleLogin } from "./routes/login"; -import { handleVerify } from "./routes/verify"; -import { handleLookup } from "./routes/lookup"; -import { handleLookupById } from "./routes/lookup-by-id"; -import { handleUpdateName } from "./routes/update-name"; -import { handleUpdateTimezone } from "./routes/update-timezone"; -import { handleUpdateInkPrefs } from "./routes/update-ink-prefs"; -import { handleUpdateReadingFont } from "./routes/update-reading-font"; -import { handleUpdateTheme } from "./routes/update-theme"; -import { handleUpdateBio } from "./routes/update-bio"; -import { handleUpdateHandle } from "./routes/update-handle"; -import { handleTotpSetup } from "./routes/totp-setup"; -import { handleTotpEnable } from "./routes/totp-enable"; -import { handleTotpDisable } from "./routes/totp-disable"; -import { handleTotpStatus } from "./routes/totp-status"; -import { handleChangePassword } from "./routes/change-password"; -import { handleChangeEmail } from "./routes/change-email"; -import { handleChangeEmailResend } from "./routes/change-email-resend"; -import { handleChangeEmailCancel } from "./routes/change-email-cancel"; -import { handleForceChangePassword } from "./routes/force-change-password"; -import { handleWebauthnRegisterStart } from "./routes/webauthn-register-start"; -import { handleWebauthnRegisterFinish } from "./routes/webauthn-register-finish"; -import { handleWebauthnAuthStart } from "./routes/webauthn-auth-start"; -import { handleWebauthnAuthFinish } from "./routes/webauthn-auth-finish"; -import { handlePasskeyAuthStart } from "./routes/passkey-auth-start"; -import { handlePasskeyAuthFinish } from "./routes/passkey-auth-finish"; -import { handleWebauthnCredentialsList } from "./routes/webauthn-credentials-list"; -import { handleWebauthnCredentialsDelete } from "./routes/webauthn-credentials-delete"; -import { handleTotpBackupCodesGenerate } from "./routes/totp-backup-codes-generate"; -import { handleAdminHandoffStart } from "./routes/admin-handoff-start"; -import { handleAdminHandoffExchange } from "./routes/admin-handoff-exchange"; -import { handleVerifyEmail } from "./routes/verify-email"; -import { handleVerifyEmailResend } from "./routes/verify-email-resend"; -import { handleDeleteAccount } from "./routes/delete-account"; -import { handleSessionsList } from "./routes/sessions-list"; -import { handleSessionsRevoke } from "./routes/sessions-revoke"; -import { handleSessionsRevokeOthers } from "./routes/sessions-revoke-others"; -import { handleSessionsLogout } from "./routes/sessions-logout"; -import { handleBillingCheckout, handleBillingPortal } from "./routes/billing"; -import { handleStripeWebhook } from "./routes/stripe-webhook"; -import { handleDevQuickLogin } from "./routes/dev-quick-login"; -import { sweepExpiredRows } from "./cleanup"; - -export interface Env { - DB: D1Database; - JWT_SECRET: string; - JWT_ISSUER: string; - ADMIN_APP_ORIGIN: string; - APP_ORIGIN: string; - TURNSTILE_SECRET: string; - WEBAUTHN_RP_ID: string; - WEBAUTHN_RP_NAME: string; - WEBAUTHN_ORIGIN: string; - EMAIL: { - send(message: { - to: string; - from: string; - subject: string; - text?: string; - html?: string; - }): Promise<{ messageId: string }>; - }; - // Cloudflare Flagship feature flags (shares the API worker's app). Optional so - // local dev / flag-service outages fall back to each call's default. Flags in - // use: `email-verification` (default off) gates registration verification, the - // unverified-login block (register.ts / login.ts), and the confirm-first email - // change flow (change-email.ts); `signup` gates new account registration - // (handleRegister). - FLAGS?: { getBooleanValue(flag: string, defaultValue: boolean, ctx?: Record): Promise }; - RATE_LIMITER_LOOKUP: { limit(opts: { key: string }): Promise<{ success: boolean }> }; - RATE_LIMITER_AUTH: { limit(opts: { key: string }): Promise<{ success: boolean }> }; - RATE_LIMITER_EMAIL_VERIFY: { limit(opts: { key: string }): Promise<{ success: boolean }> }; - STRIPE_SECRET_KEY: string; - STRIPE_WEBHOOK_SECRET: string; - DEV_QUICK_LOGIN?: string; - // Local-only opt-in (.dev.vars): re-enable email-verification enforcement on - // a localhost deployment, which isEmailVerificationEnabled otherwise - // bypasses regardless of the dashboard flag (see verification.ts). - DEV_EMAIL_VERIFICATION?: string; - STRIPE_INK_PRICE_ID: string; -} - -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { - const url = new URL(request.url); - - // Every route is reached from the app origin (over the api/frontend - // service bindings). The OpenID provider that used to live here moved to - // the cubityfirst-auth worker at https://auth.cubityfir.st. - const corsOrigin = "https://docs.cubityfir.st"; - - // CORS preflight - if (request.method === "OPTIONS") { - return new Response(null, { status: 204, headers: corsHeaders(corsOrigin) }); - } - - // CF-Connecting-IP is present only when this worker is hit directly at the - // edge (e.g. auth.cubityfir.st). App traffic arrives via two service-binding - // hops (frontend → api → auth) which drop that header, so the frontend - // worker forwards the edge-observed IP as X-Client-IP and the API worker - // re-forwards it. CF-Connecting-IP takes precedence because the edge sets - // it unspoofably; X-Client-IP is only honored when it's absent, i.e. on - // trusted service-binding hops. Without this fallback every proxied request - // shared the single "unknown" rate-limit bucket. - const ip = clientIp(request) ?? "unknown"; - let response: Response; - - try { - if (url.pathname === "/register" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleRegister(request, env); - } else if (url.pathname === "/login" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleLogin(request, env); - } else if (url.pathname === "/verify" && request.method === "GET") { - response = await handleVerify(request, env, ctx); - } else if (url.pathname === "/lookup" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_LOOKUP.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleLookup(request, env); - } else if (url.pathname === "/lookup-by-id" && request.method === "POST") { - response = await handleLookupById(request, env); - } else if (url.pathname === "/update-name" && request.method === "POST") { - response = await handleUpdateName(request, env); - } else if (url.pathname === "/update-timezone" && request.method === "POST") { - response = await handleUpdateTimezone(request, env); - } else if (url.pathname === "/update-ink-prefs" && request.method === "POST") { - response = await handleUpdateInkPrefs(request, env); - } else if (url.pathname === "/update-reading-font" && request.method === "POST") { - response = await handleUpdateReadingFont(request, env); - } else if (url.pathname === "/update-theme" && request.method === "POST") { - response = await handleUpdateTheme(request, env); - } else if (url.pathname === "/update-bio" && request.method === "POST") { - response = await handleUpdateBio(request, env); - } else if (url.pathname === "/update-handle" && request.method === "POST") { - response = await handleUpdateHandle(request, env); - } else if (url.pathname === "/totp/setup" && request.method === "POST") { - response = await handleTotpSetup(request, env); - } else if (url.pathname === "/totp/enable" && request.method === "POST") { - response = await handleTotpEnable(request, env); - } else if (url.pathname === "/totp/disable" && request.method === "POST") { - response = await handleTotpDisable(request, env); - } else if (url.pathname === "/totp/status" && request.method === "POST") { - response = await handleTotpStatus(request, env); - } else if (url.pathname === "/change-password" && request.method === "POST") { - response = await handleChangePassword(request, env); - } else if (url.pathname === "/change-email" && request.method === "POST") { - // Same limiter as the other verification-email senders (3/60s). - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleChangeEmail(request, env); - } else if (url.pathname === "/change-email/resend" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleChangeEmailResend(request, env); - } else if (url.pathname === "/change-email/cancel" && request.method === "POST") { - response = await handleChangeEmailCancel(request, env); - } else if (url.pathname === "/force-change-password" && request.method === "POST") { - response = await handleForceChangePassword(request, env); - } else if (url.pathname === "/verify-email" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleVerifyEmail(request, env); - } else if (url.pathname === "/verify-email/resend" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleVerifyEmailResend(request, env); - } else if (url.pathname === "/admin/handoff/start" && request.method === "POST") { - response = await handleAdminHandoffStart(request, env); - } else if (url.pathname === "/admin/handoff/exchange" && request.method === "POST") { - response = await handleAdminHandoffExchange(request, env); - } else if (url.pathname === "/webauthn/register/start" && request.method === "POST") { - response = await handleWebauthnRegisterStart(request, env); - } else if (url.pathname === "/webauthn/register/finish" && request.method === "POST") { - response = await handleWebauthnRegisterFinish(request, env); - } else if (url.pathname === "/webauthn/auth/start" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleWebauthnAuthStart(request, env); - } else if (url.pathname === "/webauthn/auth/finish" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handleWebauthnAuthFinish(request, env); - } else if (url.pathname === "/webauthn/auth/passkey/start" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handlePasskeyAuthStart(request, env); - } else if (url.pathname === "/webauthn/auth/passkey/finish" && request.method === "POST") { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); - if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); - response = await handlePasskeyAuthFinish(request, env); - } else if (url.pathname === "/webauthn/credentials" && request.method === "POST") { - response = await handleWebauthnCredentialsList(request, env); - } else if (url.pathname === "/webauthn/credentials/delete" && request.method === "POST") { - response = await handleWebauthnCredentialsDelete(request, env); - } else if (url.pathname === "/totp/backup-codes/generate" && request.method === "POST") { - response = await handleTotpBackupCodesGenerate(request, env); - } else if (url.pathname === "/delete-account" && request.method === "POST") { - response = await handleDeleteAccount(request, env); - } else if (url.pathname === "/sessions/list" && request.method === "POST") { - response = await handleSessionsList(request, env); - } else if (url.pathname === "/sessions/revoke" && request.method === "POST") { - response = await handleSessionsRevoke(request, env); - } else if (url.pathname === "/sessions/revoke-others" && request.method === "POST") { - response = await handleSessionsRevokeOthers(request, env); - } else if (url.pathname === "/sessions/logout" && request.method === "POST") { - response = await handleSessionsLogout(request, env); - } else if (url.pathname === "/billing/checkout" && request.method === "POST") { - response = await handleBillingCheckout(request, env); - } else if (url.pathname === "/billing/portal" && request.method === "POST") { - response = await handleBillingPortal(request, env); - } else if (url.pathname === "/stripe/webhook" && request.method === "POST") { - // Stripe webhook handler reads its own raw body for signature - // verification; it must NOT be wrapped by anything that calls - // request.json() upstream. CORS is also irrelevant - Stripe - // calls this server-to-server, not from a browser. - response = await handleStripeWebhook(request, env); - } else if (url.pathname === "/dev/quick-login" && request.method === "POST") { - response = await handleDevQuickLogin(request, env); - } else { - response = errorResponse(Errors.NOT_FOUND); - } - } catch (err) { - console.error(err); - response = errorResponse(Errors.INTERNAL); - } - - return addCorsHeaders(response, corsOrigin); - }, - - // Weekly sweep of long-dead rows (sessions, Stripe webhook markers, email - // tokens, WebAuthn challenges) - see cleanup.ts. Login does opportunistic - // GC for the logging-in user, but inactive accounts never get cleaned up - // that way. - async scheduled(_controller: ScheduledController, env: Env, _ctx: ExecutionContext): Promise { - await sweepExpiredRows(env); - }, -}; - -function corsHeaders(origin: string): HeadersInit { - return { - "Access-Control-Allow-Origin": origin, - "Access-Control-Allow-Methods": "GET, POST, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Authorization", - }; -} - -function addCorsHeaders(response: Response, origin: string): Response { - const headers = new Headers(response.headers); - for (const [k, v] of Object.entries(corsHeaders(origin))) { - headers.set(k, v); - } - return new Response(response.body, { status: response.status, headers }); -} diff --git a/packages/auth/src/jwt.test.ts b/packages/auth/src/jwt.test.ts deleted file mode 100644 index d5430cf8..00000000 --- a/packages/auth/src/jwt.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { signJwt, verifyJwt } from "./jwt"; -import type { Session } from "./lib"; - -const SECRET = "test-jwt-secret"; -const PAYLOAD: Session = { - userId: "user-abc", - email: "test@example.com", - expiresAt: Date.now() + 60_000, -}; - -describe("signJwt / verifyJwt", () => { - it("round-trips: verify returns the original payload", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const session = await verifyJwt(token, SECRET); - expect(session).not.toBeNull(); - expect(session!.userId).toBe(PAYLOAD.userId); - expect(session!.email).toBe(PAYLOAD.email); - expect(session!.expiresAt).toBe(PAYLOAD.expiresAt); - }); - - it("returns null when verified with the wrong secret", async () => { - const token = await signJwt(PAYLOAD, SECRET); - expect(await verifyJwt(token, "wrong-secret")).toBeNull(); - }); - - it("returns null for a token with only two parts", async () => { - expect(await verifyJwt("header.payload", SECRET)).toBeNull(); - }); - - it("returns null for an empty string", async () => { - expect(await verifyJwt("", SECRET)).toBeNull(); - }); - - it("returns null for a token with a tampered payload", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const [h, , s] = token.split("."); - const tampered = btoa(JSON.stringify({ ...PAYLOAD, isAdmin: true })) - .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - expect(await verifyJwt(`${h}.${tampered}.${s}`, SECRET)).toBeNull(); - }); - - it("returns null for an expired token", async () => { - const expired: Session = { ...PAYLOAD, expiresAt: Date.now() - 1000 }; - const token = await signJwt(expired, SECRET); - expect(await verifyJwt(token, SECRET)).toBeNull(); - }); - - it("preserves optional isAdmin field", async () => { - const admin: Session = { ...PAYLOAD, isAdmin: true }; - const token = await signJwt(admin, SECRET); - const session = await verifyJwt(token, SECRET); - expect(session!.isAdmin).toBe(true); - }); - - it("preserves optional forcePasswordChange field", async () => { - const forced: Session = { ...PAYLOAD, forcePasswordChange: true }; - const token = await signJwt(forced, SECRET); - const session = await verifyJwt(token, SECRET); - expect(session!.forcePasswordChange).toBe(true); - }); - - it("preserves optional sid field", async () => { - const withSid: Session = { ...PAYLOAD, sid: "session-uuid" }; - const token = await signJwt(withSid, SECRET); - const session = await verifyJwt(token, SECRET); - expect(session!.sid).toBe("session-uuid"); - }); - - it("rejects a token whose header alg is not HS256", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const [, body, sig] = token.split("."); - // Replace the header with one that claims `alg: none` while keeping the - // body and (now-invalid) signature - the alg check must reject before - // the signature is consulted. - const noneHeader = btoa(JSON.stringify({ alg: "none", typ: "JWT" })) - .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - expect(await verifyJwt(`${noneHeader}.${body}.${sig}`, SECRET)).toBeNull(); - }); - - it("rejects a token whose header typ is not JWT", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const [, body, sig] = token.split("."); - const wrongTyp = btoa(JSON.stringify({ alg: "HS256", typ: "JWE" })) - .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - expect(await verifyJwt(`${wrongTyp}.${body}.${sig}`, SECRET)).toBeNull(); - }); - - it("rejects a token with an unparseable header", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const [, body, sig] = token.split("."); - expect(await verifyJwt(`!!!.${body}.${sig}`, SECRET)).toBeNull(); - }); - - it("returns null (not a throw) for a signature that is not valid base64", async () => { - const token = await signJwt(PAYLOAD, SECRET); - const [h, body] = token.split("."); - await expect(verifyJwt(`${h}.${body}.!!!not-base64!!!`, SECRET)).resolves.toBeNull(); - }); - - it("rejects a correctly-signed token that lacks expiresAt", async () => { - const noExpiry = { userId: "user-abc", email: "test@example.com" } as unknown as Session; - const token = await signJwt(noExpiry, SECRET); - expect(await verifyJwt(token, SECRET)).toBeNull(); - }); - - it("rejects a correctly-signed token whose expiresAt is not a number", async () => { - const badExpiry = { ...PAYLOAD, expiresAt: "9999999999999" } as unknown as Session; - const token = await signJwt(badExpiry, SECRET); - expect(await verifyJwt(token, SECRET)).toBeNull(); - }); -}); diff --git a/packages/auth/src/jwt.ts b/packages/auth/src/jwt.ts deleted file mode 100644 index 4fc38b37..00000000 --- a/packages/auth/src/jwt.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { toArrayBuffer } from "./crypto"; -import type { Session } from "./lib"; - -const ALG = { name: "HMAC", hash: "SHA-256" }; - -async function importKey(secret: string): Promise { - const enc = new TextEncoder(); - return crypto.subtle.importKey("raw", toArrayBuffer(enc.encode(secret)), ALG, false, ["sign", "verify"]); -} - -function b64url(buf: ArrayBuffer): string { - return btoa(String.fromCharCode(...new Uint8Array(buf))) - .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} - -function b64urlDecode(str: string): string { - return atob(str.replace(/-/g, "+").replace(/_/g, "/")); -} - -function encodeJSON(obj: unknown): string { - return b64url(toArrayBuffer(new TextEncoder().encode(JSON.stringify(obj)))); -} - -export async function signJwt(payload: Session, secret: string): Promise { - const header = encodeJSON({ alg: "HS256", typ: "JWT" }); - const body = encodeJSON(payload); - const key = await importKey(secret); - const sig = await crypto.subtle.sign(ALG, key, new TextEncoder().encode(`${header}.${body}`)); - return `${header}.${body}.${b64url(sig)}`; -} - -export async function verifyJwt(token: string, secret: string): Promise { - const parts = token.split("."); - if (parts.length !== 3) return null; - - // Pin the algorithm explicitly. Without this, a future verifier that - // accepts multiple algs is one bug away from `alg: none` / RS→HS confusion. - let header: { alg?: unknown; typ?: unknown }; - try { - header = JSON.parse(b64urlDecode(parts[0])); - } catch { - return null; - } - if (header.alg !== "HS256" || header.typ !== "JWT") return null; - - // atob throws on non-base64 input - a garbage signature must read as an - // invalid token (401), not bubble up as an internal error (500). - let sigBytes: Uint8Array; - try { - sigBytes = Uint8Array.from(b64urlDecode(parts[2]), c => c.charCodeAt(0)); - } catch { - return null; - } - - const key = await importKey(secret); - const valid = await crypto.subtle.verify( - ALG, - key, - toArrayBuffer(sigBytes), - toArrayBuffer(new TextEncoder().encode(`${parts[0]}.${parts[1]}`)), - ); - if (!valid) return null; - - let payload: Session; - try { - payload = JSON.parse(b64urlDecode(parts[1])); - } catch { - return null; - } - // Fail closed on a missing/malformed expiry: `undefined < n` is false, so - // without the type check a payload lacking expiresAt would never expire. - if (typeof payload.expiresAt !== "number" || payload.expiresAt < Date.now()) return null; - - return payload; -} diff --git a/packages/auth/src/lib.test.ts b/packages/auth/src/lib.test.ts deleted file mode 100644 index 2974f2a4..00000000 --- a/packages/auth/src/lib.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { clientIp, normalizeEmail } from "./lib"; - -describe("normalizeEmail", () => { - it("strips leading and trailing whitespace", () => { - expect(normalizeEmail(" user@example.com ")).toBe("user@example.com"); - }); - - it("strips tabs and newlines as well as spaces", () => { - expect(normalizeEmail("\tuser@example.com\n")).toBe("user@example.com"); - }); - - it("lowercases the address", () => { - expect(normalizeEmail("User@Example.COM")).toBe("user@example.com"); - }); - - it("returns empty string for a whitespace-only input (caller rejects it)", () => { - expect(normalizeEmail(" ")).toBe(""); - }); - - it("leaves interior characters untouched (only edges are trimmed)", () => { - expect(normalizeEmail("a.b+tag@sub.example.com")).toBe("a.b+tag@sub.example.com"); - }); -}); - -describe("clientIp", () => { - const req = (headers: Record) => - new Request("https://auth/login", { headers }); - - it("prefers the edge-set CF-Connecting-IP when present", () => { - expect(clientIp(req({ "CF-Connecting-IP": "1.2.3.4", "X-Client-IP": "5.6.7.8" }))) - .toBe("1.2.3.4"); - }); - - it("falls back to the proxy-forwarded X-Client-IP on service-binding hops", () => { - expect(clientIp(req({ "X-Client-IP": "5.6.7.8" }))).toBe("5.6.7.8"); - }); - - it("returns null when neither header is present", () => { - expect(clientIp(req({}))).toBeNull(); - }); -}); diff --git a/packages/auth/src/lib.ts b/packages/auth/src/lib.ts deleted file mode 100644 index c9c91c5b..00000000 --- a/packages/auth/src/lib.ts +++ /dev/null @@ -1,94 +0,0 @@ -export interface Session { - userId: string; - email: string; - expiresAt: number; - isAdmin?: boolean; - forcePasswordChange?: true; - // Server-side session row id. Required for normal sessions; absent on - // the short-lived "force password change" token. - sid?: string; - // Force-change-token nonce. Set only on `forcePasswordChange: true` - // tokens; mirrored on `users.change_token_id`. Re-issuing the token - // overwrites the row, invalidating any prior unused token. - cti?: string; - // Resolved per-user plan, computed by resolvePersonalPlan() when the - // session is loaded. Optional so JWT-only consumers (no DB hit) and - // the api worker's filtered session don't need to populate them. - personalPlan?: "free" | "ink"; - personalPlanSince?: number | null; - personalPlanStatus?: string | null; - personalPlanCancelAt?: number | null; - personalPlanStyle?: string | null; - personalPresenceColor?: string | null; - personalCritSparkles?: boolean; - // User-picked prose fonts for reading vs editing modes. NULL means the - // frontend falls back to the default sans stack. Not gated on plan. - readingFont?: string | null; - editingFont?: string | null; - uiFont?: string | null; - // Per-user site theme. themeMode ∈ {dark,light,custom}; NULL = dark default. - // themeCustomColor is the #rrggbb base for 'custom'. Admin-gated (set via - // routes/update-theme.ts). Not gated on plan. - themeMode?: string | null; - themeCustomColor?: string | null; -} - -export const Errors = { - UNAUTHORIZED: { error: "Unauthorized", status: 401 }, - FORBIDDEN: { error: "Forbidden", status: 403 }, - NOT_FOUND: { error: "Not found", status: 404 }, - CONFLICT: { error: "Already exists", status: 409 }, - BAD_REQUEST: { error: "Bad request", status: 400 }, - INTERNAL: { error: "Internal server error", status: 500 }, - RATE_LIMITED: { error: "rate_limited", status: 429 }, -} as const; - -export function errorResponse(err: typeof Errors[keyof typeof Errors]): Response { - return Response.json({ ok: false, ...err }, { status: err.status }); -} - -export function okResponse(data: T, status = 200): Response { - return Response.json({ ok: true, data }, { status }); -} - -// Resolve the real client IP. CF-Connecting-IP is edge-set and unspoofable but -// survives only direct edge hits; service-binding hops (frontend → api → auth) -// drop it, so the proxies forward the edge-observed value as X-Client-IP -// (overwritten at every hop, never client-controlled). Returns null when -// neither is present (local dev without the header). -export function clientIp(request: Request): string | null { - return request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"); -} - -// True only for a SQLite/D1 UNIQUE-constraint violation. Apply paths that -// race the `users.email` UNIQUE index catch their UPDATE with this so a -// transient D1 failure surfaces as a 500 instead of masquerading as -// "email taken." -export function isUniqueConstraintError(err: unknown): boolean { - return err instanceof Error && err.message.includes("UNIQUE constraint failed"); -} - -// Shape of the Cloudflare ratelimit bindings (see Env in index.ts). -export interface RateLimiter { - limit(opts: { key: string }): Promise<{ success: boolean }>; -} - -// Per-user rate-limit guard for authenticated, proxied routes. These reach the -// auth worker via the API worker's service-binding proxy, which does not forward -// CF-Connecting-IP, so an IP key would collapse to "unknown" and bucket every -// caller together. We key on the authenticated userId instead. Returns a 429 -// Response to short-circuit on, or null to proceed. -export async function rateLimitUser(limiter: RateLimiter, key: string): Promise { - const { success } = await limiter.limit({ key }); - return success ? null : errorResponse(Errors.RATE_LIMITED); -} - -// Canonical email normalization for every auth entry point (register, login, -// resend-verification, webauthn). Trim surrounding whitespace - addresses can't -// contain spaces, so a stray leading/trailing space is always user error - then -// lowercase so case differences map to the same account. Must be applied -// identically on the write (register) and read (login/lookup) paths or a user -// could register one way and fail to authenticate the other. -export function normalizeEmail(email: string): string { - return email.trim().toLowerCase(); -} diff --git a/packages/auth/src/mfa-enrollment.test.ts b/packages/auth/src/mfa-enrollment.test.ts deleted file mode 100644 index 98af2e1d..00000000 --- a/packages/auth/src/mfa-enrollment.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("./password", () => ({ - verifyPassword: vi.fn(), -})); - -import { requireEnrollmentStepUp } from "./mfa"; -import { verifyPassword } from "./password"; -import type { Env } from "./index"; - -function makeEnv(opts?: { hasKey?: boolean; limitSuccess?: boolean }) { - const first = vi.fn(); - const prepare = vi.fn((sql: string) => ({ - bind: vi.fn(() => ({ - first: vi.fn(async () => { - if (sql.includes("FROM users")) { - return { password_hash: "stored-hash", totp_secret: null }; - } - if (sql.includes("webauthn_credentials")) { - return opts?.hasKey ? { id: "credential-1" } : null; - } - return first(); - }), - })), - })); - const limit = vi.fn(async () => ({ success: opts?.limitSuccess ?? true })); - const env = { - DB: { prepare }, - RATE_LIMITER_AUTH: { limit }, - } as unknown as Env; - return { env, prepare, limit }; -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyPassword).mockResolvedValue(true); -}); - -describe("requireEnrollmentStepUp", () => { - it("rejects first-factor enrollment when a bearer session has no password proof", async () => { - const { env, limit } = makeEnv(); - - const response = await requireEnrollmentStepUp(env, "user-1", {}); - - expect(response?.status).toBe(401); - expect(await response?.json()).toMatchObject({ error: "password_required" }); - expect(verifyPassword).not.toHaveBeenCalled(); - expect(limit).not.toHaveBeenCalled(); - }); - - it("accepts the current password for an account with no existing factor", async () => { - const { env, limit } = makeEnv(); - - expect(await requireEnrollmentStepUp(env, "user-1", { - currentPassword: "current-password", - })).toBeNull(); - expect(limit).toHaveBeenCalledWith({ key: "enroll-factor:user-1" }); - expect(verifyPassword).toHaveBeenCalledWith("current-password", "stored-hash"); - }); - - it("rate-limits password guesses before verifying them", async () => { - const { env } = makeEnv({ limitSuccess: false }); - - const response = await requireEnrollmentStepUp(env, "user-1", { - currentPassword: "guess", - }); - - expect(response?.status).toBe(429); - expect(verifyPassword).not.toHaveBeenCalled(); - }); - - it("rejects an incorrect current password", async () => { - vi.mocked(verifyPassword).mockResolvedValue(false); - const { env } = makeEnv(); - - const response = await requireEnrollmentStepUp(env, "user-1", { - currentPassword: "wrong", - }); - - expect(response?.status).toBe(401); - }); -}); diff --git a/packages/auth/src/mfa.test.ts b/packages/auth/src/mfa.test.ts deleted file mode 100644 index 1748ed46..00000000 --- a/packages/auth/src/mfa.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { describe, it, expect, vi } from "vitest"; -import { hashCode, validateAndConsumeBackupCode, verifyAndConsumeTotp } from "./mfa"; -import { base32Decode } from "./totp"; -import { toArrayBuffer } from "./crypto"; -import type { Env } from "./index"; - -const SECRET = "JBSWY3DPEHPK3PXP"; - -// Reimplements HOTP so tests can generate expected codes independently -// (same helper as totp.test.ts). -async function computeTOTP(secret: string, timeMs: number): Promise { - const secretBytes = base32Decode(secret); - const counter = Math.floor(timeMs / 1000 / 30); - const key = await crypto.subtle.importKey( - "raw", toArrayBuffer(secretBytes), - { name: "HMAC", hash: "SHA-1" }, - false, ["sign"], - ); - const counterBuffer = new ArrayBuffer(8); - new DataView(counterBuffer).setBigUint64(0, BigInt(counter), false); - const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBuffer)); - const offset = hmac[19] & 0x0f; - const code = ( - ((hmac[offset] & 0x7f) << 24) | - ((hmac[offset + 1] & 0xff) << 16) | - ((hmac[offset + 2] & 0xff) << 8) | - (hmac[offset + 3] & 0xff) - ) % 1_000_000; - return code.toString().padStart(6, "0"); -} - -function makeEnv(updateChanges: number) { - const run = vi.fn().mockResolvedValue({ meta: { changes: updateChanges } }); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Env, prepare, bind }; -} - -describe("verifyAndConsumeTotp", () => { - it("accepts a valid code when the step consume updates a row", async () => { - const { env, bind } = makeEnv(1); - const code = await computeTOTP(SECRET, Date.now()); - expect(await verifyAndConsumeTotp(env, "user-1", SECRET, code)).toBe(true); - // The consumed step must be bound for both the SET and the strictly-less - // guard, scoped to the user. - const expectedStep = Math.floor(Date.now() / 1000 / 30); - const [setStep, userId, guardStep] = bind.mock.calls[0]; - expect(userId).toBe("user-1"); - expect(setStep).toBe(guardStep); - // Allow the adjacent drift steps in case the clock ticked mid-test. - expect(Math.abs(setStep - expectedStep)).toBeLessThanOrEqual(1); - }); - - it("rejects a replayed code: valid code but the conditional update matches no row", async () => { - const { env } = makeEnv(0); - const code = await computeTOTP(SECRET, Date.now()); - expect(await verifyAndConsumeTotp(env, "user-1", SECRET, code)).toBe(false); - }); - - it("rejects an invalid code without touching the database", async () => { - const { env, prepare } = makeEnv(1); - expect(await verifyAndConsumeTotp(env, "user-1", SECRET, "abcdef")).toBe(false); - expect(prepare).not.toHaveBeenCalled(); - }); -}); - -describe("validateAndConsumeBackupCode", () => { - async function makeBackupCodeEnv(updateChanges: number) { - const code = "abcd-1234"; - const codeHash = await hashCode(code.toUpperCase()); - const all = vi.fn().mockResolvedValue({ - results: [{ id: "backup-1", code_hash: codeHash }], - }); - const selectBind = vi.fn().mockReturnValue({ all }); - const run = vi.fn().mockResolvedValue({ meta: { changes: updateChanges } }); - const updateBind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn() - .mockReturnValueOnce({ bind: selectBind }) - .mockReturnValueOnce({ bind: updateBind }); - return { - code, - env: { DB: { prepare } } as unknown as Env, - prepare, - selectBind, - updateBind, - }; - } - - it("accepts only the request whose conditional consume updates the code", async () => { - const { code, env, prepare, selectBind, updateBind } = await makeBackupCodeEnv(1); - - expect(await validateAndConsumeBackupCode(env, "user-1", code)).toBe(true); - expect(selectBind).toHaveBeenCalledWith("user-1"); - expect(updateBind).toHaveBeenCalledWith("backup-1", "user-1"); - expect(prepare).toHaveBeenLastCalledWith(expect.stringContaining("used_at IS NULL")); - }); - - it("rejects a matching code already consumed by a concurrent request", async () => { - const { code, env, prepare } = await makeBackupCodeEnv(0); - - expect(await validateAndConsumeBackupCode(env, "user-1", code)).toBe(false); - expect(prepare).toHaveBeenCalledTimes(2); - }); -}); diff --git a/packages/auth/src/mfa.ts b/packages/auth/src/mfa.ts deleted file mode 100644 index 8307541a..00000000 --- a/packages/auth/src/mfa.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { verifyWebauthnAssertion } from "./webauthn"; -import { matchTotpStep, verifyTOTP } from "./totp"; -import { errorResponse, Errors } from "./lib"; -import { verifyPassword } from "./password"; -import type { Env } from "./index"; - -export type MFAVerification = { - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; -}; - -export type EnrollmentVerification = MFAVerification & { - currentPassword?: string; -}; - -/** - * Protects enrollment of a new authenticator. - * - * Existing MFA is the preferred step-up. If the account has no factor yet, - * require the current password instead: possession of a bearer session alone - * must never be enough to add a passkey and turn a transient session theft - * into permanent passwordless access. - */ -export async function requireEnrollmentStepUp( - env: Env, - userId: string, - verification: EnrollmentVerification, -): Promise { - const user = await env.DB.prepare( - "SELECT password_hash, totp_secret FROM users WHERE id = ?", - ).bind(userId).first<{ password_hash: string; totp_secret: string | null }>(); - if (!user) return errorResponse(Errors.UNAUTHORIZED); - - const existingKey = await env.DB.prepare( - "SELECT id FROM webauthn_credentials WHERE user_id = ? LIMIT 1", - ).bind(userId).first<{ id: string }>(); - - if (user.totp_secret || existingKey) { - return requireMFA(env, userId, verification); - } - - if (!verification.currentPassword) { - return Response.json({ ok: false, error: "password_required" }, { status: 401 }); - } - - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: `enroll-factor:${userId}` }); - if (!success) return errorResponse(Errors.RATE_LIMITED); - - const valid = await verifyPassword(verification.currentPassword, user.password_hash); - if (!valid) return errorResponse(Errors.UNAUTHORIZED); - return null; -} - -/** - * Enforces MFA for a given user. - * - * - If the user has no MFA configured, returns null (allow through). - * - If the user has MFA and a valid verification is provided, returns null. - * - Otherwise returns an error Response. - * - * Priority: WebAuthn assertion (if provided) is accepted regardless of - * whether TOTP is also enabled. Falls back to TOTP if no assertion given. - * Backup codes are accepted in place of a TOTP code. - */ -export async function requireMFA( - env: Env, - userId: string, - verification: MFAVerification, -): Promise { - const user = await env.DB.prepare( - "SELECT totp_secret FROM users WHERE id = ?", - ).bind(userId).first<{ totp_secret: string | null }>(); - if (!user) return Response.json({ ok: false, error: "unauthorized" }, { status: 401 }); - - const hasTOTP = !!user.totp_secret; - const existingKey = await env.DB.prepare( - "SELECT id FROM webauthn_credentials WHERE user_id = ? LIMIT 1", - ).bind(userId).first<{ id: string }>(); - const hasWebauthn = !!existingKey; - - if (!hasTOTP && !hasWebauthn) return null; - - // Throttle real verification attempts per-user so a stolen/live session - // can't brute-force the 6-digit TOTP or a backup code to strip MFA. Keyed - // on userId rather than IP so the budget holds even against a distributed - // attacker rotating source addresses. Only counted when a code/assertion is - // actually supplied; the "mfa_required" prompt path below is a normal flow - // and not throttled. - const attempting = !!( - verification.totpCode || - verification.backupCode || - (verification.challengeId && verification.webauthnResponse) - ); - if (attempting) { - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: `mfa:${userId}` }); - if (!success) return errorResponse(Errors.RATE_LIMITED); - } - - if (verification.challengeId && verification.webauthnResponse) { - return verifyWebauthnAssertion( - env, - userId, - verification.challengeId, - verification.webauthnResponse as Record, - "mfa", - ); - } - - if (hasTOTP) { - if (verification.totpCode) { - // Plain verify, no step consume: these are authenticated re-confirmations - // (change password, disable TOTP, delete account), and a user legitimately - // confirms several of them within one 30s code window. Replay protection - // lives on the unauthenticated login path (verifyAndConsumeTotp), where a - // captured code is actually dangerous. Brute force is covered by the - // per-user throttle above. - const valid = await verifyTOTP(user.totp_secret!, verification.totpCode); - if (!valid) { - return Response.json({ ok: false, error: "invalid_totp" }, { status: 401 }); - } - return null; - } - if (verification.backupCode) { - const backupResult = await validateAndConsumeBackupCode(env, userId, verification.backupCode); - if (!backupResult) { - return Response.json({ ok: false, error: "invalid_backup_code" }, { status: 401 }); - } - return null; - } - return Response.json({ ok: false, error: "mfa_required" }, { status: 200 }); - } - - // Has WebAuthn only, no assertion provided - return Response.json({ ok: false, error: "mfa_required" }, { status: 200 }); -} - -// Verifies a TOTP code AND consumes its time step, so a captured code can't be -// replayed to LOG IN within its ±1-step validity window. The conditional -// UPDATE is the consume: it only succeeds for a step strictly later than the -// last accepted one, and concurrent requests race on the row so exactly one -// wins. Only the unauthenticated login path consumes - enroll and the -// authenticated requireMFA confirmations deliberately don't, so enabling TOTP -// and signing in (or confirming several settings actions) within one code -// window keeps working. -export async function verifyAndConsumeTotp( - env: Env, - userId: string, - secret: string, - code: string, -): Promise { - const step = await matchTotpStep(secret, code); - if (step === null) return false; - const result = await env.DB.prepare( - "UPDATE users SET totp_last_used_step = ? WHERE id = ? AND (totp_last_used_step IS NULL OR totp_last_used_step < ?)", - ).bind(step, userId, step).run(); - return (result.meta.changes ?? 0) === 1; -} - -export async function validateAndConsumeBackupCode(env: Env, userId: string, code: string): Promise { - const hash = await hashCode(code.toUpperCase()); - const rows = await env.DB.prepare( - "SELECT id, code_hash FROM backup_codes WHERE user_id = ? AND used_at IS NULL", - ).bind(userId).all<{ id: string; code_hash: string }>(); - - for (const row of rows.results) { - if (row.code_hash === hash) { - const result = await env.DB.prepare( - "UPDATE backup_codes SET used_at = datetime('now') WHERE id = ? AND user_id = ? AND used_at IS NULL", - ).bind(row.id, userId).run(); - // The matching row may have been consumed by a concurrent request after - // the SELECT above. Only the request whose conditional UPDATE changed the - // row gets to treat the one-time code as valid. - return (result.meta.changes ?? 0) === 1; - } - } - return false; -} - -export async function hashCode(code: string): Promise { - const buf = new TextEncoder().encode(code); - const digest = await crypto.subtle.digest("SHA-256", buf); - return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, "0")).join(""); -} diff --git a/packages/auth/src/password.test.ts b/packages/auth/src/password.test.ts deleted file mode 100644 index 2fc84bcd..00000000 --- a/packages/auth/src/password.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { hashPassword, verifyPassword, needsRehash, DUMMY_PASSWORD_HASH } from "./password"; - -describe("hashPassword", () => { - it("returns the versioned pbkdf2 format", async () => { - const result = await hashPassword("my-password"); - expect(result).toMatch(/^pbkdf2-1\$\d+\$[0-9a-f]+\$[0-9a-f]+$/); - }); - - it("encodes the iteration count in the hash", async () => { - const [, iter] = (await hashPassword("password")).split("$"); - expect(Number.parseInt(iter, 10)).toBeGreaterThanOrEqual(100_000); - }); - - it("produces a unique salt on each call", async () => { - const h1 = await hashPassword("same-password"); - const h2 = await hashPassword("same-password"); - expect(h1).not.toBe(h2); - }); -}); - -describe("verifyPassword", () => { - it("returns true for the correct password", async () => { - const hash = await hashPassword("correct-horse-battery-staple"); - expect(await verifyPassword("correct-horse-battery-staple", hash)).toBe(true); - }); - - it("returns false for the wrong password", async () => { - const hash = await hashPassword("correct-horse-battery-staple"); - expect(await verifyPassword("wrong-password", hash)).toBe(false); - }); - - it("returns false for an empty password against a real hash", async () => { - const hash = await hashPassword("secret"); - expect(await verifyPassword("", hash)).toBe(false); - }); - - it("verifies legacy : format with old iteration count", async () => { - // Built by deriving PBKDF2-HMAC-SHA256 at 100k iterations against a - // fixed salt; previously the only stored format. Must remain - // verifiable so existing accounts keep working until next login. - const enc = new TextEncoder(); - const salt = new Uint8Array(16).fill(0xab); - const base = await crypto.subtle.importKey( - "raw", enc.encode("legacy-pass"), "PBKDF2", false, ["deriveBits", "deriveKey"], - ); - const key = await crypto.subtle.deriveKey( - { name: "PBKDF2", salt: salt.buffer.slice(0), iterations: 100_000, hash: "SHA-256" }, - base, - { name: "HMAC", hash: "SHA-256", length: 256 }, - true, - ["sign"], - ); - const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key)); - const toHex = (b: Uint8Array) => Array.from(b).map(x => x.toString(16).padStart(2, "0")).join(""); - const stored = `${toHex(salt)}:${toHex(raw)}`; - expect(await verifyPassword("legacy-pass", stored)).toBe(true); - expect(await verifyPassword("wrong", stored)).toBe(false); - }); -}); - -describe("DUMMY_PASSWORD_HASH (login timing-oracle defence)", () => { - it("is in the current versioned format at the full iteration count", () => { - expect(DUMMY_PASSWORD_HASH).toMatch(/^pbkdf2-1\$\d+\$[0-9a-f]+\$[0-9a-f]+$/); - const [, iter] = DUMMY_PASSWORD_HASH.split("$"); - expect(Number.parseInt(iter, 10)).toBeGreaterThanOrEqual(100_000); - // No opportunistic rehash should ever be triggered by it. - expect(needsRehash(DUMMY_PASSWORD_HASH)).toBe(false); - }); - - it("runs a real derivation and never matches (returns false, does not throw)", async () => { - expect(await verifyPassword("anything", DUMMY_PASSWORD_HASH)).toBe(false); - expect(await verifyPassword("", DUMMY_PASSWORD_HASH)).toBe(false); - }); -}); - -describe("needsRehash", () => { - it("returns true for legacy : format", async () => { - expect(needsRehash("aabb:ccdd")).toBe(true); - }); - - it("returns false for a hash at the current iteration count", async () => { - const hash = await hashPassword("any"); - expect(needsRehash(hash)).toBe(false); - }); - - it("returns true for a hash at a lower iteration count", () => { - expect(needsRehash("pbkdf2-1$50000$aabb$ccdd")).toBe(true); - }); - - it("returns true for a malformed versioned hash", () => { - expect(needsRehash("pbkdf2-1$notanumber$aa$bb")).toBe(true); - }); -}); diff --git a/packages/auth/src/password.ts b/packages/auth/src/password.ts deleted file mode 100644 index 2b46bbcf..00000000 --- a/packages/auth/src/password.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { toArrayBuffer } from "./crypto"; - -// PBKDF2-HMAC-SHA256 via WebCrypto. OWASP 2023+ minimum is 600k iterations, -// but Cloudflare Workers' WebCrypto refuses PBKDF2 calls above 100,000 -// iterations ("NotSupportedError: iteration counts above 100000 are not -// supported"). Hashes written above the cap throw on verify and lock the -// user out, so we stay at 100k until either CF raises the cap or we move -// derivation to Node's crypto via the nodejs_compat path. -// Stored format is versioned so we can raise the cost ceiling later without -// invalidating existing hashes: -// pbkdf2-1$$$ -// Hashes written before this format (":") are still -// verifiable at the legacy iteration count and rewritten on next login. -const ITERATIONS = 100_000; -const LEGACY_ITERATIONS = 100_000; -const HASH = "SHA-256"; -const FORMAT_PREFIX = "pbkdf2-1$"; - -// A well-formed hash that no password will ever match. Used to equalise work -// on the "user not found" login path so PBKDF2 timing can't be used as a -// registration oracle (verifyPassword against this performs the same -// 100k-iteration derivation as a real user). The hash bytes are arbitrary. -export const DUMMY_PASSWORD_HASH = - `${FORMAT_PREFIX}${ITERATIONS}$00000000000000000000000000000000$` + - "0000000000000000000000000000000000000000000000000000000000000000"; - -export async function hashPassword(password: string): Promise { - const salt = crypto.getRandomValues(new Uint8Array(16)); - const hash = await derive(password, salt, ITERATIONS); - return `${FORMAT_PREFIX}${ITERATIONS}$${buf2hex(salt)}$${buf2hex(hash)}`; -} - -export async function verifyPassword(password: string, stored: string): Promise { - if (stored.startsWith(FORMAT_PREFIX)) { - const parts = stored.split("$"); - if (parts.length !== 4) return false; - const iter = Number.parseInt(parts[1], 10); - if (!Number.isFinite(iter) || iter < 1) return false; - const salt = hex2buf(parts[2]); - const hash = await derive(password, salt, iter); - return constantTimeEqualHex(buf2hex(hash), parts[3]); - } - const [saltHex, hashHex] = stored.split(":"); - if (!saltHex || !hashHex) return false; - const salt = hex2buf(saltHex); - const hash = await derive(password, salt, LEGACY_ITERATIONS); - return constantTimeEqualHex(buf2hex(hash), hashHex); -} - -// True if the stored hash should be re-derived at the current iteration cost. -// Call after a successful verifyPassword to opportunistically migrate users. -export function needsRehash(stored: string): boolean { - if (!stored.startsWith(FORMAT_PREFIX)) return true; - const parts = stored.split("$"); - if (parts.length !== 4) return true; - const iter = Number.parseInt(parts[1], 10); - return !Number.isFinite(iter) || iter < ITERATIONS; -} - -async function derive(password: string, salt: Uint8Array, iterations: number): Promise { - const base = await crypto.subtle.importKey( - "raw", toArrayBuffer(new TextEncoder().encode(password)), "PBKDF2", false, ["deriveBits", "deriveKey"], - ); - const key = await crypto.subtle.deriveKey( - { name: "PBKDF2", salt: toArrayBuffer(salt), iterations, hash: HASH }, - base, - { name: "HMAC", hash: HASH, length: 256 }, - true, - ["sign"], - ); - return crypto.subtle.exportKey("raw", key); -} - -function constantTimeEqualHex(a: string, b: string): boolean { - if (a.length !== b.length) return false; - let diff = 0; - for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); - return diff === 0; -} - -function buf2hex(buf: ArrayBuffer | Uint8Array): string { - return Array.from(buf instanceof Uint8Array ? buf : new Uint8Array(buf)) - .map(b => b.toString(16).padStart(2, "0")).join(""); -} - -function hex2buf(hex: string): Uint8Array { - return new Uint8Array(hex.match(/.{2}/g)!.map(b => parseInt(b, 16))); -} diff --git a/packages/auth/src/plan.test.ts b/packages/auth/src/plan.test.ts deleted file mode 100644 index e1f15843..00000000 --- a/packages/auth/src/plan.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { resolvePersonalPlan, type PlanRow } from "./plan"; - -const FREE: PlanRow = { - granted_plan: null, - granted_plan_expires_at: null, - granted_plan_started_at: null, - personal_plan: null, - personal_plan_status: null, - personal_plan_started_at: null, - personal_plan_cancel_at: null, - personal_plan_style: null, - personal_presence_color: null, - personal_crit_sparkles: null, -}; - -const NOW = 1_000_000; - -describe("resolvePersonalPlan", () => { - it("returns free when no plan info is set", () => { - const r = resolvePersonalPlan(FREE, NOW); - expect(r.plan).toBe("free"); - expect(r.via).toBe("free"); - expect(r.since).toBeNull(); - }); - - it("returns ink when paid plan is active", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "active", - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.via).toBe("paid"); - expect(r.since).toBe(500); - expect(r.status).toBe("active"); - }); - - it("keeps perks active during past_due grace period", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "past_due", - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.status).toBe("past_due"); - }); - - it("trialing counts as active", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "trialing", - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("ink"); - }); - - it("returns free when paid plan is canceled", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "canceled", - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("free"); - expect(r.via).toBe("free"); - }); - - it("returns free when paid plan is unpaid or incomplete_expired", () => { - for (const status of ["unpaid", "incomplete_expired", "incomplete"]) { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: status, - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("free"); - } - }); - - it("granted plan with NULL expiry beats no paid plan", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: null, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.via).toBe("granted"); - expect(r.status).toBe("granted"); - }); - - it("granted plan with future expiry beats no paid plan", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: NOW + 1000, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.via).toBe("granted"); - }); - - it("granted plan with past expiry falls back to paid", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: NOW - 1, - personal_plan: "ink", - personal_plan_status: "active", - personal_plan_started_at: 500, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.via).toBe("paid"); - }); - - it("granted plan with past expiry and no paid plan falls back to free", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: NOW - 1, - }, NOW); - expect(r.plan).toBe("free"); - }); - - it("granted plan beats paid plan even when both are active", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: null, - personal_plan: "ink", - personal_plan_status: "active", - personal_plan_started_at: 500, - }, NOW); - expect(r.via).toBe("granted"); - }); - - it("unknown plan strings normalize to free", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "mystery_tier", - personal_plan_status: "active", - }, NOW); - expect(r.plan).toBe("free"); - }); - - it("surfaces cancelAt for paid plans pending cancellation", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "active", - personal_plan_started_at: 100, - personal_plan_cancel_at: NOW + 86400_000, - }, NOW); - expect(r.plan).toBe("ink"); - expect(r.cancelAt).toBe(NOW + 86400_000); - }); - - it("granted plans never carry a cancelAt", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: null, - personal_plan_cancel_at: NOW + 86400_000, - }, NOW); - expect(r.cancelAt).toBeNull(); - }); - - it("granted plans surface granted_plan_started_at as since", () => { - const r = resolvePersonalPlan({ - ...FREE, - granted_plan: "ink", - granted_plan_expires_at: null, - granted_plan_started_at: 12345, - }, NOW); - expect(r.via).toBe("granted"); - expect(r.since).toBe(12345); - }); - - it("crit sparkles default to true for paid Ink users (NULL column)", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "active", - }, NOW); - expect(r.critSparkles).toBe(true); - }); - - it("crit sparkles respect explicit 0 (off) for Ink users", () => { - const r = resolvePersonalPlan({ - ...FREE, - personal_plan: "ink", - personal_plan_status: "active", - personal_crit_sparkles: 0, - }, NOW); - expect(r.critSparkles).toBe(false); - }); - - it("crit sparkles are always false for free users", () => { - const r = resolvePersonalPlan({ ...FREE, personal_crit_sparkles: 1 }, NOW); - expect(r.plan).toBe("free"); - expect(r.critSparkles).toBe(false); - }); -}); diff --git a/packages/auth/src/plan.ts b/packages/auth/src/plan.ts deleted file mode 100644 index 3d81f2d1..00000000 --- a/packages/auth/src/plan.ts +++ /dev/null @@ -1,115 +0,0 @@ -// Per-user plan resolution. Three sources of truth, in priority order: -// -// 1. granted_plan (set via wrangler one-liner for comps) - wins if it -// either has no expiry or hasn't expired yet -// 2. personal_plan (Stripe-managed) - active when status is one of -// active|trialing|past_due (past_due gets a grace period; the UI -// shows a banner but the perks stay on) -// 3. free -// -// Keep this a pure function so the api worker can import it via the -// same cross-package path it already uses for loadCurrentSession. - -export type PersonalPlan = "free" | "ink"; - -// Allowed ring style ids. Default ('shimmer') is what every supporter gets -// before customising; null on the row means "use the default". 'none' -// opts out of the animated ring entirely. Adding a new style: append the -// id here, add a CSS variant in ink-border.css, and add it to -// INK_PRESENCE_RING_STYLES below. -export const INK_RING_STYLES = ["shimmer", "aurora", "ember", "mono", "none"] as const; -export type InkRingStyle = typeof INK_RING_STYLES[number]; - -export function isInkRingStyle(value: unknown): value is InkRingStyle { - return typeof value === "string" && (INK_RING_STYLES as readonly string[]).includes(value); -} - -// Strict #rrggbb. We render the colour straight into a CSS box-shadow / -// caret-color, so we lock the input down to a known-safe shape. -const HEX_COLOR = /^#[0-9a-fA-F]{6}$/; -export function isInkPresenceColor(value: unknown): value is string { - return typeof value === "string" && HEX_COLOR.test(value); -} - -export type PlanRow = { - granted_plan: string | null; - granted_plan_expires_at: number | null; - granted_plan_started_at: number | null; - personal_plan: string | null; - personal_plan_status: string | null; - personal_plan_started_at: number | null; - personal_plan_cancel_at: number | null; - personal_plan_style: string | null; - personal_presence_color: string | null; - personal_crit_sparkles: number | null; -}; - -export type ResolvedPlan = { - plan: PersonalPlan; - via: "granted" | "paid" | "free"; - since: number | null; - status: string | null; - // When non-null, the active sub has been set to cancel and access - // ends at this Unix-ms timestamp. Stays in 'active' status until - // then; UI uses this to show "expires on X". - cancelAt: null | number; - // Cosmetic prefs. null on a free user (no Ink → no perks); for an Ink - // user, null means "use the default" (style: 'shimmer', presence colour: - // deterministic from userColor()). Persisted values that fail validation - // are normalised to null here so callers don't have to re-validate. - style: InkRingStyle | null; - presenceColor: string | null; - // Whether to render the dice crit sparkle burst for this user. Ink-only - // perk: false for free users. For Ink users, NULL on the row means "use - // the default" which is true; an explicit 0 turns it off. - critSparkles: boolean; -}; - -const ACTIVE_STATUSES = new Set(["active", "trialing", "past_due"]); - -function asPlan(value: string | null): PersonalPlan { - return value === "ink" ? "ink" : "free"; -} - -function readStyle(row: PlanRow): InkRingStyle | null { - return isInkRingStyle(row.personal_plan_style) ? row.personal_plan_style : null; -} - -function readPresenceColor(row: PlanRow): string | null { - return isInkPresenceColor(row.personal_presence_color) ? row.personal_presence_color : null; -} - -// NULL → default (on); explicit 0 → off; anything else → on. -function readCritSparkles(row: PlanRow): boolean { - return row.personal_crit_sparkles !== 0; -} - -export function resolvePersonalPlan(row: PlanRow, now: number = Date.now()): ResolvedPlan { - if (row.granted_plan && (row.granted_plan_expires_at === null || row.granted_plan_expires_at > now)) { - return { - plan: asPlan(row.granted_plan), - via: "granted", - since: row.granted_plan_started_at, - status: "granted", - cancelAt: null, - style: readStyle(row), - presenceColor: readPresenceColor(row), - critSparkles: readCritSparkles(row), - }; - } - - if (row.personal_plan && row.personal_plan_status && ACTIVE_STATUSES.has(row.personal_plan_status)) { - return { - plan: asPlan(row.personal_plan), - via: "paid", - since: row.personal_plan_started_at, - status: row.personal_plan_status, - cancelAt: row.personal_plan_cancel_at, - style: readStyle(row), - presenceColor: readPresenceColor(row), - critSparkles: readCritSparkles(row), - }; - } - - return { plan: "free", via: "free", since: null, status: null, cancelAt: null, style: null, presenceColor: null, critSparkles: false }; -} diff --git a/packages/auth/src/routes/admin-handoff-exchange.test.ts b/packages/auth/src/routes/admin-handoff-exchange.test.ts deleted file mode 100644 index 67bbd0f8..00000000 --- a/packages/auth/src/routes/admin-handoff-exchange.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -vi.mock("../admin-handoff", () => ({ - normalizeAdminCallbackUrl: vi.fn(), - writeAdminHandoffAudit: vi.fn(), -})); -vi.mock("../sessions", async (orig) => ({ - ...(await orig()), - createSession: vi.fn(), -})); -vi.mock("../jwt", () => ({ signJwt: vi.fn(async () => "signed-jwt") })); - -import { handleAdminHandoffExchange } from "./admin-handoff-exchange"; -import { normalizeAdminCallbackUrl, writeAdminHandoffAudit } from "../admin-handoff"; -import { createSession, ADMIN_SESSION_TTL_MS, SESSION_TTL_MS } from "../sessions"; -import { signJwt } from "../jwt"; -import type { Env } from "../index"; - -function makeDb() { - const firstQueue: unknown[] = []; - const runResults: Array<{ meta: { changes: number } }> = []; - const stmt = { - bind: (..._args: unknown[]) => stmt, - first: async () => firstQueue.shift() ?? null, - run: async () => runResults.shift() ?? { meta: { changes: 1 } }, - }; - return { firstQueue, runResults, prepare: vi.fn(() => stmt) }; -} - -function makeRequest(body: unknown, headers: Record = {}) { - return new Request("http://auth/admin/handoff/exchange", { - method: "POST", - headers: { "Content-Type": "application/json", ...headers }, - body: JSON.stringify(body), - }); -} - -const ADMIN_USER = { id: "u-1", email: "a@x.com", moderation: 0, force_password_change: 0, is_admin: 1 }; - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(normalizeAdminCallbackUrl).mockReturnValue("https://admin.cubityfir.st/auth/callback"); - vi.mocked(createSession).mockResolvedValue("sid-1"); -}); - -describe("handleAdminHandoffExchange", () => { - it("mints a SHORT-TTL admin session (hours, not the standard 7 days) and audits it (AB-M7/AB-M2)", async () => { - const db = makeDb(); - db.firstQueue.push({ id: "code-1", user_id: "u-1" }); // handoff row - db.firstQueue.push(ADMIN_USER); - const env = { DB: db, JWT_SECRET: "s" } as unknown as Env; - - const before = Date.now(); - const res = await handleAdminHandoffExchange( - makeRequest({ code: "code-1", callbackUrl: "https://admin.cubityfir.st/auth/callback" }), - env, - ); - expect(res.status).toBe(200); - - // TTL sanity: admin sessions must be far shorter than the standard week. - expect(ADMIN_SESSION_TTL_MS).toBeLessThan(SESSION_TTL_MS); - expect(ADMIN_SESSION_TTL_MS).toBeLessThanOrEqual(24 * 60 * 60 * 1000); - - const expiresAt = vi.mocked(createSession).mock.calls[0][3]; - expect(expiresAt).toBeGreaterThanOrEqual(before + ADMIN_SESSION_TTL_MS - 1000); - expect(expiresAt).toBeLessThanOrEqual(Date.now() + ADMIN_SESSION_TTL_MS + 1000); - - const jwtPayload = vi.mocked(signJwt).mock.calls[0][0] as { expiresAt: number }; - expect(jwtPayload.expiresAt).toBe(expiresAt); - - expect(writeAdminHandoffAudit).toHaveBeenCalledWith( - env, - { userId: "u-1", email: "a@x.com" }, - "admin.handoff.exchange", - expect.objectContaining({ sessionId: "sid-1", expiresAt }), - ); - }); - - it("refuses a non-admin user with 403 and no session/audit", async () => { - const db = makeDb(); - db.firstQueue.push({ id: "code-1", user_id: "u-1" }); - db.firstQueue.push({ ...ADMIN_USER, is_admin: 0 }); - const env = { DB: db, JWT_SECRET: "s" } as unknown as Env; - - const res = await handleAdminHandoffExchange( - makeRequest({ code: "code-1", callbackUrl: "https://admin.cubityfir.st/auth/callback" }), - env, - ); - expect(res.status).toBe(403); - expect(createSession).not.toHaveBeenCalled(); - expect(writeAdminHandoffAudit).not.toHaveBeenCalled(); - }); - - it("refuses an already-consumed code (atomic compare-and-set lost)", async () => { - const db = makeDb(); - db.firstQueue.push({ id: "code-1", user_id: "u-1" }); - db.runResults.push({ meta: { changes: 0 } }); // consume raced and lost - const env = { DB: db, JWT_SECRET: "s" } as unknown as Env; - - const res = await handleAdminHandoffExchange( - makeRequest({ code: "code-1", callbackUrl: "https://admin.cubityfir.st/auth/callback" }), - env, - ); - expect(res.status).toBe(401); - expect(createSession).not.toHaveBeenCalled(); - expect(writeAdminHandoffAudit).not.toHaveBeenCalled(); - }); - - it("rejects an unapproved callbackUrl before touching the database", async () => { - vi.mocked(normalizeAdminCallbackUrl).mockReturnValue(null); - const db = makeDb(); - const env = { DB: db, JWT_SECRET: "s" } as unknown as Env; - const res = await handleAdminHandoffExchange( - makeRequest({ code: "code-1", callbackUrl: "https://evil.com/auth/callback" }), - env, - ); - expect(res.status).toBe(400); - expect(db.prepare).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/auth/src/routes/admin-handoff-exchange.ts b/packages/auth/src/routes/admin-handoff-exchange.ts deleted file mode 100644 index c813e439..00000000 --- a/packages/auth/src/routes/admin-handoff-exchange.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { normalizeAdminCallbackUrl, writeAdminHandoffAudit } from "../admin-handoff"; -import { signJwt } from "../jwt"; -import { errorResponse, Errors, okResponse } from "../lib"; -import { checkModeration } from "./login"; -import { createSession, ADMIN_SESSION_TTL_MS } from "../sessions"; -import type { Env } from "../index"; - -export async function handleAdminHandoffExchange(request: Request, env: Env): Promise { - const body = await request.json<{ code?: string; callbackUrl?: string }>(); - if (!body.code || !body.callbackUrl) return errorResponse(Errors.BAD_REQUEST); - - const normalizedCallbackUrl = normalizeAdminCallbackUrl(body.callbackUrl, env); - if (!normalizedCallbackUrl) return errorResponse(Errors.BAD_REQUEST); - - const now = Date.now(); - const handoff = await env.DB.prepare( - "SELECT id, user_id FROM admin_handoffs WHERE id = ? AND return_to = ? AND consumed_at IS NULL AND expires_at > ?", - ).bind(body.code, normalizedCallbackUrl, now).first<{ id: string; user_id: string }>(); - - if (!handoff) return errorResponse(Errors.UNAUTHORIZED); - - const consumeResult = await env.DB.prepare( - "UPDATE admin_handoffs SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL", - ).bind(now, handoff.id).run(); - - if ((consumeResult.meta.changes ?? 0) !== 1) { - return errorResponse(Errors.UNAUTHORIZED); - } - - const user = await env.DB.prepare( - "SELECT id, email, moderation, force_password_change, is_admin FROM users WHERE id = ?", - ).bind(handoff.user_id).first<{ - id: string; - email: string; - moderation: number; - force_password_change: number; - is_admin: number; - }>(); - - if (!user) return errorResponse(Errors.UNAUTHORIZED); - - if (!user.is_admin) { - return Response.json({ ok: false, error: "not_admin" }, { status: 403 }); - } - - const moderationError = checkModeration(user.moderation); - if (moderationError) return moderationError; - - if (user.force_password_change) { - return errorResponse(Errors.UNAUTHORIZED); - } - - // Deliberately short-lived (hours, not the standard 7 days): this token - // carries full admin privilege. createSession stamps ip/device from the - // X-Client-IP / User-Agent the admin worker forwards across the - // service-binding hop. - const expiresAt = Date.now() + ADMIN_SESSION_TTL_MS; - const sid = await createSession(env, user.id, request, expiresAt); - const token = await signJwt( - { - userId: user.id, - email: user.email, - expiresAt, - isAdmin: true, - sid, - }, - env.JWT_SECRET, - ); - - // Record who obtained admin access, from where, and until when. - await writeAdminHandoffAudit(env, { userId: user.id, email: user.email }, "admin.handoff.exchange", { - sessionId: sid, - expiresAt, - ip: request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"), - }); - - return okResponse({ token }); -} diff --git a/packages/auth/src/routes/admin-handoff-start.ts b/packages/auth/src/routes/admin-handoff-start.ts deleted file mode 100644 index ce9449ca..00000000 --- a/packages/auth/src/routes/admin-handoff-start.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { normalizeAdminCallbackUrl, writeAdminHandoffAudit } from "../admin-handoff"; -import { errorResponse, Errors, okResponse } from "../lib"; -import type { Env } from "../index"; - -const HANDOFF_TTL_MS = 5 * 60 * 1000; - -export async function handleAdminHandoffStart(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - if (!session.isAdmin) { - return Response.json({ ok: false, error: "not_admin" }, { status: 403 }); - } - - const body = await request.json<{ returnTo?: string }>(); - if (!body.returnTo) return errorResponse(Errors.BAD_REQUEST); - - const normalizedReturnTo = normalizeAdminCallbackUrl(body.returnTo, env); - if (!normalizedReturnTo) return errorResponse(Errors.BAD_REQUEST); - - const now = Date.now(); - const expiresAt = now + HANDOFF_TTL_MS; - const code = crypto.randomUUID(); - - // Opportunistic GC of expired handoffs, batched with the INSERT. Consumed - // rows are left to expire (<= HANDOFF_TTL_MS): the exchange only accepts - // `consumed_at IS NULL`, so they're inert, and an `OR consumed_at IS NOT - // NULL` arm would turn this index range delete into a full table scan. - await env.DB.batch([ - env.DB.prepare("DELETE FROM admin_handoffs WHERE expires_at <= ?").bind(now), - env.DB.prepare( - "INSERT INTO admin_handoffs (id, user_id, return_to, created_at, expires_at, consumed_at) VALUES (?, ?, ?, ?, ?, NULL)", - ).bind(code, session.userId, normalizedReturnTo, now, expiresAt), - ]); - - // Record that an admin handoff was initiated (the exchange writes its own - // row when the code is redeemed - a start with no matching exchange is - // itself a useful signal). - await writeAdminHandoffAudit(env, { userId: session.userId, email: session.email }, "admin.handoff.start", { - returnTo: normalizedReturnTo, - }); - - const redirectUrl = new URL(normalizedReturnTo); - redirectUrl.searchParams.set("code", code); - - return okResponse({ - redirectTo: redirectUrl.toString(), - expiresAt, - }); -} diff --git a/packages/auth/src/routes/billing.test.ts b/packages/auth/src/routes/billing.test.ts deleted file mode 100644 index 5c85a37b..00000000 --- a/packages/auth/src/routes/billing.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleBillingCheckout, handleBillingPortal } from "./billing"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -vi.mock("../stripe-client", () => ({ - getStripe: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { getStripe } from "../stripe-client"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(userRow: Record | null) { - return { - DB: { - prepare: vi.fn().mockReturnValue({ - bind: vi.fn().mockReturnValue({ - first: vi.fn().mockResolvedValue(userRow), - }), - }), - }, - STRIPE_SECRET_KEY: "sk_test_xxx", - STRIPE_INK_PRICE_ID: "price_xxx", - APP_ORIGIN: "https://docs.example.com", - } as unknown as Parameters[1]; -} - -function makeRequest(path: string, authHeader = "Bearer t") { - return new Request(`http://localhost${path}`, { - method: "POST", - headers: { Authorization: authHeader }, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleBillingCheckout", () => { - it("returns 401 when session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleBillingCheckout(makeRequest("/billing/checkout"), makeEnv(null)); - expect(res.status).toBe(401); - }); - - it("returns 404 when user row missing", async () => { - const res = await handleBillingCheckout(makeRequest("/billing/checkout"), makeEnv(null)); - expect(res.status).toBe(404); - }); - - it("creates checkout with customer_email when no stripe_customer_id", async () => { - const create = vi.fn().mockResolvedValue({ url: "https://checkout.stripe.com/abc" }); - vi.mocked(getStripe).mockReturnValue({ - checkout: { sessions: { create } }, - } as unknown as ReturnType); - - const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: null }); - const res = await handleBillingCheckout(makeRequest("/billing/checkout"), env); - expect(res.status).toBe(200); - const body = await res.json<{ data: { url: string } }>(); - expect(body.data.url).toBe("https://checkout.stripe.com/abc"); - - expect(create).toHaveBeenCalledOnce(); - const args = create.mock.calls[0][0]; - expect(args.mode).toBe("subscription"); - expect(args.customer_email).toBe("u@example.com"); - expect(args.customer).toBeUndefined(); - expect(args.client_reference_id).toBe("user-1"); - expect(args.line_items).toEqual([{ price: "price_xxx", quantity: 1 }]); - }); - - it("reuses existing stripe_customer_id when present", async () => { - const create = vi.fn().mockResolvedValue({ url: "https://checkout.stripe.com/def" }); - vi.mocked(getStripe).mockReturnValue({ - checkout: { sessions: { create } }, - } as unknown as ReturnType); - - const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: "cus_existing" }); - await handleBillingCheckout(makeRequest("/billing/checkout"), env); - - const args = create.mock.calls[0][0]; - expect(args.customer).toBe("cus_existing"); - expect(args.customer_email).toBeUndefined(); - }); - - it("returns 500 when Stripe doesn't return a url", async () => { - const create = vi.fn().mockResolvedValue({ url: null }); - vi.mocked(getStripe).mockReturnValue({ - checkout: { sessions: { create } }, - } as unknown as ReturnType); - - const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: null }); - const res = await handleBillingCheckout(makeRequest("/billing/checkout"), env); - expect(res.status).toBe(500); - }); -}); - -describe("handleBillingPortal", () => { - it("returns 400 when user has no stripe_customer_id", async () => { - const env = makeEnv({ stripe_customer_id: null }); - const res = await handleBillingPortal(makeRequest("/billing/portal"), env); - expect(res.status).toBe(400); - }); - - it("creates a portal session and returns the url", async () => { - const create = vi.fn().mockResolvedValue({ url: "https://billing.stripe.com/portal/xyz" }); - vi.mocked(getStripe).mockReturnValue({ - billingPortal: { sessions: { create } }, - } as unknown as ReturnType); - - const env = makeEnv({ stripe_customer_id: "cus_1" }); - const res = await handleBillingPortal(makeRequest("/billing/portal"), env); - expect(res.status).toBe(200); - const body = await res.json<{ data: { url: string } }>(); - expect(body.data.url).toBe("https://billing.stripe.com/portal/xyz"); - - const args = create.mock.calls[0][0]; - expect(args.customer).toBe("cus_1"); - expect(args.return_url).toBe("https://docs.example.com/settings#billing"); - }); -}); diff --git a/packages/auth/src/routes/billing.ts b/packages/auth/src/routes/billing.ts deleted file mode 100644 index 8c87b188..00000000 --- a/packages/auth/src/routes/billing.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { getStripe } from "../stripe-client"; -import type { Env } from "../index"; - -interface UserBillingRow { - email: string; - name: string; - stripe_customer_id: string | null; -} - -// POST /billing/checkout -// Creates a Stripe Checkout Session for the Annex Ink subscription and -// returns the redirect URL. The browser navigates to it; on success -// Stripe sends us back to /settings#billing and the webhook fires -// checkout.session.completed which links the customer + sub to the user. -export async function handleBillingCheckout(request: Request, env: Env): Promise { - if (!env.STRIPE_SECRET_KEY || !env.STRIPE_INK_PRICE_ID) { - return errorResponse(Errors.INTERNAL); - } - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare( - `SELECT u.email, u.name, b.stripe_customer_id - FROM users u - LEFT JOIN user_billing b ON b.user_id = u.id - WHERE u.id = ?`, - ).bind(session.userId).first(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - const stripe = getStripe(env.STRIPE_SECRET_KEY); - const returnUrl = `${env.APP_ORIGIN}/settings#billing`; - - // Reuse an existing customer when we have one (resub case); otherwise - // let Checkout create a new customer and we'll link it on webhook. - const customerArgs = user.stripe_customer_id - ? { customer: user.stripe_customer_id } - : { customer_email: user.email }; - - const checkout = await stripe.checkout.sessions.create({ - mode: "subscription", - line_items: [{ price: env.STRIPE_INK_PRICE_ID, quantity: 1 }], - client_reference_id: session.userId, - // Stripe doesn't guarantee event ordering. Stamping userId into the - // subscription metadata means every customer.subscription.* event - // can resolve back to a user even if checkout.session.completed - // hasn't been processed yet. - subscription_data: { metadata: { userId: session.userId } }, - success_url: returnUrl, - cancel_url: returnUrl, - allow_promotion_codes: true, - ...customerArgs, - }); - - if (!checkout.url) return errorResponse(Errors.INTERNAL); - return okResponse({ url: checkout.url }); -} - -// POST /billing/portal -// Creates a Stripe Customer Portal session so the user can manage their -// subscription (update card, cancel, view invoices). Requires that we've -// already linked a stripe_customer_id - i.e. they've completed at least -// one Checkout. Free users get a 400. -export async function handleBillingPortal(request: Request, env: Env): Promise { - if (!env.STRIPE_SECRET_KEY) return errorResponse(Errors.INTERNAL); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare( - "SELECT stripe_customer_id FROM user_billing WHERE user_id = ?", - ).bind(session.userId).first<{ stripe_customer_id: string | null }>(); - if (!user?.stripe_customer_id) return errorResponse(Errors.BAD_REQUEST); - - const stripe = getStripe(env.STRIPE_SECRET_KEY); - const portal = await stripe.billingPortal.sessions.create({ - customer: user.stripe_customer_id, - return_url: `${env.APP_ORIGIN}/settings#billing`, - }); - - return okResponse({ url: portal.url }); -} diff --git a/packages/auth/src/routes/change-email-cancel.test.ts b/packages/auth/src/routes/change-email-cancel.test.ts deleted file mode 100644 index a832fecf..00000000 --- a/packages/auth/src/routes/change-email-cancel.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../../api/src/test/sqliteD1"; -import { handleChangeEmailCancel } from "./change-email-cancel"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -// Real SQLite with every auth migration applied: which tokens the DELETE -// matches is the whole behaviour. -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../migrations", import.meta.url)); - -const mockSession = { userId: "user-1", email: "old@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const user = sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, 'U', 'x', datetime('now'))"); - user.run("user-1", "old@example.com"); - user.run("user-2", "b@example.com"); - const token = sqlite.prepare("INSERT INTO email_verification_tokens (id, user_id, created_at, expires_at, email) VALUES (?, ?, 0, 9999999999999, ?)"); - token.run("change-1", "user-1", "new@example.com"); - token.run("change-2", "user-1", "newer@example.com"); - token.run("signup", "user-1", null); // pending signup verification - token.run("other-change", "user-2", "x@example.com"); - const remaining = () => - sqlite.prepare("SELECT id FROM email_verification_tokens ORDER BY id").all().map(r => r.id); - return { env: { DB: db } as unknown as Parameters[1], remaining }; -} - -function req() { - return new Request("http://localhost/change-email/cancel", { method: "POST", body: "{}" }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleChangeEmailCancel", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env, remaining } = makeEnv(); - const res = await handleChangeEmailCancel(req(), env); - expect(res.status).toBe(401); - expect(remaining()).toEqual(["change-1", "change-2", "other-change", "signup"]); - }); - - it("deletes only the caller's pending change tokens (idempotent)", async () => { - const { env, remaining } = makeEnv(); - expect((await handleChangeEmailCancel(req(), env)).status).toBe(200); - // Scoped to change tokens only - a pending signup verification survives. - expect(remaining()).toEqual(["other-change", "signup"]); - expect((await handleChangeEmailCancel(req(), env)).status).toBe(200); - expect(remaining()).toEqual(["other-change", "signup"]); - }); -}); diff --git a/packages/auth/src/routes/change-email-cancel.ts b/packages/auth/src/routes/change-email-cancel.ts deleted file mode 100644 index 7f906640..00000000 --- a/packages/auth/src/routes/change-email-cancel.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse } from "../lib"; -import type { Env } from "../index"; - -// Drop the caller's pending email change (all unconsumed change tokens). -// Idempotent - cancelling with nothing pending is a no-op success. -export async function handleChangeEmailCancel(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - await env.DB.prepare( - "DELETE FROM email_verification_tokens WHERE user_id = ? AND email IS NOT NULL", - ).bind(session.userId).run(); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/change-email-resend.test.ts b/packages/auth/src/routes/change-email-resend.test.ts deleted file mode 100644 index 85240769..00000000 --- a/packages/auth/src/routes/change-email-resend.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleChangeEmailResend } from "./change-email-resend"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../verification", () => ({ - createVerificationToken: vi.fn(), -})); -vi.mock("../email", () => ({ - sendEmailChangeConfirmEmail: vi.fn().mockResolvedValue(true), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { createVerificationToken } from "../verification"; -import { sendEmailChangeConfirmEmail } from "../email"; - -const mockSession = { userId: "user-1", email: "old@example.com", expiresAt: Date.now() + 3600_000 }; - -// A pending token old enough to clear the 5-minute resend floor. -const OLD_ENOUGH = () => Date.now() - 10 * 60 * 1000; - -function makeEnv(pending: { email: string; created_at: number } | null, opts: { rateLimited?: boolean } = {}) { - const sqls: string[] = []; - const bindCalls: unknown[][] = []; - const prepare = vi.fn((sql: string) => { - sqls.push(sql); - return { - bind: vi.fn((...args: unknown[]) => { - bindCalls.push(args); - return { - first: vi.fn().mockResolvedValue(pending), - run: vi.fn().mockResolvedValue({}), - }; - }), - }; - }); - const limit = vi.fn().mockResolvedValue({ success: !opts.rateLimited }); - const env = { - DB: { prepare }, - APP_ORIGIN: "http://localhost:5173", - RATE_LIMITER_EMAIL_VERIFY: { limit }, - } as unknown as Parameters[1]; - return { env, sqls, bindCalls, limit }; -} - -function req() { - return new Request("http://localhost/change-email/resend", { method: "POST", body: "{}" }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(createVerificationToken).mockResolvedValue("tok-456"); - vi.mocked(sendEmailChangeConfirmEmail).mockResolvedValue(true); -}); - -describe("handleChangeEmailResend", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleChangeEmailResend(req(), makeEnv({ email: "new@example.com", created_at: OLD_ENOUGH() }).env); - expect(res.status).toBe(401); - }); - - it("throttles per-user via the email-verify limiter", async () => { - const { env, limit } = makeEnv({ email: "new@example.com", created_at: OLD_ENOUGH() }, { rateLimited: true }); - const res = await handleChangeEmailResend(req(), env); - expect(res.status).toBe(429); - expect(limit).toHaveBeenCalledWith({ key: "change-email:user-1" }); - expect(sendEmailChangeConfirmEmail).not.toHaveBeenCalled(); - }); - - it("returns 400 no_pending_change when nothing is pending", async () => { - const res = await handleChangeEmailResend(req(), makeEnv(null).env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("no_pending_change"); - expect(createVerificationToken).not.toHaveBeenCalled(); - }); - - it("refuses with 429 too_soon inside the 5-minute resend floor", async () => { - const { env } = makeEnv({ email: "new@example.com", created_at: Date.now() - 60_000 }); - const res = await handleChangeEmailResend(req(), env); - expect(res.status).toBe(429); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("too_soon"); - expect(sendEmailChangeConfirmEmail).not.toHaveBeenCalled(); - }); - - it("re-issues the token with a fresh TTL and resends the confirm email", async () => { - const { env, sqls, bindCalls } = makeEnv({ email: "new@example.com", created_at: OLD_ENOUGH() }); - const res = await handleChangeEmailResend(req(), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { sent: boolean; pendingEmail: string } }; - expect(json.data).toEqual({ sent: true, pendingEmail: "new@example.com" }); - - // Lookup and delete are both scoped to the caller's change tokens. - const selIdx = sqls.findIndex(s => s.startsWith("SELECT email")); - expect(sqls[selIdx]).toContain("email IS NOT NULL"); - expect(bindCalls[selIdx][0]).toBe("user-1"); - const delIdx = sqls.findIndex(s => s.startsWith("DELETE")); - expect(sqls[delIdx]).toContain("email IS NOT NULL"); - expect(bindCalls[delIdx]).toEqual(["user-1"]); - - expect(createVerificationToken).toHaveBeenCalledWith(env, "user-1", "new@example.com"); - expect(sendEmailChangeConfirmEmail).toHaveBeenCalledWith( - env, - "new@example.com", - "http://localhost:5173/verify-email?token=tok-456", - ); - }); - - it("surfaces a failed send as 500 send_failed", async () => { - vi.mocked(sendEmailChangeConfirmEmail).mockResolvedValueOnce(false); - const { env } = makeEnv({ email: "new@example.com", created_at: OLD_ENOUGH() }); - const res = await handleChangeEmailResend(req(), env); - expect(res.status).toBe(500); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("send_failed"); - }); -}); diff --git a/packages/auth/src/routes/change-email-resend.ts b/packages/auth/src/routes/change-email-resend.ts deleted file mode 100644 index 95203e57..00000000 --- a/packages/auth/src/routes/change-email-resend.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { createVerificationToken } from "../verification"; -import { sendEmailChangeConfirmEmail } from "../email"; -import type { Env } from "../index"; - -// Floor between resends. The pending address is caller-chosen with no -// ownership proof, so resend is an unsolicited-email lever pointed at an -// arbitrary mailbox - the per-IP/per-user limiters cap bursts, this caps the -// sustained rate per pending change. -const RESEND_MIN_AGE_MS = 5 * 60 * 1000; - -// Re-send the confirm link for the caller's own pending email change with a -// fresh 24h TTL. No anti-enumeration dance needed - authenticated and scoped -// to the caller. -export async function handleChangeEmailResend(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // Per-user throttle on top of the router's per-IP one (see change-email.ts). - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: `change-email:${session.userId}` }); - if (!success) return errorResponse(Errors.RATE_LIMITED); - - const pending = await env.DB.prepare( - "SELECT email, created_at FROM email_verification_tokens WHERE user_id = ? AND email IS NOT NULL AND consumed_at IS NULL AND expires_at > ? ORDER BY created_at DESC LIMIT 1", - ).bind(session.userId, Date.now()).first<{ email: string; created_at: number }>(); - - if (!pending) { - return Response.json({ ok: false, error: "no_pending_change" }, { status: 400 }); - } - - if (Date.now() - pending.created_at < RESEND_MIN_AGE_MS) { - return Response.json({ ok: false, error: "too_soon" }, { status: 429 }); - } - - await env.DB.prepare( - "DELETE FROM email_verification_tokens WHERE user_id = ? AND email IS NOT NULL", - ).bind(session.userId).run(); - - const token = await createVerificationToken(env, session.userId, pending.email); - const verifyUrl = `${env.APP_ORIGIN}/verify-email?token=${token}`; - const sent = await sendEmailChangeConfirmEmail(env, pending.email, verifyUrl); - if (!sent) { - // Keep the rotated token so the pending state survives; the min-age gate - // above naturally spaces out the retry. - return Response.json({ ok: false, error: "send_failed" }, { status: 500 }); - } - - return okResponse({ sent: true, pendingEmail: pending.email }); -} diff --git a/packages/auth/src/routes/change-email.test.ts b/packages/auth/src/routes/change-email.test.ts deleted file mode 100644 index 51870a8a..00000000 --- a/packages/auth/src/routes/change-email.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleChangeEmail } from "./change-email"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), -})); -vi.mock("../verification", () => ({ - createVerificationToken: vi.fn(), - isEmailVerificationEnabled: vi.fn(), -})); -vi.mock("../email", () => ({ - sendEmailChangeConfirmEmail: vi.fn().mockResolvedValue(true), - sendEmailChangedNotice: vi.fn().mockResolvedValue(true), -})); -vi.mock("../stripe-client", () => ({ - syncStripeCustomerEmail: vi.fn().mockResolvedValue(undefined), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA } from "../mfa"; -import { createVerificationToken, isEmailVerificationEnabled } from "../verification"; -import { sendEmailChangeConfirmEmail, sendEmailChangedNotice } from "../email"; -import { syncStripeCustomerEmail } from "../stripe-client"; - -const mockSession = { userId: "user-1", email: "old@example.com", expiresAt: Date.now() + 3600_000 }; - -// Queue-based D1 mock: first() results shift in handler call-order -// (1: SELECT email+password_hash, 2: SELECT id uniqueness pre-check). -// SQL strings + bind args are captured so WHERE scoping can be asserted. -function makeEnv(opts: { - user?: { email: string; password_hash: string } | null; - taken?: boolean; - flagOn?: boolean; - updateError?: Error; - rateLimited?: boolean; -}) { - const firstResults: unknown[] = [opts.user ?? null, opts.taken ? { id: "other-user" } : null]; - const sqls: string[] = []; - const bindCalls: unknown[][] = []; - const run = vi.fn((): Promise => Promise.resolve({})); - const prepare = vi.fn((sql: string) => { - sqls.push(sql); - return { - bind: vi.fn((...args: unknown[]) => { - bindCalls.push(args); - return { - first: vi.fn(() => Promise.resolve(firstResults.shift() ?? null)), - run: sql.startsWith("UPDATE users") && opts.updateError - ? vi.fn(() => Promise.reject(opts.updateError)) - : run, - }; - }), - }; - }); - const limit = vi.fn().mockResolvedValue({ success: !opts.rateLimited }); - const env = { - DB: { prepare }, - APP_ORIGIN: "http://localhost:5173", - RATE_LIMITER_EMAIL_VERIFY: { limit }, - } as unknown as Parameters[1]; - // Flag reads go through isEmailVerificationEnabled (mocked above) - the - // helper itself is covered in verification.test.ts, incl. the dev bypass. - vi.mocked(isEmailVerificationEnabled).mockResolvedValue(opts.flagOn ?? false); - return { env, prepare, sqls, bindCalls, run, limit }; -} - -function makeRequest(body: Record) { - return new Request("http://localhost/change-email", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -let userHash: string; - -beforeEach(async () => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue(null); - vi.mocked(createVerificationToken).mockResolvedValue("tok-123"); - if (!userHash) { - const { hashPassword } = await import("../password"); - userHash = await hashPassword("current-password"); - } -}); - -function userRow() { - return { email: "old@example.com", password_hash: userHash }; -} - -describe("handleChangeEmail", () => { - it("returns 400 when newEmail is missing", async () => { - const res = await handleChangeEmail(makeRequest({ currentPassword: "x" }), makeEnv({}).env); - expect(res.status).toBe(400); - }); - - it("returns 400 when currentPassword is missing", async () => { - const res = await handleChangeEmail(makeRequest({ newEmail: "new@example.com" }), makeEnv({}).env); - expect(res.status).toBe(400); - }); - - it("returns 400 for a malformed address", async () => { - const res = await handleChangeEmail( - makeRequest({ newEmail: "not-an-email", currentPassword: "current-password" }), - makeEnv({ user: userRow() }).env, - ); - expect(res.status).toBe(400); - }); - - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - makeEnv({}).env, - ); - expect(res.status).toBe(401); - }); - - it("returns 400 same_email when the new address equals the current one (case-insensitively)", async () => { - const res = await handleChangeEmail( - makeRequest({ newEmail: " OLD@example.com ", currentPassword: "current-password" }), - makeEnv({ user: userRow() }).env, - ); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("same_email"); - }); - - it("returns 401 when the current password is wrong", async () => { - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "wrong-password" }), - makeEnv({ user: userRow() }).env, - ); - expect(res.status).toBe(401); - expect(requireMFA).not.toHaveBeenCalled(); - }); - - it("returns the MFA error response when MFA fails", async () => { - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 200 }), - ); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - makeEnv({ user: userRow() }).env, - ); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("mfa_required"); - }); - - it("throttles per-user via the email-verify limiter", async () => { - const { env, limit } = makeEnv({ user: userRow(), rateLimited: true }); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(429); - expect(limit).toHaveBeenCalledWith({ key: "change-email:user-1" }); - }); - - it("returns 409 when the address belongs to another account", async () => { - const { env, run } = makeEnv({ user: userRow(), taken: true }); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(409); - // No mutation happened. - expect(run).not.toHaveBeenCalled(); - }); - - describe("flag OFF (immediate apply)", () => { - it("normalizes, updates the row unverified, notifies the old address, and syncs Stripe", async () => { - const { env, sqls, bindCalls } = makeEnv({ user: userRow(), flagOn: false }); - const res = await handleChangeEmail( - makeRequest({ newEmail: " New@Example.COM ", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { applied: boolean; email: string } }; - expect(json.data).toEqual({ applied: true, email: "new@example.com" }); - - // Every outstanding token (pending changes AND unconsumed signup links) - // is invalidated first, so a stale signup link cannot verify the new address. - const delIdx = sqls.findIndex(s => s.includes("DELETE FROM email_verification_tokens")); - expect(delIdx).toBeGreaterThanOrEqual(0); - expect(sqls[delIdx]).toBe("DELETE FROM email_verification_tokens WHERE user_id = ?"); - expect(bindCalls[delIdx]).toEqual(["user-1"]); - - const updIdx = sqls.findIndex(s => s.startsWith("UPDATE users SET email = ?")); - expect(updIdx).toBeGreaterThanOrEqual(0); - expect(sqls[updIdx]).toContain("email_verified = 0"); - expect(bindCalls[updIdx]).toEqual(["new@example.com", "user-1"]); - - expect(sendEmailChangedNotice).toHaveBeenCalledWith(env, "old@example.com", "new@example.com"); - expect(syncStripeCustomerEmail).toHaveBeenCalledWith(env, "user-1", "new@example.com"); - expect(createVerificationToken).not.toHaveBeenCalled(); - expect(sendEmailChangeConfirmEmail).not.toHaveBeenCalled(); - }); - - it("returns 409 on a UNIQUE-constraint race past the pre-check", async () => { - const { env } = makeEnv({ - user: userRow(), - flagOn: false, - updateError: new Error("UNIQUE constraint failed: users.email"), - }); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(409); - expect(sendEmailChangedNotice).not.toHaveBeenCalled(); - }); - - it("rethrows a non-UNIQUE update failure instead of reporting 409", async () => { - const { env } = makeEnv({ - user: userRow(), - flagOn: false, - updateError: new Error("D1_ERROR: network timeout"), - }); - await expect( - handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ), - ).rejects.toThrow("network timeout"); - expect(sendEmailChangedNotice).not.toHaveBeenCalled(); - }); - }); - - describe("flag ON (confirm-first)", () => { - it("leaves users untouched and sends a confirm link to the NEW address", async () => { - const { env, sqls, bindCalls } = makeEnv({ user: userRow(), flagOn: true }); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { applied: boolean; pendingEmail: string } }; - expect(json.data).toEqual({ applied: false, pendingEmail: "new@example.com" }); - - expect(sqls.some(s => s.startsWith("UPDATE users"))).toBe(false); - // Earlier pending changes are still invalidated. - const delIdx = sqls.findIndex(s => s.includes("DELETE FROM email_verification_tokens")); - expect(delIdx).toBeGreaterThanOrEqual(0); - expect(bindCalls[delIdx]).toEqual(["user-1"]); - - expect(createVerificationToken).toHaveBeenCalledWith(env, "user-1", "new@example.com"); - expect(sendEmailChangeConfirmEmail).toHaveBeenCalledWith( - env, - "new@example.com", - "http://localhost:5173/verify-email?token=tok-123", - ); - expect(sendEmailChangedNotice).not.toHaveBeenCalled(); - expect(syncStripeCustomerEmail).not.toHaveBeenCalled(); - }); - - it("surfaces a failed confirm send and drops the orphaned token", async () => { - vi.mocked(sendEmailChangeConfirmEmail).mockResolvedValueOnce(false); - const { env, sqls, bindCalls } = makeEnv({ user: userRow(), flagOn: true }); - const res = await handleChangeEmail( - makeRequest({ newEmail: "new@example.com", currentPassword: "current-password" }), - env, - ); - expect(res.status).toBe(500); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("send_failed"); - // The just-created token is cleaned up so no phantom pending state remains. - const delByIdIdx = sqls.findIndex(s => s === "DELETE FROM email_verification_tokens WHERE id = ?"); - expect(delByIdIdx).toBeGreaterThanOrEqual(0); - expect(bindCalls[delByIdIdx]).toEqual(["tok-123"]); - }); - }); -}); diff --git a/packages/auth/src/routes/change-email.ts b/packages/auth/src/routes/change-email.ts deleted file mode 100644 index aa06dac6..00000000 --- a/packages/auth/src/routes/change-email.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors, normalizeEmail, isUniqueConstraintError } from "../lib"; -import { verifyPassword } from "../password"; -import { requireMFA } from "../mfa"; -import { createVerificationToken, isEmailVerificationEnabled } from "../verification"; -import { sendEmailChangeConfirmEmail, sendEmailChangedNotice } from "../email"; -import { syncStripeCustomerEmail } from "../stripe-client"; -import type { Env } from "../index"; - -// Change the account email. Gated like change-password: current password + -// MFA when enrolled. Behavior depends on the `email-verification` flag: -// - flag OFF: apply immediately with email_verified = 0 (mirrors signup). -// - flag ON: confirm-first - users.email is untouched until the link sent to -// the NEW address is clicked (unverified users are blocked at login while -// the flag is on, so an immediate change with a typo'd address would lock -// the user out). -export async function handleChangeEmail(request: Request, env: Env): Promise { - const body = await request.json<{ - newEmail?: string; - currentPassword?: string; - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - - if (!body.newEmail || typeof body.newEmail !== "string" || !body.currentPassword) { - return errorResponse(Errors.BAD_REQUEST); - } - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // Per-user throttle on top of the router's per-IP one: the pending address - // is caller-chosen with no ownership proof, so an IP-rotating attacker must - // not be able to fan unsolicited confirm emails at a victim address (and - // this also caps per-account password-guess attempts on this route). - const { success } = await env.RATE_LIMITER_EMAIL_VERIFY.limit({ key: `change-email:${session.userId}` }); - if (!success) return errorResponse(Errors.RATE_LIMITED); - - const email = normalizeEmail(body.newEmail); - if (!email || !email.includes("@")) return errorResponse(Errors.BAD_REQUEST); - - const user = await env.DB.prepare( - "SELECT email, password_hash FROM users WHERE id = ?", - ).bind(session.userId).first<{ email: string; password_hash: string }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - if (email === user.email) { - return Response.json({ ok: false, error: "same_email" }, { status: 400 }); - } - - const valid = await verifyPassword(body.currentPassword, user.password_hash); - if (!valid) return errorResponse(Errors.UNAUTHORIZED); - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - const taken = await env.DB.prepare( - "SELECT id FROM users WHERE email = ?", - ).bind(email).first<{ id: string }>(); - if (taken) return errorResponse(Errors.CONFLICT); - - // Invalidate every outstanding link: an earlier pending change so a stale - // confirm link can't apply an old address later (matters especially across - // flag flips), AND unconsumed signup-verify links - those mark whatever - // users.email is at click time as verified, so one minted for the old - // address would otherwise "verify" the new, never-proven one. - await env.DB.prepare( - "DELETE FROM email_verification_tokens WHERE user_id = ?", - ).bind(session.userId).run(); - - const requireVerification = await isEmailVerificationEnabled(env, session.userId); - - if (!requireVerification) { - try { - await env.DB.prepare( - "UPDATE users SET email = ?, email_verified = 0, email_verified_at = NULL WHERE id = ?", - ).bind(email, session.userId).run(); - } catch (err) { - // UNIQUE constraint race past the pre-check above; anything else is a - // real failure and must not masquerade as "email taken." - if (isUniqueConstraintError(err)) return errorResponse(Errors.CONFLICT); - throw err; - } - await sendEmailChangedNotice(env, user.email, email); - await syncStripeCustomerEmail(env, session.userId, email); - return okResponse({ applied: true, email }); - } - - const token = await createVerificationToken(env, session.userId, email); - const verifyUrl = `${env.APP_ORIGIN}/verify-email?token=${token}`; - const sent = await sendEmailChangeConfirmEmail(env, email, verifyUrl); - if (!sent) { - // The confirm email IS the mechanism in this mode - a swallowed send - // failure would leave a phantom pending change the user waits on forever. - await env.DB.prepare("DELETE FROM email_verification_tokens WHERE id = ?").bind(token).run(); - return Response.json({ ok: false, error: "send_failed" }, { status: 500 }); - } - return okResponse({ applied: false, pendingEmail: email }); -} diff --git a/packages/auth/src/routes/change-password.test.ts b/packages/auth/src/routes/change-password.test.ts deleted file mode 100644 index fdb4fe8e..00000000 --- a/packages/auth/src/routes/change-password.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleChangePassword } from "./change-password"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA } from "../mfa"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(passwordHash?: string, rateLimitSuccess = true) { - return { - DB: { - prepare: vi.fn().mockReturnValue({ - bind: vi.fn().mockReturnValue({ - first: vi.fn().mockResolvedValue(passwordHash ? { password_hash: passwordHash } : null), - run: vi.fn().mockResolvedValue(undefined), - }), - }), - }, - RATE_LIMITER_AUTH: { - limit: vi.fn().mockResolvedValue({ success: rateLimitSuccess }), - }, - } as unknown as Parameters[1]; -} - -function makeRequest(body: Record, authHeader?: string) { - return new Request("http://localhost/change-password", { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(authHeader ? { Authorization: authHeader } : {}), - }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireMFA).mockResolvedValue(null); -}); - -describe("handleChangePassword", () => { - it("returns 400 when currentPassword is missing", async () => { - const res = await handleChangePassword(makeRequest({ newPassword: "NewP@ssw0rd99" }), makeEnv()); - expect(res.status).toBe(400); - }); - - it("returns 400 when newPassword is missing", async () => { - const res = await handleChangePassword(makeRequest({ currentPassword: "old-pass" }), makeEnv()); - expect(res.status).toBe(400); - }); - - it("returns 401 when session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleChangePassword( - makeRequest({ currentPassword: "old", newPassword: "NewP@ssw0rd99" }), - makeEnv(), - ); - expect(res.status).toBe(401); - }); - - it("returns 400 with password_too_weak when new password is weak", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - const res = await handleChangePassword( - makeRequest({ currentPassword: "old-pass", newPassword: "weak" }), - makeEnv(), - ); - expect(res.status).toBe(400); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("password_too_weak"); - }); - - it("returns 401 when current password is wrong", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - - // hash of "correct-password" - const { hashPassword } = await import("../password"); - const hash = await hashPassword("correct-password"); - - const res = await handleChangePassword( - makeRequest({ currentPassword: "wrong-password", newPassword: "NewP@ssw0rd99!" }), - makeEnv(hash), - ); - expect(res.status).toBe(401); - }); - - it("returns 200 and updates password on success", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - - const { hashPassword } = await import("../password"); - const hash = await hashPassword("current-password"); - - const env = makeEnv(hash); - const res = await handleChangePassword( - makeRequest({ currentPassword: "current-password", newPassword: "NewP@ssw0rd99!" }), - env, - ); - expect(res.status).toBe(200); - const body = await res.json<{ ok: boolean }>(); - expect(body.ok).toBe(true); - // Verify the DB update ran - expect(env.DB.prepare).toHaveBeenCalledWith("UPDATE users SET password_hash = ? WHERE id = ?"); - }); - - it("returns 429 when the per-user rate limit is exceeded", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - const res = await handleChangePassword( - makeRequest({ currentPassword: "current-password", newPassword: "NewP@ssw0rd99!" }), - makeEnv("unused-hash", false), - ); - expect(res.status).toBe(429); - }); - - it("returns the MFA error response when MFA check fails", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 200 }), - ); - - const { hashPassword } = await import("../password"); - const hash = await hashPassword("current-password"); - - const res = await handleChangePassword( - makeRequest({ currentPassword: "current-password", newPassword: "NewP@ssw0rd99!" }), - makeEnv(hash), - ); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("mfa_required"); - }); -}); diff --git a/packages/auth/src/routes/change-password.ts b/packages/auth/src/routes/change-password.ts deleted file mode 100644 index 865c0c3b..00000000 --- a/packages/auth/src/routes/change-password.ts +++ /dev/null @@ -1,63 +0,0 @@ -import zxcvbn from "zxcvbn"; -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors, rateLimitUser } from "../lib"; -import { verifyPassword, hashPassword } from "../password"; -import { requireMFA } from "../mfa"; -import { revokeAllSessions } from "../sessions"; -import type { Env } from "../index"; - -export async function handleChangePassword(request: Request, env: Env): Promise { - const body = await request.json<{ - currentPassword: string; - newPassword: string; - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - - if (!body.currentPassword || !body.newPassword) { - return errorResponse(Errors.BAD_REQUEST); - } - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // The currentPassword verify below is an unauthenticated-grade guess oracle - // for anyone holding a live session; throttle it per-user (the proxy strips - // IP, so key on userId). - const limited = await rateLimitUser(env.RATE_LIMITER_AUTH, `change-pw:${session.userId}`); - if (limited) return limited; - - if (zxcvbn(body.newPassword).score < 3) { - return Response.json({ ok: false, error: "password_too_weak" }, { status: 400 }); - } - - const user = await env.DB.prepare( - "SELECT password_hash FROM users WHERE id = ?", - ).bind(session.userId).first<{ password_hash: string }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - const valid = await verifyPassword(body.currentPassword, user.password_hash); - if (!valid) return errorResponse(Errors.UNAUTHORIZED); - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - const newHash = await hashPassword(body.newPassword); - await env.DB.prepare("UPDATE users SET password_hash = ? WHERE id = ?") - .bind(newHash, session.userId) - .run(); - - // Kill every other device's session - anyone with a stolen JWT loses - // access on their next request. Current session stays alive so the user - // doesn't get bounced out of the page they just changed the password on. - await revokeAllSessions(env, session.userId, session.sid); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/delete-account.test.ts b/packages/auth/src/routes/delete-account.test.ts deleted file mode 100644 index 02c7d9be..00000000 --- a/packages/auth/src/routes/delete-account.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleDeleteAccount } from "./delete-account"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), -})); -vi.mock("../stripe-client", () => ({ - getStripe: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA } from "../mfa"; -import { getStripe } from "../stripe-client"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(opts: { - passwordHash?: string; - rateLimitSuccess?: boolean; - stripeKey?: string; - billingRow?: { stripe_customer_id: string | null } | null; -} = {}) { - const run = vi.fn().mockResolvedValue({}); - const batch = vi.fn(async (stmts: unknown[]) => stmts.map(() => ({ results: [], meta: {} }))); - const passwordFirst = vi.fn().mockResolvedValue( - opts.passwordHash ? { password_hash: opts.passwordHash } : null, - ); - const billingFirst = vi.fn().mockResolvedValue(opts.billingRow ?? null); - const prepare = vi.fn((sql: string) => ({ - bind: vi.fn().mockReturnValue({ - first: sql.includes("FROM users") ? passwordFirst : billingFirst, - run, - }), - })); - - return { - DB: { prepare, batch }, - RATE_LIMITER_AUTH: { - limit: vi.fn().mockResolvedValue({ success: opts.rateLimitSuccess ?? true }), - }, - STRIPE_SECRET_KEY: opts.stripeKey, - } as unknown as Parameters[1]; -} - -function makeRequest(body: Record) { - return new Request("http://localhost/delete-account", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer t" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue(null); -}); - -describe("handleDeleteAccount", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleDeleteAccount(makeRequest({ currentPassword: "pw" }), makeEnv()); - expect(res.status).toBe(401); - }); - - it("returns 400 when currentPassword is missing (no re-auth)", async () => { - const res = await handleDeleteAccount(makeRequest({}), makeEnv({ passwordHash: "hash" })); - expect(res.status).toBe(400); - }); - - it("returns 429 when the per-user rate limit is exceeded", async () => { - const res = await handleDeleteAccount( - makeRequest({ currentPassword: "pw" }), - makeEnv({ passwordHash: "hash", rateLimitSuccess: false }), - ); - expect(res.status).toBe(429); - }); - - it("returns 401 when the current password is wrong", async () => { - const { hashPassword } = await import("../password"); - const hash = await hashPassword("correct-password"); - const res = await handleDeleteAccount( - makeRequest({ currentPassword: "wrong-password" }), - makeEnv({ passwordHash: hash }), - ); - expect(res.status).toBe(401); - }); - - it("deletes the account on correct password + passing MFA", async () => { - const { hashPassword } = await import("../password"); - const hash = await hashPassword("correct-password"); - const env = makeEnv({ passwordHash: hash }); - const res = await handleDeleteAccount( - makeRequest({ currentPassword: "correct-password" }), - env, - ); - expect(res.status).toBe(200); - expect(env.DB.prepare).toHaveBeenCalledWith("DELETE FROM users WHERE id = ?"); - // email_verification_tokens has no FK cascade - its rows (incl. a pending - // change-email address) are removed in the same batch as the user row. - expect(env.DB.prepare).toHaveBeenCalledWith("DELETE FROM email_verification_tokens WHERE user_id = ?"); - expect(env.DB.batch).toHaveBeenCalledTimes(1); - expect(vi.mocked(env.DB.batch).mock.calls[0][0]).toHaveLength(2); - }); - - it("does not delete when MFA fails", async () => { - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 200 }), - ); - const { hashPassword } = await import("../password"); - const hash = await hashPassword("correct-password"); - const env = makeEnv({ passwordHash: hash }); - await handleDeleteAccount(makeRequest({ currentPassword: "correct-password" }), env); - expect(env.DB.prepare).not.toHaveBeenCalledWith("DELETE FROM users WHERE id = ?"); - expect(env.DB.batch).not.toHaveBeenCalled(); - }); - - it("deletes the Stripe customer before deleting the account", async () => { - const { hashPassword } = await import("../password"); - const del = vi.fn().mockResolvedValue({}); - vi.mocked(getStripe).mockReturnValue({ customers: { del } } as never); - const env = makeEnv({ - passwordHash: await hashPassword("correct-password"), - stripeKey: "sk_test", - billingRow: { stripe_customer_id: "cus_123" }, - }); - - const res = await handleDeleteAccount(makeRequest({ currentPassword: "correct-password" }), env); - - expect(res.status).toBe(200); - expect(del).toHaveBeenCalledWith("cus_123"); - expect(env.DB.prepare).toHaveBeenCalledWith("DELETE FROM users WHERE id = ?"); - }); - - it("still deletes the account if Stripe customer deletion fails", async () => { - const { hashPassword } = await import("../password"); - const del = vi.fn().mockRejectedValue(new Error("stripe down")); - vi.mocked(getStripe).mockReturnValue({ customers: { del } } as never); - const env = makeEnv({ - passwordHash: await hashPassword("correct-password"), - stripeKey: "sk_test", - billingRow: { stripe_customer_id: "cus_123" }, - }); - - const res = await handleDeleteAccount(makeRequest({ currentPassword: "correct-password" }), env); - - expect(res.status).toBe(200); - expect(env.DB.prepare).toHaveBeenCalledWith("DELETE FROM users WHERE id = ?"); - }); -}); diff --git a/packages/auth/src/routes/delete-account.ts b/packages/auth/src/routes/delete-account.ts deleted file mode 100644 index 4a674ec8..00000000 --- a/packages/auth/src/routes/delete-account.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors, rateLimitUser } from "../lib"; -import { verifyPassword } from "../password"; -import { requireMFA } from "../mfa"; -import { getStripe } from "../stripe-client"; -import type { Env } from "../index"; - -export async function handleDeleteAccount(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ - currentPassword?: string; - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - - // Step-up re-auth for an irreversible, cascading delete. requireMFA below is a - // no-op for accounts without TOTP/WebAuthn, so without this gate a single - // stolen session could destroy an MFA-less account. Mirror change-password and - // demand the current password regardless of MFA state. - if (!body.currentPassword) return errorResponse(Errors.BAD_REQUEST); - - const limited = await rateLimitUser(env.RATE_LIMITER_AUTH, `delete-account:${session.userId}`); - if (limited) return limited; - - const user = await env.DB.prepare( - "SELECT password_hash FROM users WHERE id = ?", - ).bind(session.userId).first<{ password_hash: string }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - const valid = await verifyPassword(body.currentPassword, user.password_hash); - if (!valid) return errorResponse(Errors.UNAUTHORIZED); - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - // If the user has a Stripe customer, delete it before removing their - // row. Deleting a customer auto-cancels every active subscription on - // it, so this single call handles both the cancel and the GDPR-ish - // cleanup of customer-side personal data (email, payment methods). - // We swallow Stripe failures rather than block account deletion - - // worst case is an orphan customer in Stripe that the user can't - // reach. If STRIPE_SECRET_KEY isn't set we skip the call entirely - // (e.g. in environments where billing isn't configured). - if (env.STRIPE_SECRET_KEY) { - const billingRow = await env.DB.prepare( - "SELECT stripe_customer_id FROM user_billing WHERE user_id = ?", - ).bind(session.userId).first<{ stripe_customer_id: string | null }>(); - - if (billingRow?.stripe_customer_id) { - try { - const stripe = getStripe(env.STRIPE_SECRET_KEY); - await stripe.customers.del(billingRow.stripe_customer_id); - } catch (err) { - console.error("Stripe customer delete during account deletion failed:", err); - } - } - } - - // email_verification_tokens has no FK to users, so it doesn't cascade - - // delete the rows explicitly (they can hold a pending change-email address) - // in the same transaction as the user row. - await env.DB.batch([ - env.DB.prepare("DELETE FROM email_verification_tokens WHERE user_id = ?").bind(session.userId), - env.DB.prepare("DELETE FROM users WHERE id = ?").bind(session.userId), - ]); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/dev-quick-login.ts b/packages/auth/src/routes/dev-quick-login.ts deleted file mode 100644 index db6d0409..00000000 --- a/packages/auth/src/routes/dev-quick-login.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { okResponse, errorResponse, Errors } from "../lib"; -import { signJwt } from "../jwt"; -import { createSession, SESSION_TTL_MS } from "../sessions"; -import type { Env } from "../index"; - -type Variant = "standard-free" | "standard-ink" | "admin-free" | "admin-ink"; - -export async function handleDevQuickLogin(request: Request, env: Env): Promise { - // This route mints a fully-valid (optionally admin) session with NO - // credentials. DEV_QUICK_LOGIN is the primary gate, but also hard-require a - // localhost deployment so a misconfigured flag in production can never - // expose credential-free admin minting (defence in depth). - const isLocalDeploy = /\blocalhost\b|127\.0\.0\.1/.test(env.APP_ORIGIN ?? ""); - if (env.DEV_QUICK_LOGIN !== "true" || !isLocalDeploy) { - return errorResponse(Errors.NOT_FOUND); - } - - const body = await request.json<{ variant: Variant }>(); - const isAdmin = body.variant === "admin-free" || body.variant === "admin-ink"; - const hasInk = body.variant === "standard-ink" || body.variant === "admin-ink"; - - const id = crypto.randomUUID(); - const email = `dev-${id.slice(0, 8)}@localhost`; - const name = `${isAdmin ? "Dev Admin" : "Dev User"}${hasInk ? " (Ink)" : ""}`; - const now = new Date().toISOString(); - - await env.DB.prepare( - "INSERT INTO users (id, email, name, password_hash, created_at, email_verified, is_admin) VALUES (?, ?, ?, '', ?, 1, ?)", - ).bind(id, email, name, now, isAdmin ? 1 : 0).run(); - - if (hasInk) { - await env.DB.prepare( - "INSERT INTO user_billing (user_id, granted_plan, granted_plan_reason, granted_plan_started_at) VALUES (?, 'ink', 'dev', ?)", - ).bind(id, Date.now()).run(); - } - - const expiresAt = Date.now() + SESSION_TTL_MS; - const sid = await createSession(env, id, request, expiresAt); - const token = await signJwt( - { userId: id, email, expiresAt, isAdmin, sid }, - env.JWT_SECRET, - ); - - return okResponse({ token }); -} diff --git a/packages/auth/src/routes/force-change-password.test.ts b/packages/auth/src/routes/force-change-password.test.ts deleted file mode 100644 index fafde8a1..00000000 --- a/packages/auth/src/routes/force-change-password.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleForceChangePassword } from "./force-change-password"; - -vi.mock("zxcvbn", () => ({ default: vi.fn(() => ({ score: 4 })) })); -vi.mock("../password", () => ({ hashPassword: vi.fn(async () => "new-hash") })); -vi.mock("../jwt", () => ({ verifyJwt: vi.fn(), signJwt: vi.fn(async () => "signed.jwt") })); -vi.mock("../sessions", () => ({ - createSession: vi.fn(async () => "sess-new"), - revokeAllSessions: vi.fn(async () => undefined), - SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, -})); - -import zxcvbn from "zxcvbn"; -import { verifyJwt } from "../jwt"; -import { revokeAllSessions } from "../sessions"; -import { hashPassword } from "../password"; - -const userRow = { id: "user-1", email: "test@example.com", name: "Test", created_at: "2026-01-01", is_admin: 0, moderation: 0 }; - -function makeEnv(opts?: { user?: typeof userRow | null; changes?: number }) { - const first = vi.fn().mockResolvedValue(opts?.user === undefined ? userRow : opts.user); - const run = vi.fn().mockResolvedValue({ meta: { changes: opts?.changes ?? 1 } }); - const bindCalls: unknown[][] = []; - const bind = vi.fn((...a: unknown[]) => { - bindCalls.push(a); - return { first, run }; - }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare }, JWT_SECRET: "secret" } as unknown as Parameters[1], prepare, bind, run, bindCalls }; -} - -function req(body: unknown) { - return new Request("http://localhost/force-change-password", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyJwt).mockResolvedValue({ userId: "user-1", forcePasswordChange: true, cti: "nonce-1" } as never); - vi.mocked(zxcvbn).mockReturnValue({ score: 4 } as never); -}); - -describe("handleForceChangePassword", () => { - it("rejects a body missing fields", async () => { - const { env } = makeEnv(); - const res = await handleForceChangePassword(req({ changeToken: "t" }), env); - expect(res.status).toBe(400); - }); - - it("rejects a token that isn't a force-change token", async () => { - vi.mocked(verifyJwt).mockResolvedValue({ userId: "user-1" } as never); - const { env } = makeEnv(); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "p" }), env); - expect(res.status).toBe(401); - }); - - it("rejects a weak new password", async () => { - vi.mocked(zxcvbn).mockReturnValue({ score: 1 } as never); - const { env } = makeEnv(); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "weak" }), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("password_too_weak"); - }); - - it("returns 404 when no matching flagged user exists", async () => { - const { env } = makeEnv({ user: null }); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "Str0ng!Pass" }), env); - expect(res.status).toBe(404); - }); - - it("rejects a disabled account before consuming the change token", async () => { - const { env, run } = makeEnv({ user: { ...userRow, moderation: -1 } }); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "Str0ng!Pass" }), env); - expect(res.status).toBe(403); - expect((await res.json<{ error: string }>()).error).toBe("account_disabled"); - expect(run).not.toHaveBeenCalled(); - }); - - it("returns 401 when the atomic consume changes 0 rows (token reused)", async () => { - const { env } = makeEnv({ changes: 0 }); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "Str0ng!Pass" }), env); - expect(res.status).toBe(401); - }); - - it("rotates the password, kills all sessions, and issues a fresh token", async () => { - const { env, prepare, bindCalls } = makeEnv(); - const res = await handleForceChangePassword(req({ changeToken: "t", newPassword: "Str0ng!Pass" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { token: string; user: { id: string } } }; - expect(json.data.token).toBe("signed.jwt"); - expect(json.data.user.id).toBe("user-1"); - expect(revokeAllSessions).toHaveBeenCalledWith(env, "user-1"); - - // The consume-UPDATE must write the new hash AND keep the single-use - // change_token_id guard. (An UPDATE that omits either fails here.) - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("password_hash = ?")); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("change_token_id = ?")); - // The UPDATE is the only 3-arg bind: (newHash, user.id, cti). - const updateBind = bindCalls.find((a) => a.length === 3); - expect(updateBind).toEqual(["new-hash", "user-1", "nonce-1"]); - // The hashed value written is derived from the submitted new password. - expect(hashPassword).toHaveBeenCalledWith("Str0ng!Pass"); - }); -}); diff --git a/packages/auth/src/routes/force-change-password.ts b/packages/auth/src/routes/force-change-password.ts deleted file mode 100644 index 42f8b839..00000000 --- a/packages/auth/src/routes/force-change-password.ts +++ /dev/null @@ -1,64 +0,0 @@ -import zxcvbn from "zxcvbn"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { hashPassword } from "../password"; -import { signJwt, verifyJwt } from "../jwt"; -import { createSession, revokeAllSessions, SESSION_TTL_MS } from "../sessions"; -import { checkModeration } from "./login"; -import type { Env } from "../index"; - -export async function handleForceChangePassword(request: Request, env: Env): Promise { - const body = await request.json<{ - changeToken: string; - newPassword: string; - }>(); - - if (!body.changeToken || !body.newPassword) { - return errorResponse(Errors.BAD_REQUEST); - } - - const session = await verifyJwt(body.changeToken, env.JWT_SECRET); - if (!session || !session.forcePasswordChange || !session.cti) { - return errorResponse(Errors.UNAUTHORIZED); - } - - if (zxcvbn(body.newPassword).score < 3) { - return Response.json({ ok: false, error: "password_too_weak" }, { status: 400 }); - } - - const user = await env.DB.prepare( - "SELECT id, email, name, created_at, is_admin, moderation FROM users WHERE id = ? AND force_password_change = 1", - ).bind(session.userId).first<{ id: string; email: string; name: string; created_at: string; is_admin: number; moderation: number }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - // Re-check moderation at consume time (mirrors admin-handoff-exchange). The - // change token was minted at login, before any later suspension/disable — a - // user moderated inside the 15-min window must not complete the reset and - // receive a fresh session. - const moderationError = checkModeration(user.moderation); - if (moderationError) return moderationError; - - // Single statement performs the consume: matches `change_token_id` to the - // JWT's `cti` claim, writes the new hash, clears the flag, and clears the - // nonce - atomically. If 0 rows change, the token was either never the - // current one, or has already been consumed by a concurrent request. - const newHash = await hashPassword(body.newPassword); - const updateResult = await env.DB.prepare( - "UPDATE users SET password_hash = ?, force_password_change = 0, change_token_id = NULL WHERE id = ? AND force_password_change = 1 AND change_token_id = ?", - ).bind(newHash, user.id, session.cti).run(); - if ((updateResult.meta.changes ?? 0) !== 1) { - return errorResponse(Errors.UNAUTHORIZED); - } - - // The forced-reset path is for "your password was leaked / your account - // is compromised" scenarios - kill every existing session, no exceptions. - await revokeAllSessions(env, user.id); - - const expiresAt = Date.now() + SESSION_TTL_MS; - const sid = await createSession(env, user.id, request, expiresAt); - const token = await signJwt( - { userId: user.id, email: user.email, expiresAt, isAdmin: Boolean(user.is_admin), sid }, - env.JWT_SECRET, - ); - - return okResponse({ token, user: { id: user.id, email: user.email, name: user.name, createdAt: user.created_at } }); -} diff --git a/packages/auth/src/routes/login.test.ts b/packages/auth/src/routes/login.test.ts deleted file mode 100644 index 479966ca..00000000 --- a/packages/auth/src/routes/login.test.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { checkModeration, handleLogin } from "./login"; - -vi.mock("../turnstile", () => ({ verifyTurnstile: vi.fn(async () => true) })); -vi.mock("../password", () => ({ - verifyPassword: vi.fn(async () => true), - hashPassword: vi.fn(async () => "new-hash"), - needsRehash: vi.fn(() => false), - DUMMY_PASSWORD_HASH: "dummy-hash", -})); -vi.mock("../jwt", () => ({ signJwt: vi.fn(async () => "signed.jwt"), verifyJwt: vi.fn() })); -vi.mock("../sessions", () => ({ - createSession: vi.fn(async () => "sess-1"), - SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, -})); -vi.mock("../mfa", () => ({ - verifyAndConsumeTotp: vi.fn(async () => true), - validateAndConsumeBackupCode: vi.fn(async () => true), -})); - -import { verifyTurnstile } from "../turnstile"; -import { signJwt, verifyJwt } from "../jwt"; -import { verifyAndConsumeTotp } from "../mfa"; - -type UserRow = { - id: string; email: string; name: string; password_hash: string; created_at: string; - moderation: number; totp_secret: string | null; force_password_change: number; - is_admin: number; email_verified: number; -}; - -function baseUser(overrides?: Partial): UserRow { - return { - id: "user-1", - email: "test@example.com", - name: "Test", - password_hash: "hash", - created_at: "2026-01-01", - moderation: 0, - totp_secret: null, - force_password_change: 0, - is_admin: 0, - email_verified: 1, - ...overrides, - }; -} - -// SQL-aware D1 mock: the user SELECT and the webauthn existence check both call -// .first(), so dispatch by the query text. createSession is module-mocked, so no -// session writes hit this. -function makeEnv(opts?: { user?: UserRow | null; hasWebauthn?: boolean; limitSuccess?: boolean }) { - const user = opts?.user === undefined ? baseUser() : opts.user; - const hasWebauthn = opts?.hasWebauthn ?? false; - const run = vi.fn().mockResolvedValue({ meta: { changes: 1 } }); - const prepare = vi.fn((sql: string) => ({ - bind: vi.fn(() => ({ - first: vi.fn(async () => { - if (sql.includes("FROM users")) return user; - if (sql.includes("webauthn_credentials")) return hasWebauthn ? { 1: 1 } : null; - return null; - }), - run, - })), - })); - const limit = vi.fn(async () => ({ success: opts?.limitSuccess ?? true })); - return { - env: { - DB: { prepare }, - JWT_SECRET: "secret", - TURNSTILE_SECRET: "ts-secret", - RATE_LIMITER_AUTH: { limit }, - } as unknown as Parameters[1], - prepare, - run, - limit, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyTurnstile).mockResolvedValue(true); - vi.mocked(verifyAndConsumeTotp).mockResolvedValue(true); - vi.mocked(signJwt).mockResolvedValue("signed.jwt"); -}); - -describe("checkModeration", () => { - it("returns null for an active account (moderation=0)", () => { - expect(checkModeration(0)).toBeNull(); - }); - - it("returns a 403 account_disabled response for moderation=-1", async () => { - const res = checkModeration(-1); - expect(res).not.toBeNull(); - expect(res!.status).toBe(403); - const body = await res!.json<{ ok: boolean; error: string }>(); - expect(body.error).toBe("account_disabled"); - }); - - it("returns a 403 account_suspended response when suspended until a future time", async () => { - const untilSeconds = Math.floor(Date.now() / 1000) + 3600; - const res = checkModeration(untilSeconds); - expect(res).not.toBeNull(); - expect(res!.status).toBe(403); - const body = await res!.json<{ ok: boolean; error: string; until: number }>(); - expect(body.error).toBe("account_suspended"); - expect(body.until).toBe(untilSeconds); - }); - - it("returns null when a suspension timestamp is in the past (expired)", () => { - const expiredSeconds = Math.floor(Date.now() / 1000) - 1; - expect(checkModeration(expiredSeconds)).toBeNull(); - }); - - it("returns null when the suspension expires exactly now", () => { - // nowSeconds === moderation → suspension has just expired - const nowSeconds = Math.floor(Date.now() / 1000); - expect(checkModeration(nowSeconds)).toBeNull(); - }); -}); - -describe("handleLogin - 2FA prompt carries a pre-auth token", () => { - it("includes preAuthToken in the totp_required response", async () => { - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ email: "test@example.com", password: "pw", turnstileToken: "t" }), env); - expect(res.status).toBe(200); - const body = await res.json<{ error: string; preAuthToken: string }>(); - expect(body.error).toBe("totp_required"); - expect(typeof body.preAuthToken).toBe("string"); - expect(body.preAuthToken).toBe("signed.jwt"); - // Signed with the pre2fa marker so only the continuation path can redeem it. - expect(signJwt).toHaveBeenCalledWith( - expect.objectContaining({ userId: "user-1", email: "test@example.com", pre2fa: true }), - "secret", - ); - }); - - it("includes preAuthToken in the two_factor_required response", async () => { - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }), hasWebauthn: true }); - const res = await handleLogin(req({ email: "test@example.com", password: "pw", turnstileToken: "t" }), env); - expect(res.status).toBe(200); - const body = await res.json<{ error: string; methods: string[]; preAuthToken: string }>(); - expect(body.error).toBe("two_factor_required"); - expect(body.methods).toEqual(["totp", "webauthn"]); - expect(typeof body.preAuthToken).toBe("string"); - expect(body.preAuthToken).toBe("signed.jwt"); - }); -}); - -describe("handleLogin - pre-auth continuation", () => { - const validClaims = () => ({ userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 60_000, pre2fa: true }); - - it("issues a session for a valid pre-auth token + totpCode without touching Turnstile", async () => { - vi.mocked(verifyJwt).mockResolvedValue(validClaims() as never); - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "pre.token", totpCode: "123456" }), env); - expect(res.status).toBe(200); - const body = await res.json<{ ok: boolean; data: { token: string; user: { id: string } } }>(); - expect(body.ok).toBe(true); - expect(body.data.token).toBe("signed.jwt"); - expect(body.data.user.id).toBe("user-1"); - // The whole point of the token: no re-verification of Turnstile. - expect(verifyTurnstile).not.toHaveBeenCalled(); - }); - - it("returns invalid_totp and consumes the MFA rate limit for a wrong code", async () => { - vi.mocked(verifyJwt).mockResolvedValue(validClaims() as never); - vi.mocked(verifyAndConsumeTotp).mockResolvedValue(false); - const { env, limit } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "pre.token", totpCode: "000000" }), env); - expect(res.status).toBe(401); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("invalid_totp"); - expect(limit).toHaveBeenCalledWith({ key: "mfa:user-1" }); - }); - - it("returns 401 pre_auth_expired for an expired token", async () => { - vi.mocked(verifyJwt).mockResolvedValue({ ...validClaims(), expiresAt: Date.now() - 1 } as never); - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "pre.token", totpCode: "123456" }), env); - expect(res.status).toBe(401); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("pre_auth_expired"); - }); - - it("returns 401 pre_auth_expired for a tampered/garbage token", async () => { - vi.mocked(verifyJwt).mockResolvedValue(null); - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "garbage", totpCode: "123456" }), env); - expect(res.status).toBe(401); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("pre_auth_expired"); - }); - - it("refuses a token lacking the pre2fa claim (e.g. a real session token)", async () => { - // Same secret, valid signature/expiry, but no pre2fa marker. - vi.mocked(verifyJwt).mockResolvedValue({ userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 60_000, sid: "sess-x" } as never); - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "session.token", totpCode: "123456" }), env); - expect(res.status).toBe(401); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("pre_auth_expired"); - }); - - it("returns 401 pre_auth_expired when the user row is gone", async () => { - vi.mocked(verifyJwt).mockResolvedValue(validClaims() as never); - const { env } = makeEnv({ user: null }); - const res = await handleLogin(req({ preAuthToken: "pre.token", totpCode: "123456" }), env); - expect(res.status).toBe(401); - const body = await res.json<{ error: string }>(); - expect(body.error).toBe("pre_auth_expired"); - }); - - it("returns 401 Unauthorized when TOTP was disabled mid-flow", async () => { - vi.mocked(verifyJwt).mockResolvedValue(validClaims() as never); - const { env } = makeEnv({ user: baseUser({ totp_secret: null }) }); - const res = await handleLogin(req({ preAuthToken: "pre.token", totpCode: "123456" }), env); - expect(res.status).toBe(401); - }); - - it("returns 400 when neither totpCode nor backupCode is supplied", async () => { - vi.mocked(verifyJwt).mockResolvedValue(validClaims() as never); - const { env } = makeEnv({ user: baseUser({ totp_secret: "SECRET" }) }); - const res = await handleLogin(req({ preAuthToken: "pre.token" }), env); - expect(res.status).toBe(400); - }); -}); - -describe("handleLogin - password path still works", () => { - it("issues a session for valid credentials with no 2FA", async () => { - const { env } = makeEnv({ user: baseUser() }); - const res = await handleLogin(req({ email: "test@example.com", password: "pw", turnstileToken: "t" }), env); - expect(res.status).toBe(200); - const body = await res.json<{ ok: boolean; data: { token: string } }>(); - expect(body.ok).toBe(true); - expect(body.data.token).toBe("signed.jwt"); - expect(verifyTurnstile).toHaveBeenCalledOnce(); - }); - - it("rejects a failed Turnstile check", async () => { - vi.mocked(verifyTurnstile).mockResolvedValue(false); - const { env } = makeEnv({ user: baseUser() }); - const res = await handleLogin(req({ email: "test@example.com", password: "pw", turnstileToken: "bad" }), env); - expect(res.status).toBe(400); - }); -}); diff --git a/packages/auth/src/routes/login.ts b/packages/auth/src/routes/login.ts deleted file mode 100644 index b77e2054..00000000 --- a/packages/auth/src/routes/login.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { okResponse, errorResponse, Errors, normalizeEmail } from "../lib"; -import { verifyPassword, hashPassword, needsRehash, DUMMY_PASSWORD_HASH } from "../password"; -import { signJwt, verifyJwt } from "../jwt"; -import { verifyTurnstile } from "../turnstile"; -import { validateAndConsumeBackupCode, verifyAndConsumeTotp } from "../mfa"; -import { createSession, SESSION_TTL_MS } from "../sessions"; -import { isEmailVerificationEnabled } from "../verification"; -import type { Session } from "../lib"; -import type { Env } from "../index"; - -// Shared column list so the password path and the pre-auth continuation load -// the exact same user shape. -const USER_SELECT = - "SELECT id, email, name, password_hash, created_at, moderation, totp_secret, force_password_change, is_admin, email_verified FROM users"; - -type LoginUserRow = { - id: string; email: string; name: string; password_hash: string; created_at: string; moderation: number; totp_secret: string | null; force_password_change: number; is_admin: number; email_verified: number; -}; - -// Claims carried by the short-lived pre-auth token. Identity only, plus the -// `pre2fa` marker that gates redemption - a session token or change-token -// signed with the same secret lacks it and can't be redeemed for 2FA. -type PreAuthClaims = Session & { pre2fa?: boolean }; - -export async function handleLogin(request: Request, env: Env): Promise { - const body = await request.json<{ - email?: string; - password?: string; - turnstileToken?: string; - totpCode?: string; - backupCode?: string; - preAuthToken?: string; - }>(); - - // Continuation path: a prior attempt already cleared password + Turnstile and - // returned `totp_required` / `two_factor_required` with a short-lived pre-auth - // token. The client now returns just that token plus a 2FA code, so skip - // Turnstile and the email/password check entirely. Identity rides in the - // token, but nothing beyond `userId` is trusted - the user row is reloaded and - // every gate re-run on redemption. - if (body.preAuthToken) return handlePreAuthContinuation(request, env, body); - - if (!body.email || !body.password) return errorResponse(Errors.BAD_REQUEST); - - const turnstileValid = await verifyTurnstile(body.turnstileToken ?? "", env.TURNSTILE_SECRET); - if (!turnstileValid) return errorResponse(Errors.BAD_REQUEST); - - const row = await env.DB.prepare(USER_SELECT + " WHERE email = ?") - .bind(normalizeEmail(body.email)).first(); - - // Always run a PBKDF2 derivation, even when the account doesn't exist, so the - // response time can't be used to enumerate registered emails. The dummy hash - // never matches, so the missing-user branch still returns UNAUTHORIZED. - const valid = await verifyPassword(body.password, row?.password_hash ?? DUMMY_PASSWORD_HASH); - if (!row || !valid) return errorResponse(Errors.UNAUTHORIZED); - - const moderationResponse = checkModeration(row.moderation); - if (moderationResponse) return moderationResponse; - - // Only an unverified account can be gated, so skip the flag lookup entirely - // for verified users. Default off: when the flag (or its binding) is absent, - // verification isn't enforced and login proceeds. - if (!row.email_verified) { - const requireVerification = await isEmailVerificationEnabled(env, row.id); - if (requireVerification) { - return Response.json({ ok: false, error: "email_not_verified" }, { status: 403 }); - } - } - - // Existence check only - stop at the first row instead of counting every - // credential. Backed by idx_webauthn_credentials_user (migration 0027). - const webauthnResult = await env.DB.prepare( - "SELECT 1 FROM webauthn_credentials WHERE user_id = ? LIMIT 1", - ).bind(row.id).first<{ 1: number }>(); - const hasWebauthn = webauthnResult !== null; - const hasTOTP = !!row.totp_secret; - - if (hasWebauthn && hasTOTP) { - // Both methods available: if totpCode or backupCode supplied the user chose TOTP, otherwise prompt for choice - if (!body.totpCode && !body.backupCode) { - return Response.json( - { - ok: false, - error: "two_factor_required", - methods: ["totp", "webauthn"], - userId: row.id, - preAuthToken: await signPreAuthToken(env, row.id, row.email), - }, - { status: 200 }, - ); - } - const totpError = await verifyTotpOrBackup(env, row.id, row.totp_secret!, body.totpCode, body.backupCode); - if (totpError) return totpError; - } else if (hasWebauthn) { - return Response.json({ ok: false, error: "webauthn_required", userId: row.id }, { status: 200 }); - } else if (hasTOTP) { - if (!body.totpCode && !body.backupCode) { - return Response.json( - { ok: false, error: "totp_required", preAuthToken: await signPreAuthToken(env, row.id, row.email) }, - { status: 200 }, - ); - } - const totpError = await verifyTotpOrBackup(env, row.id, row.totp_secret!, body.totpCode, body.backupCode); - if (totpError) return totpError; - } - - // Authentication succeeded - opportunistically migrate hashes that were - // written with an older iteration count. (Continuation path has no password - // in hand, so it skips this and relies on the original login having done it.) - if (needsRehash(row.password_hash)) { - const newHash = await hashPassword(body.password); - await env.DB.prepare("UPDATE users SET password_hash = ? WHERE id = ?") - .bind(newHash, row.id).run(); - } - - return issueSessionOrForceChange(request, env, row); -} - -// Redeems a pre-auth token for the 2FA step of a login that already cleared -// password + Turnstile. Trusts nothing beyond identity: reloads the user row, -// re-runs moderation, and re-verifies the 2FA code under the same per-user -// `mfa:` throttle as the password path. -async function handlePreAuthContinuation( - request: Request, - env: Env, - body: { preAuthToken?: string; totpCode?: string; backupCode?: string }, -): Promise { - // verifyJwt already checks the signature and generic expiry, but re-assert - // the `pre2fa` claim and the expiry here explicitly so a session token or a - // change-token signed with the same secret can never be redeemed for 2FA. - const claims = (await verifyJwt(body.preAuthToken!, env.JWT_SECRET)) as PreAuthClaims | null; - if (!claims || claims.pre2fa !== true || claims.expiresAt <= Date.now()) { - return Response.json({ ok: false, error: "pre_auth_expired" }, { status: 401 }); - } - - const row = await env.DB.prepare(USER_SELECT + " WHERE id = ?") - .bind(claims.userId).first(); - if (!row) return Response.json({ ok: false, error: "pre_auth_expired" }, { status: 401 }); - - const moderationResponse = checkModeration(row.moderation); - if (moderationResponse) return moderationResponse; - - if (!row.email_verified && await isEmailVerificationEnabled(env, row.id)) { - return Response.json({ ok: false, error: "email_not_verified" }, { status: 403 }); - } - - // TOTP was disabled between issuing the token and redeeming it - a weird - // state; refuse rather than issue a session with the 2FA step skipped. - if (!row.totp_secret) return errorResponse(Errors.UNAUTHORIZED); - - if (!body.totpCode && !body.backupCode) return errorResponse(Errors.BAD_REQUEST); - - const totpError = await verifyTotpOrBackup(env, row.id, row.totp_secret, body.totpCode, body.backupCode); - if (totpError) return totpError; - - return issueSessionOrForceChange(request, env, row); -} - -// Post-2FA tail shared by the password path, the pre-auth continuation, and -// passkey sign-in: force-change branch, otherwise issue a session. Assumes the -// caller has already verified credentials (password, pre-auth token, or -// passkey), any 2FA, and the moderation / email-verification gates. -export async function issueSessionOrForceChange( - request: Request, - env: Env, - row: Pick, -): Promise { - if (row.force_password_change) { - // Pre-session token: short-lived, no `sid`. Only valid against - // /force-change-password, which checks `forcePasswordChange` explicitly. - // The `cti` nonce is mirrored on the user row; re-issuing it here - // overwrites any prior unused token, killing it before its 15-min - // expiry kicks in. - const cti = crypto.randomUUID(); - await env.DB.prepare("UPDATE users SET change_token_id = ? WHERE id = ?") - .bind(cti, row.id).run(); - const changeToken = await signJwt( - { userId: row.id, email: row.email, expiresAt: Date.now() + 15 * 60 * 1000, isAdmin: Boolean(row.is_admin), forcePasswordChange: true, cti }, - env.JWT_SECRET, - ); - return Response.json({ ok: false, error: "password_change_required", changeToken }, { status: 200 }); - } - - const expiresAt = Date.now() + SESSION_TTL_MS; - const sid = await createSession(env, row.id, request, expiresAt); - const token = await signJwt( - { userId: row.id, email: row.email, expiresAt, isAdmin: Boolean(row.is_admin), sid }, - env.JWT_SECRET, - ); - - return okResponse({ token, user: { id: row.id, email: row.email, name: row.name, createdAt: row.created_at } }); -} - -// Mints the short-lived pre-auth token handed back with the 2FA prompt so the -// client needn't re-send password + Turnstile on each 2FA attempt. Carries -// identity only; redemption reloads the user and re-checks everything. -async function signPreAuthToken(env: Env, userId: string, email: string): Promise { - const payload: PreAuthClaims = { userId, email, expiresAt: Date.now() + 5 * 60 * 1000, pre2fa: true }; - return signJwt(payload, env.JWT_SECRET); -} - -async function verifyTotpOrBackup( - env: Env, - userId: string, - totpSecret: string, - totpCode?: string, - backupCode?: string, -): Promise { - if (!totpCode && !backupCode) return null; - - // Same per-user budget as requireMFA (`mfa:`): the password is - // already verified by this point, so key the throttle on the account - a - // distributed attacker can rotate source IPs, but not this key. - const { success } = await env.RATE_LIMITER_AUTH.limit({ key: `mfa:${userId}` }); - if (!success) return errorResponse(Errors.RATE_LIMITED); - - if (totpCode) { - const valid = await verifyAndConsumeTotp(env, userId, totpSecret, totpCode); - if (!valid) return Response.json({ ok: false, error: "invalid_totp" }, { status: 401 }); - return null; - } - const valid = await validateAndConsumeBackupCode(env, userId, backupCode!); - if (!valid) return Response.json({ ok: false, error: "invalid_backup_code" }, { status: 401 }); - return null; -} - -// Returns a 403 response if the account is restricted, or null if active. -// moderation: 0 = active, -1 = disabled, >0 = suspended until unix timestamp (seconds) -export function checkModeration(moderation: number): Response | null { - if (moderation === 0) return null; - if (moderation === -1) return Response.json({ ok: false, error: "account_disabled" }, { status: 403 }); - if (moderation > 0) { - const nowSeconds = Math.floor(Date.now() / 1000); - if (nowSeconds < moderation) { - return Response.json({ ok: false, error: "account_suspended", until: moderation }, { status: 403 }); - } - } - return null; // suspension has expired -} diff --git a/packages/auth/src/routes/lookup-by-id.ts b/packages/auth/src/routes/lookup-by-id.ts deleted file mode 100644 index f695f6f3..00000000 --- a/packages/auth/src/routes/lookup-by-id.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { okResponse, errorResponse, Errors } from "../lib"; -import { isEmailVerificationEnabled } from "../verification"; -import type { Env } from "../index"; - -type LookupUserRow = { - id: string; - email: string; - name: string; - email_verified: number; - created_at: string; - timezone: string | null; - badges: number | null; - bio: string | null; - handle: string | null; - handle_locked: number | null; -}; - -export async function handleLookupById(request: Request, env: Env): Promise { - const body = await request.json<{ userId?: string }>(); - if (!body.userId) return errorResponse(Errors.BAD_REQUEST); - - // One round trip for both reads. The pending-email query binds the - // requested id directly; it matches `u.id = ?` exactly, so for an unknown - // user it simply returns no row and we 404 below. - const [userResult, pendingResult] = await env.DB.batch([ - env.DB.prepare( - `SELECT u.id, u.email, u.name, u.email_verified, u.created_at, - p.timezone, p.badges, p.bio, p.handle, p.handle_locked - FROM users u - LEFT JOIN user_preferences p ON p.user_id = u.id - WHERE u.id = ?`, - ).bind(body.userId), - // In-flight email change (confirm-first flow): the newest unconsumed, - // unexpired change token's target address, or null. - env.DB.prepare( - "SELECT email FROM email_verification_tokens WHERE user_id = ? AND email IS NOT NULL AND consumed_at IS NULL AND expires_at > ? ORDER BY created_at DESC LIMIT 1", - ).bind(body.userId, Date.now()), - ]); - - const user = (userResult.results as LookupUserRow[])[0]; - if (!user) return errorResponse(Errors.NOT_FOUND); - const pending = (pendingResult.results as { email: string }[])[0]; - - const emailVerificationEnabled = await isEmailVerificationEnabled(env, user.id); - - return okResponse({ userId: user.id, email: user.email, name: user.name, emailVerified: user.email_verified === 1, emailVerificationEnabled, pendingEmail: pending?.email ?? null, createdAt: user.created_at, timezone: user.timezone, badges: user.badges ?? 0, bio: user.bio, handle: user.handle ?? null, handleLocked: !!user.handle_locked }); -} diff --git a/packages/auth/src/routes/lookup.ts b/packages/auth/src/routes/lookup.ts deleted file mode 100644 index eb05db1c..00000000 --- a/packages/auth/src/routes/lookup.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; - -export async function handleLookup(request: Request, env: Env): Promise { - const body = await request.json<{ email: string }>(); - if (!body.email) return errorResponse(Errors.BAD_REQUEST); - - const user = await env.DB.prepare( - "SELECT id, email, name FROM users WHERE LOWER(email) = LOWER(?)", - ).bind(body.email.trim()).first<{ id: string; email: string; name: string }>(); - - if (!user) return errorResponse(Errors.NOT_FOUND); - - return okResponse({ userId: user.id, email: user.email, name: user.name }); -} diff --git a/packages/auth/src/routes/passkey-auth-finish.test.ts b/packages/auth/src/routes/passkey-auth-finish.test.ts deleted file mode 100644 index 6a061253..00000000 --- a/packages/auth/src/routes/passkey-auth-finish.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("../webauthn", () => ({ - verifyDiscoverableAssertion: vi.fn(), - verifyWebauthnAssertion: vi.fn(), -})); -vi.mock("../verification", () => ({ - isEmailVerificationEnabled: vi.fn(), -})); -vi.mock("../jwt", () => ({ - signJwt: vi.fn(async () => "signed.jwt"), - verifyJwt: vi.fn(), -})); -vi.mock("../sessions", () => ({ - createSession: vi.fn(async () => "session-1"), - SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, -})); - -import { handlePasskeyAuthFinish } from "./passkey-auth-finish"; -import { verifyDiscoverableAssertion } from "../webauthn"; -import { isEmailVerificationEnabled } from "../verification"; -import { createSession } from "../sessions"; - -function request(body: Record = { challengeId: "challenge-1", response: { id: "credential-1" } }) { - return new Request("http://localhost/webauthn/auth/passkey/finish", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -function makeEnv(overrides: Record = {}) { - const user = { - id: "user-1", - email: "user@example.com", - name: "User", - created_at: "2026-01-01", - moderation: 0, - force_password_change: 0, - is_admin: 0, - email_verified: 1, - ...overrides, - }; - const first = vi.fn().mockResolvedValue(user); - const run = vi.fn().mockResolvedValue({ meta: { changes: 1 } }); - const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare }, JWT_SECRET: "secret" } as unknown as Parameters[1], - bind, - }; -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyDiscoverableAssertion).mockResolvedValue({ userId: "user-1" }); - vi.mocked(isEmailVerificationEnabled).mockResolvedValue(false); -}); - -describe("handlePasskeyAuthFinish", () => { - it("rejects a request without a challenge or assertion", async () => { - const { env } = makeEnv(); - const response = await handlePasskeyAuthFinish(request({ challengeId: "c" }), env); - expect(response.status).toBe(400); - expect(verifyDiscoverableAssertion).not.toHaveBeenCalled(); - }); - - it("issues a session for the account the verified passkey belongs to", async () => { - const { env, bind } = makeEnv(); - const response = await handlePasskeyAuthFinish(request(), env); - - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ ok: true, data: { token: "signed.jwt", user: { id: "user-1" } } }); - expect(bind).toHaveBeenCalledWith("user-1"); - expect(createSession).toHaveBeenCalledOnce(); - }); - - it("passes a failed assertion through without loading the account", async () => { - vi.mocked(verifyDiscoverableAssertion).mockResolvedValue( - Response.json({ ok: false, error: "unauthorized" }, { status: 401 }), - ); - const { env, bind } = makeEnv(); - const response = await handlePasskeyAuthFinish(request(), env); - - expect(response.status).toBe(401); - expect(bind).not.toHaveBeenCalled(); - expect(createSession).not.toHaveBeenCalled(); - }); - - it("refuses a disabled account", async () => { - const { env } = makeEnv({ moderation: -1 }); - const response = await handlePasskeyAuthFinish(request(), env); - - expect(response.status).toBe(403); - expect(await response.json()).toMatchObject({ error: "account_disabled" }); - expect(createSession).not.toHaveBeenCalled(); - }); - - it("gates an unverified account and returns its email for the resend prompt", async () => { - vi.mocked(isEmailVerificationEnabled).mockResolvedValue(true); - const { env } = makeEnv({ email_verified: 0 }); - const response = await handlePasskeyAuthFinish(request(), env); - - expect(response.status).toBe(403); - expect(await response.json()).toMatchObject({ error: "email_not_verified", email: "user@example.com" }); - expect(createSession).not.toHaveBeenCalled(); - }); - - it("routes a forced password change to the change-token flow instead of a session", async () => { - const { env } = makeEnv({ force_password_change: 1 }); - const response = await handlePasskeyAuthFinish(request(), env); - - expect(await response.json()).toMatchObject({ error: "password_change_required", changeToken: "signed.jwt" }); - expect(createSession).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/auth/src/routes/passkey-auth-finish.ts b/packages/auth/src/routes/passkey-auth-finish.ts deleted file mode 100644 index c4ff040c..00000000 --- a/packages/auth/src/routes/passkey-auth-finish.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { errorResponse, Errors } from "../lib"; -import { verifyDiscoverableAssertion } from "../webauthn"; -import { checkModeration, issueSessionOrForceChange } from "./login"; -import { isEmailVerificationEnabled } from "../verification"; -import type { Env } from "../index"; - -// Completes a usernameless passkey sign-in. A user-verifying passkey is a -// complete login on its own (possession + PIN/biometric), the same standing it -// already has as the second step of password login, so no TOTP is asked for. -// -// Unlike /webauthn/auth/finish, the account is only known once the assertion -// verifies, so the account gates run after the challenge is consumed. That's -// deliberate: checking them first would let anyone holding a credential id -// learn its account's moderation / verification state without the passkey. -// The user just retries the ceremony - there's nothing to retype. -export async function handlePasskeyAuthFinish(request: Request, env: Env): Promise { - const body = await request.json<{ challengeId?: string; response?: Record }>(); - if (!body.challengeId || !body.response || typeof body.response !== "object") { - return errorResponse(Errors.BAD_REQUEST); - } - - const result = await verifyDiscoverableAssertion(env, body.challengeId, body.response); - if (result instanceof Response) return result; - - const user = await env.DB.prepare( - "SELECT id, email, name, created_at, moderation, force_password_change, is_admin, email_verified FROM users WHERE id = ?", - ) - .bind(result.userId) - .first<{ id: string; email: string; name: string; created_at: string; moderation: number; force_password_change: number; is_admin: number; email_verified: number }>(); - if (!user) return errorResponse(Errors.UNAUTHORIZED); - - const moderationResponse = checkModeration(user.moderation); - if (moderationResponse) return moderationResponse; - - if (!user.email_verified && await isEmailVerificationEnabled(env, user.id)) { - // The caller proved control of the account, and the client never typed an - // email on this path, so hand it back for the "resend verification" button. - return Response.json({ ok: false, error: "email_not_verified", email: user.email }, { status: 403 }); - } - - return issueSessionOrForceChange(request, env, user); -} diff --git a/packages/auth/src/routes/passkey-auth-start.ts b/packages/auth/src/routes/passkey-auth-start.ts deleted file mode 100644 index 737c792e..00000000 --- a/packages/auth/src/routes/passkey-auth-start.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { okResponse } from "../lib"; -import { createDiscoverableAuthenticationOptions } from "../webauthn"; -import type { Env } from "../index"; - -// Starts a usernameless passkey sign-in. No identity in, so nothing to leak: -// the browser offers whichever passkeys it holds for this RP ID. IP-rate-limited -// in index.ts (RATE_LIMITER_AUTH), which bounds the challenge rows it writes. -export async function handlePasskeyAuthStart(_request: Request, env: Env): Promise { - const { options, challengeId } = await createDiscoverableAuthenticationOptions(env); - return okResponse({ options, challengeId }); -} diff --git a/packages/auth/src/routes/register.test.ts b/packages/auth/src/routes/register.test.ts deleted file mode 100644 index 6bd67a52..00000000 --- a/packages/auth/src/routes/register.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, it, expect, vi } from "vitest"; -import { handleRegister } from "./register"; - -function req(body: unknown) { - return new Request("http://localhost/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -function makeEnv(getBooleanValue?: ReturnType) { - const prepare = vi.fn(); - return { - env: { - DB: { prepare }, - FLAGS: getBooleanValue ? { getBooleanValue } : undefined, - } as unknown as Parameters[1], - prepare, - }; -} - -describe("handleRegister signup flag gate", () => { - it("refuses with 403 and a message when the signup flag is off", async () => { - const getBooleanValue = vi.fn().mockResolvedValue(false); - const { env, prepare } = makeEnv(getBooleanValue); - - const res = await handleRegister( - req({ email: "a@example.com", password: "correct horse battery staple", name: "A", turnstileToken: "t" }), - env, - ); - - expect(res.status).toBe(403); - const body = await res.json<{ ok: boolean; error: string }>(); - expect(body.ok).toBe(false); - expect(body.error).toBe("New sign-ups are currently disabled."); - // The gate is checked before any parsing/DB work - nothing should be touched. - expect(getBooleanValue).toHaveBeenCalledWith("signup", true); - expect(prepare).not.toHaveBeenCalled(); - }); -}); - -describe("handleRegister email_verified", () => { - it("stores email_verified = 0 even when the verification flag is off", async () => { - // signup flag on, email-verification flag off. - const getBooleanValue = vi.fn().mockImplementation((flag: string) => - Promise.resolve(flag === "signup"), - ); - const calls: Array<{ sql: string; binds: unknown[] }> = []; - const prepare = vi.fn((sql: string) => ({ - bind: (...binds: unknown[]) => { - calls.push({ sql, binds }); - return { - first: async () => null, - run: async () => ({}), - }; - }, - })); - const env = { - DB: { prepare, batch: async (stmts: unknown[]) => stmts.map(() => ({ results: [], meta: {} })) }, - FLAGS: { getBooleanValue }, - TURNSTILE_SECRET: "1x0000000000000000000000000000000AA", - JWT_SECRET: "test-secret", - } as unknown as Parameters[1]; - - const res = await handleRegister( - req({ email: "a@example.com", password: "correct horse battery staple", name: "A", turnstileToken: "t" }), - env, - ); - - expect(res.status).toBe(201); - const body = await res.json<{ ok: boolean; data: { verificationSent: boolean } }>(); - expect(body.data.verificationSent).toBe(false); - - const insert = calls.find(c => c.sql.includes("INSERT INTO users")); - expect(insert).toBeDefined(); - // The literal 0 lives in the SQL, not the binds - no bind may carry a 1 - // into the email_verified slot. - expect(insert!.sql).toContain("email_verified) VALUES (?, ?, ?, ?, ?, 0)"); - expect(insert!.binds).toHaveLength(5); - }); -}); diff --git a/packages/auth/src/routes/register.ts b/packages/auth/src/routes/register.ts deleted file mode 100644 index 045fc833..00000000 --- a/packages/auth/src/routes/register.ts +++ /dev/null @@ -1,88 +0,0 @@ -import zxcvbn from "zxcvbn"; -import { okResponse, errorResponse, Errors, normalizeEmail } from "../lib"; -import { hashPassword } from "../password"; -import { verifyTurnstile } from "../turnstile"; -import { createVerificationToken, isEmailVerificationEnabled } from "../verification"; -import { sendVerificationEmail } from "../email"; -import { signJwt } from "../jwt"; -import { createSession, SESSION_TTL_MS } from "../sessions"; -import type { Env } from "../index"; - -export async function handleRegister(request: Request, env: Env): Promise { - // New account creation is gated by the Flagship "signup" flag. Checked before - // any parsing/DB work so a kill takes effect with zero load. Defaults to - // enabled when the flag/binding is unavailable (local dev or a flag-service - // outage) - a deliberate-off switch, not fail-closed. - const signupEnabled = env.FLAGS ? await env.FLAGS.getBooleanValue("signup", true) : true; - if (!signupEnabled) { - return Response.json( - { ok: false, error: "New sign-ups are currently disabled.", status: 403 }, - { status: 403 }, - ); - } - - const body = await request.json<{ email: string; password: string; name: string; turnstileToken: string }>(); - - if (!body.email || !body.password || !body.name) { - return errorResponse(Errors.BAD_REQUEST); - } - - if (typeof body.name !== "string" || body.name.trim().length === 0 || body.name.length > 100) { - return errorResponse(Errors.BAD_REQUEST); - } - - if (typeof body.email !== "string") return errorResponse(Errors.BAD_REQUEST); - const email = normalizeEmail(body.email); - // A whitespace-only address passes the truthy check above but trims to empty. - if (!email) return errorResponse(Errors.BAD_REQUEST); - - if (zxcvbn(body.password).score < 3) { - return errorResponse(Errors.BAD_REQUEST); - } - - const turnstileValid = await verifyTurnstile(body.turnstileToken, env.TURNSTILE_SECRET); - if (!turnstileValid) return errorResponse(Errors.BAD_REQUEST); - - const existing = await env.DB.prepare("SELECT id FROM users WHERE email = ?") - .bind(email) - .first(); - - if (existing) return errorResponse(Errors.CONFLICT); - - const id = crypto.randomUUID(); - const passwordHash = await hashPassword(body.password); - const now = new Date().toISOString(); - const requireVerification = await isEmailVerificationEnabled(env, id); - - // email_verified starts at 0 unconditionally: even when the flag isn't - // enforcing verification, the address genuinely hasn't been verified, and - // the column feeds truthful surfaces (admin - // dashboard). Enforcement (login gate, verification email) stays flag-only. - await env.DB.prepare( - "INSERT INTO users (id, email, name, password_hash, created_at, email_verified) VALUES (?, ?, ?, ?, ?, 0)", - ).bind(id, email, body.name, passwordHash, now).run(); - - if (requireVerification) { - const verificationToken = await createVerificationToken(env, id); - const verifyUrl = `${env.APP_ORIGIN}/verify-email?token=${verificationToken}`; - await sendVerificationEmail(env, email, verifyUrl); - return okResponse({ verificationSent: true, email }, 201); - } - - const expiresAt = Date.now() + SESSION_TTL_MS; - const sid = await createSession(env, id, request, expiresAt); - const token = await signJwt( - { userId: id, email, expiresAt, isAdmin: false, sid }, - env.JWT_SECRET, - ); - - return okResponse( - { - verificationSent: false, - email, - token, - user: { id, email, name: body.name, createdAt: now }, - }, - 201, - ); -} diff --git a/packages/auth/src/routes/sessions-list.test.ts b/packages/auth/src/routes/sessions-list.test.ts deleted file mode 100644 index 4b823cc2..00000000 --- a/packages/auth/src/routes/sessions-list.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../../api/src/test/sqliteD1"; -import { handleSessionsList } from "./sessions-list"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -// Real SQLite with every auth migration applied: the listing is a SQL filter -// (revoked / expired / other users excluded) plus the `current` flag mapping. -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../migrations", import.meta.url)); - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000, sid: "sess-current" }; - -function makeEnv() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const now = Date.now(); - const user = sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, 'U', 'x', datetime('now'))"); - user.run("user-1", "a@example.com"); - user.run("user-2", "b@example.com"); - const session = sqlite.prepare( - "INSERT INTO sessions (id, user_id, created_at, expires_at, last_used_at, device_kind, client_label, ip, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - ); - session.run("sess-current", "user-1", now - 5000, now + 60_000, now - 100, "desktop", "Firefox on Linux", "203.0.113.1", null); - session.run("sess-other", "user-1", now - 9000, now + 60_000, now - 2000, null, null, null, null); - session.run("sess-revoked", "user-1", now - 9000, now + 60_000, now - 50, null, null, null, now - 10); - session.run("sess-expired", "user-1", now - 9000, now - 1, now - 40, null, null, null, null); - session.run("sess-someone-else", "user-2", now - 9000, now + 60_000, now - 30, null, null, null, null); - return { env: { DB: db } as unknown as Parameters[1], now }; -} - -function req() { - return new Request("http://localhost/sessions/list", { - headers: { Authorization: "Bearer t" }, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleSessionsList", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - const res = await handleSessionsList(req(), env); - expect(res.status).toBe(401); - }); - - it("lists only the caller's live sessions, most recent first, flagging the current one", async () => { - const { env, now } = makeEnv(); - const res = await handleSessionsList(req(), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { sessions: unknown[] } }; - expect(json.ok).toBe(true); - expect(json.data.sessions).toEqual([ - { - id: "sess-current", createdAt: now - 5000, lastUsedAt: now - 100, expiresAt: now + 60_000, - deviceKind: "desktop", clientLabel: "Firefox on Linux", ip: "203.0.113.1", current: true, - }, - { - id: "sess-other", createdAt: now - 9000, lastUsedAt: now - 2000, expiresAt: now + 60_000, - deviceKind: null, clientLabel: null, ip: null, current: false, - }, - ]); - }); -}); diff --git a/packages/auth/src/routes/sessions-list.ts b/packages/auth/src/routes/sessions-list.ts deleted file mode 100644 index 9a4923ab..00000000 --- a/packages/auth/src/routes/sessions-list.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse } from "../lib"; -import { listActiveSessions } from "../sessions"; -import type { Env } from "../index"; - -export async function handleSessionsList(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const sessions = await listActiveSessions(env, session.userId, session.sid); - return okResponse({ sessions }); -} diff --git a/packages/auth/src/routes/sessions-logout.test.ts b/packages/auth/src/routes/sessions-logout.test.ts deleted file mode 100644 index 1b937efb..00000000 --- a/packages/auth/src/routes/sessions-logout.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleSessionsLogout } from "./sessions-logout"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../sessions", () => ({ - revokeSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { revokeSession } from "../sessions"; - -// Always-denying limiter: logout must never consult it (see the handler -// comment), so every passing test below doubles as proof it doesn't. -const limit = vi.fn().mockResolvedValue({ success: false }); -const env = { DB: {}, RATE_LIMITER_AUTH: { limit } } as unknown as Parameters[1]; - -function req() { - return new Request("http://localhost/sessions/logout", { - method: "POST", - headers: { Authorization: "Bearer t" }, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(revokeSession).mockResolvedValue(true); -}); - -describe("handleSessionsLogout", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleSessionsLogout(req(), env); - expect(res.status).toBe(401); - expect(revokeSession).not.toHaveBeenCalled(); - }); - - it("revokes the caller's own current session, never rate limited - the best-effort client swallow must not leave the session alive", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue({ - userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000, sid: "sess-current", - }); - const res = await handleSessionsLogout(req(), env); - expect(res.status).toBe(200); - expect(revokeSession).toHaveBeenCalledWith(env, "sess-current", "user-1"); - expect(limit).not.toHaveBeenCalled(); - }); - - it("is a no-op revoke when the session has no sid (still 200)", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue({ - userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000, - }); - const res = await handleSessionsLogout(req(), env); - expect(res.status).toBe(200); - expect(revokeSession).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/auth/src/routes/sessions-logout.ts b/packages/auth/src/routes/sessions-logout.ts deleted file mode 100644 index 26c618b6..00000000 --- a/packages/auth/src/routes/sessions-logout.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse } from "../lib"; -import { revokeSession } from "../sessions"; -import type { Env } from "../index"; - -export async function handleSessionsLogout(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // Deliberately NOT rate limited. Logout is self-limiting - a successful call - // revokes the very session that authenticated it, so replays fail auth - and - // the client fires it best-effort and ignores the result, so a 429 here would - // silently leave the server-side session alive: the exact outcome this - // endpoint exists to prevent. - if (session.sid) await revokeSession(env, session.sid, session.userId); - return okResponse({}); -} diff --git a/packages/auth/src/routes/sessions-revoke-others.test.ts b/packages/auth/src/routes/sessions-revoke-others.test.ts deleted file mode 100644 index 09bf5378..00000000 --- a/packages/auth/src/routes/sessions-revoke-others.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleSessionsRevokeOthers } from "./sessions-revoke-others"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../sessions", () => ({ - revokeAllSessions: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { revokeAllSessions } from "../sessions"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000, sid: "sess-current" }; - -// Always-denying limiter: the panic button must never consult it (see the -// handler comment), so every passing test below doubles as proof it doesn't. -const limit = vi.fn().mockResolvedValue({ success: false }); -const env = { DB: {}, RATE_LIMITER_AUTH: { limit } } as unknown as Parameters[1]; - -function req() { - return new Request("http://localhost/sessions/revoke-others", { - method: "POST", - headers: { Authorization: "Bearer t" }, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(revokeAllSessions).mockResolvedValue(undefined); -}); - -describe("handleSessionsRevokeOthers", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleSessionsRevokeOthers(req(), env); - expect(res.status).toBe(401); - expect(revokeAllSessions).not.toHaveBeenCalled(); - }); - - it("is never rate limited - a stolen session must not be able to block the panic button", async () => { - const res = await handleSessionsRevokeOthers(req(), env); - expect(res.status).toBe(200); - expect(revokeAllSessions).toHaveBeenCalledWith(env, "user-1", "sess-current"); - expect(limit).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/auth/src/routes/sessions-revoke-others.ts b/packages/auth/src/routes/sessions-revoke-others.ts deleted file mode 100644 index 1068c98f..00000000 --- a/packages/auth/src/routes/sessions-revoke-others.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse } from "../lib"; -import { revokeAllSessions } from "../sessions"; -import type { Env } from "../index"; - -export async function handleSessionsRevokeOthers(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // Deliberately NOT rate limited. This is the panic button for a compromised - // account: a fail-closed per-user limit would let an attacker holding a - // stolen session keep the bucket exhausted and block the victim from revoking - // them. Spamming it buys an attacker nothing (it only revokes sessions), and - // the handler is a single cheap D1 statement. - await revokeAllSessions(env, session.userId, session.sid); - return okResponse({}); -} diff --git a/packages/auth/src/routes/sessions-revoke.test.ts b/packages/auth/src/routes/sessions-revoke.test.ts deleted file mode 100644 index d73e7491..00000000 --- a/packages/auth/src/routes/sessions-revoke.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleSessionsRevoke } from "./sessions-revoke"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../sessions", () => ({ - revokeSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { revokeSession } from "../sessions"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000, sid: "sess-current" }; - -const limit = vi.fn().mockResolvedValue({ success: true }); -const env = { DB: {}, RATE_LIMITER_AUTH: { limit } } as unknown as Parameters[1]; - -function req(body: unknown) { - return new Request("http://localhost/sessions/revoke", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(revokeSession).mockResolvedValue(true); -}); - -describe("handleSessionsRevoke", () => { - it("rejects a missing sessionId before touching auth", async () => { - const res = await handleSessionsRevoke(req({}), env); - expect(res.status).toBe(400); - expect(requireAuthenticatedSession).not.toHaveBeenCalled(); - }); - - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const res = await handleSessionsRevoke(req({ sessionId: "sess-x" }), env); - expect(res.status).toBe(401); - expect(revokeSession).not.toHaveBeenCalled(); - }); - - it("revokes the targeted session scoped to the caller", async () => { - const res = await handleSessionsRevoke(req({ sessionId: "sess-x" }), env); - expect(res.status).toBe(200); - expect(revokeSession).toHaveBeenCalledWith(env, "sess-x", "user-1"); - }); - - it("returns 429 without revoking when the user limit is exceeded", async () => { - limit.mockResolvedValueOnce({ success: false }); - const res = await handleSessionsRevoke(req({ sessionId: "sess-x" }), env); - expect(res.status).toBe(429); - // Own bucket - shared with no other route, so nothing else can starve it. - expect(limit).toHaveBeenCalledWith({ key: "sessions-revoke:user-1" }); - expect(revokeSession).not.toHaveBeenCalled(); - }); - - it("returns 404 when nothing was revoked (not the caller's session)", async () => { - vi.mocked(revokeSession).mockResolvedValue(false); - const res = await handleSessionsRevoke(req({ sessionId: "sess-foreign" }), env); - expect(res.status).toBe(404); - }); -}); diff --git a/packages/auth/src/routes/sessions-revoke.ts b/packages/auth/src/routes/sessions-revoke.ts deleted file mode 100644 index 347ea8d8..00000000 --- a/packages/auth/src/routes/sessions-revoke.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors, rateLimitUser } from "../lib"; -import { revokeSession } from "../sessions"; -import type { Env } from "../index"; - -export async function handleSessionsRevoke(request: Request, env: Env): Promise { - const body = await request.json<{ sessionId?: string }>(); - if (!body.sessionId) return errorResponse(Errors.BAD_REQUEST); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // Own bucket (not shared with any other route) so nothing can starve it; if - // it does run dry, /sessions/revoke-others stays available as the unthrottled - // escape hatch - see the comment there before rate-limiting that route. - const limited = await rateLimitUser(env.RATE_LIMITER_AUTH, `sessions-revoke:${session.userId}`); - if (limited) return limited; - - const ok = await revokeSession(env, body.sessionId, session.userId); - if (!ok) return errorResponse(Errors.NOT_FOUND); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/stripe-webhook.test.ts b/packages/auth/src/routes/stripe-webhook.test.ts deleted file mode 100644 index 6fb89858..00000000 --- a/packages/auth/src/routes/stripe-webhook.test.ts +++ /dev/null @@ -1,370 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleStripeWebhook } from "./stripe-webhook"; - -vi.mock("../stripe-client", () => ({ - getStripe: vi.fn(), - getStripeWebhookCryptoProvider: vi.fn().mockReturnValue({}), -})); - -import { getStripe } from "../stripe-client"; - -interface MockDB { - prepare: ReturnType; - _runResults: Array<{ meta: { changes: number } } | Error>; - _bindCalls: unknown[][]; - _statements: string[]; -} - -// Returns a sequence-aware D1 mock. Each call to .run() returns the next -// object from `runResults` (default: { meta: { changes: 1 } }); an Error -// entry makes that .run() reject (simulates a transient D1 failure). -// `.first()` always resolves to `firstResult` - used by the idempotency -// dedup check (null/undefined = not yet processed, truthy = duplicate). -function makeDB( - runResults: Array<{ meta: { changes: number } } | Error> = [], - firstResult: unknown = null, -): MockDB { - const _runResults = runResults; - const _bindCalls: unknown[][] = []; - const _statements: string[] = []; - let runIndex = 0; - - const prepare = vi.fn((sql: string) => { - _statements.push(sql); - return { - bind: (...args: unknown[]) => { - _bindCalls.push(args); - return { - run: vi.fn().mockImplementation(() => { - const result = _runResults[runIndex] ?? { meta: { changes: 1 } }; - runIndex += 1; - if (result instanceof Error) return Promise.reject(result); - return Promise.resolve(result); - }), - first: vi.fn().mockImplementation(() => Promise.resolve(firstResult)), - }; - }, - }; - }); - - return { prepare, _runResults, _bindCalls, _statements }; -} - -function makeEnv(db: MockDB) { - return { - DB: db, - STRIPE_SECRET_KEY: "sk_test_xxx", - STRIPE_WEBHOOK_SECRET: "whsec_xxx", - } as unknown as Parameters[1]; -} - -function makeRequest(body: string, sig = "valid-sig") { - return new Request("http://localhost/stripe/webhook", { - method: "POST", - headers: { "stripe-signature": sig, "content-type": "application/json" }, - body, - }); -} - -// subscriptions.retrieve returns the live subscription; by default it matches -// the event payload, `liveSub` overrides it (e.g. a stale event). -function mockConstructEvent(event: unknown, liveSub?: unknown) { - const evObj = (event as { data?: { object?: unknown } } | null)?.data?.object; - vi.mocked(getStripe).mockReturnValue({ - webhooks: { - constructEventAsync: vi.fn().mockResolvedValue(event), - }, - subscriptions: { - retrieve: vi.fn().mockResolvedValue(liveSub ?? evObj), - }, - } as unknown as ReturnType); -} - -beforeEach(() => { - vi.clearAllMocks(); -}); - -describe("handleStripeWebhook - signature + idempotency", () => { - it("returns 400 when stripe-signature header is missing", async () => { - const db = makeDB(); - const req = new Request("http://localhost/stripe/webhook", { - method: "POST", - headers: { "content-type": "application/json" }, - body: "{}", - }); - const res = await handleStripeWebhook(req, makeEnv(db)); - expect(res.status).toBe(400); - }); - - it("returns 400 on bad signature", async () => { - vi.mocked(getStripe).mockReturnValue({ - webhooks: { - constructEventAsync: vi.fn().mockRejectedValue(new Error("bad sig")), - }, - } as unknown as ReturnType); - - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(400); - }); - - it("acknowledges duplicate events without processing", async () => { - mockConstructEvent({ id: "evt_1", type: "customer.subscription.updated", data: { object: { id: "sub_1", metadata: {} } } }); - // dedup SELECT returns a row → already processed - const db = makeDB([], { seen: 1 }); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - // Only the dedup lookup should have run - no handler, no marker write - expect(db._statements.length).toBe(1); - expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); - }); -}); - -describe("handleStripeWebhook - checkout.session.completed", () => { - it("links customer + subscription IDs to the user", async () => { - mockConstructEvent({ - id: "evt_2", - type: "checkout.session.completed", - data: { - object: { - id: "cs_1", - client_reference_id: "user-1", - customer: "cus_abc", - subscription: "sub_xyz", - }, - }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - - expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); - expect(db._statements[1]).toContain("INSERT INTO user_billing"); - expect(db._statements[1]).toContain("stripe_customer_id"); - expect(db._statements[1]).toContain("stripe_subscription_id"); - // bind args for the user_billing upsert: userId, customerId, subId - expect(db._bindCalls[1]).toEqual(["user-1", "cus_abc", "sub_xyz"]); - // marker recorded only after the handler succeeded - expect(db._statements[2]).toContain("INSERT OR IGNORE INTO webhook_events"); - }); - - it("ignores events missing client_reference_id", async () => { - mockConstructEvent({ - id: "evt_3", - type: "checkout.session.completed", - data: { object: { id: "cs_2", customer: "cus_abc", subscription: "sub_xyz" } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - // dedup lookup + post-success marker; no user_billing write (no-op) - expect(db._statements.length).toBe(2); - expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); - expect(db._statements[1]).toContain("INSERT OR IGNORE INTO webhook_events"); - }); -}); - -describe("handleStripeWebhook - customer.subscription.created/updated", () => { - const event = { - id: "evt_4", - type: "customer.subscription.created", - data: { - object: { - id: "sub_1", - customer: "cus_1", - status: "active", - metadata: { userId: "user-1" }, - items: { - data: [{ current_period_end: 1_700_000_000 }], - }, - }, - }, - }; - - it("upserts plan, status, period_end, started_at via COALESCE", async () => { - mockConstructEvent(event); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - - expect(db._statements[1]).toContain("INSERT INTO user_billing"); - expect(db._statements[1]).toContain("personal_plan"); - expect(db._statements[1]).toContain("COALESCE(user_billing.personal_plan_started_at"); - - const args = db._bindCalls[1]; - expect(args[0]).toBe("user-1"); // user id (now leads since it's the upsert key) - expect(args[1]).toBe("cus_1"); // customerId - expect(args[2]).toBe("sub_1"); // subscriptionId - expect(args[3]).toBe("ink"); // plan - expect(args[4]).toBe("active"); // status - expect(args[5]).toBe(1_700_000_000_000); // period end (ms) - expect(args[6]).toBeNull(); // cancel_at (null when no cancellation pending) - // args[7] is now (Date.now()) - just check it's a number - expect(typeof args[7]).toBe("number"); - }); - - it("captures cancel_at when subscription is set to cancel at period end", () => { - mockConstructEvent({ - ...event, - data: { - object: { - ...event.data.object, - cancel_at: 1_750_000_000, - cancel_at_period_end: true, - }, - }, - }); - const db = makeDB(); - return handleStripeWebhook(makeRequest("{}"), makeEnv(db)).then(() => { - const args = db._bindCalls[1]; - expect(args[6]).toBe(1_750_000_000_000); // cancel_at in ms (now position 6 - userId leads) - }); - }); - - it("ignores subscription events missing metadata.userId", async () => { - mockConstructEvent({ - ...event, - data: { object: { ...event.data.object, metadata: {} } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - // dedup lookup + post-success marker; no user_billing write (no-op) - expect(db._statements.length).toBe(2); - expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); - expect(db._statements[1]).toContain("INSERT OR IGNORE INTO webhook_events"); - }); - - it("a stale 'active' event whose live subscription is canceled does NOT re-grant Ink", async () => { - // subscription.deleted was processed first; this created/updated arrives late. - mockConstructEvent(event, { ...event.data.object, status: "canceled" }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - expect(db._statements.some(s => s.includes("INSERT INTO user_billing"))).toBe(false); - expect(db._statements[1]).toContain("personal_plan = NULL"); - expect(db._bindCalls[1]).toEqual(["user-1", "sub_1"]); - }); - - it("persists the live status, not the event snapshot", async () => { - mockConstructEvent(event, { ...event.data.object, status: "past_due" }); - const db = makeDB(); - await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(db._bindCalls[1][4]).toBe("past_due"); - }); - - // Price-binding guard: when STRIPE_INK_PRICE_ID is configured, only a - // subscription on that price may grant Ink. - function makeEnvWithInkPrice(db: MockDB, priceId: string) { - return { ...makeEnv(db), STRIPE_INK_PRICE_ID: priceId } as Parameters[1]; - } - - it("grants Ink when a subscription item matches the configured Ink price", async () => { - mockConstructEvent({ - ...event, - data: { object: { ...event.data.object, items: { data: [{ price: { id: "price_ink" }, current_period_end: 1_700_000_000 }] } } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnvWithInkPrice(db, "price_ink")); - expect(res.status).toBe(200); - expect(db._statements[1]).toContain("INSERT INTO user_billing"); - expect(db._bindCalls[1][3]).toBe("ink"); - }); - - it("does NOT grant Ink for a subscription on a different price", async () => { - mockConstructEvent({ - ...event, - data: { object: { ...event.data.object, items: { data: [{ price: { id: "price_other_cheaper" }, current_period_end: 1_700_000_000 }] } } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnvWithInkPrice(db, "price_ink")); - expect(res.status).toBe(200); - // No user_billing write - only dedup lookup + post-success marker. - expect(db._statements.length).toBe(2); - expect(db._statements.some(s => s.includes("INSERT INTO user_billing"))).toBe(false); - }); -}); - -describe("handleStripeWebhook - customer.subscription.deleted", () => { - it("clears plan + sub id, sets status canceled", async () => { - mockConstructEvent({ - id: "evt_5", - type: "customer.subscription.deleted", - data: { object: { id: "sub_1", customer: "cus_1", metadata: { userId: "user-1" } } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - - expect(db._statements[1]).toContain("personal_plan = NULL"); - expect(db._statements[1]).toContain("'canceled'"); - // Guarded on the subscription on record, so a late deletion of an old - // subscription can't cancel a newer one. - expect(db._statements[1]).toContain("(stripe_subscription_id IS NULL OR stripe_subscription_id = ?)"); - expect(db._bindCalls[1]).toEqual(["user-1", "sub_1"]); - }); -}); - -describe("handleStripeWebhook - invoice events", () => { - it("invoice.payment_failed flips status to past_due", async () => { - mockConstructEvent({ - id: "evt_6", - type: "invoice.payment_failed", - data: { object: { id: "in_1", subscription: "sub_1", lines: { data: [] } } }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - - expect(db._statements[1]).toContain("'past_due'"); - expect(db._bindCalls[1]).toEqual(["sub_1"]); - }); - - it("invoice.paid sets status active and refreshes period_end", async () => { - mockConstructEvent({ - id: "evt_7", - type: "invoice.paid", - data: { - object: { - id: "in_2", - subscription: "sub_1", - lines: { data: [{ period: { end: 1_800_000_000 } }] }, - }, - }, - }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - - expect(db._statements[1]).toContain("'active'"); - expect(db._bindCalls[1]).toEqual([1_800_000_000_000, "sub_1"]); - }); -}); - -describe("handleStripeWebhook - idempotency ordering on failure", () => { - const deletedEvent = { - id: "evt_fail", - type: "customer.subscription.deleted", - data: { object: { id: "sub_1", customer: "cus_1", metadata: { userId: "user-1" } } }, - }; - - it("returns 500 and does NOT record the event when the handler throws", async () => { - mockConstructEvent(deletedEvent); - // The handler's UPDATE rejects (transient D1 failure). - const db = makeDB([new Error("d1 unavailable")]); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(500); - // No idempotency marker written → Stripe's redelivery will reprocess. - expect(db._statements.some(s => s.includes("INSERT OR IGNORE INTO webhook_events"))).toBe(false); - }); - - it("records the marker only after the handler succeeds", async () => { - mockConstructEvent({ ...deletedEvent, id: "evt_ok" }); - const db = makeDB(); - const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); - expect(res.status).toBe(200); - expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); - // Last statement is the post-success idempotency marker. - expect(db._statements[db._statements.length - 1]).toContain("INSERT OR IGNORE INTO webhook_events"); - }); -}); diff --git a/packages/auth/src/routes/stripe-webhook.ts b/packages/auth/src/routes/stripe-webhook.ts deleted file mode 100644 index 1c987595..00000000 --- a/packages/auth/src/routes/stripe-webhook.ts +++ /dev/null @@ -1,278 +0,0 @@ -import type Stripe from "stripe"; -import { Errors, errorResponse } from "../lib"; -import { getStripe, getStripeWebhookCryptoProvider } from "../stripe-client"; -import type { Env } from "../index"; - -// POST /stripe/webhook -// -// Public endpoint, signature-verified. Bad-signature requests get 400. -// Logical no-ops (event references an unknown user, unsubscribed event -// type, etc.) are acknowledged with 200 - retrying won't help and the -// event is genuinely unprocessable. A *thrown* handler error returns 500 -// so Stripe redelivers; transient failures (a D1 blip) must not be -// silently dropped. -// -// Idempotency: we record event.id in webhook_events only AFTER the -// handler succeeds, and skip early when that row already exists. Stripe -// replays events during outages: a replay after a successful handle is a -// no-op, while a replay after a FAILED handle still reprocesses because -// the marker was never written. -export async function handleStripeWebhook(request: Request, env: Env): Promise { - if (!env.STRIPE_SECRET_KEY || !env.STRIPE_WEBHOOK_SECRET) { - console.error("Stripe webhook reached but STRIPE_SECRET_KEY or STRIPE_WEBHOOK_SECRET is unset"); - return errorResponse(Errors.INTERNAL); - } - - const sig = request.headers.get("stripe-signature"); - if (!sig) return errorResponse(Errors.BAD_REQUEST); - - // MUST read raw body before any .json() - signature is over the bytes. - const rawBody = await request.text(); - - const stripe = getStripe(env.STRIPE_SECRET_KEY); - let event: Stripe.Event; - try { - event = await stripe.webhooks.constructEventAsync( - rawBody, - sig, - env.STRIPE_WEBHOOK_SECRET, - undefined, - getStripeWebhookCryptoProvider(), - ); - } catch (err) { - console.error("Stripe webhook signature verification failed:", err); - return errorResponse(Errors.BAD_REQUEST); - } - - // Idempotency: skip if we've already fully processed this event id. - // The marker is written only after the handler succeeds (below), so a - // failed attempt leaves no row and Stripe's redelivery reprocesses. - const alreadyProcessed = await env.DB.prepare( - "SELECT 1 FROM webhook_events WHERE event_id = ?", - ).bind(event.id).first(); - if (alreadyProcessed) { - return new Response("ok", { status: 200 }); - } - - try { - switch (event.type) { - case "checkout.session.completed": - await handleCheckoutCompleted(env, event.data.object as Stripe.Checkout.Session); - break; - case "customer.subscription.created": - case "customer.subscription.updated": - await handleSubscriptionUpsert(env, event.data.object as Stripe.Subscription); - break; - case "customer.subscription.deleted": - await handleSubscriptionDeleted(env, event.data.object as Stripe.Subscription); - break; - case "invoice.payment_failed": - await handleInvoicePaymentFailed(env, event.data.object as Stripe.Invoice); - break; - case "invoice.paid": - await handleInvoicePaid(env, event.data.object as Stripe.Invoice); - break; - default: - // Unsubscribed event types are fine - Stripe sends what it's - // configured to send. Just acknowledge and move on. - break; - } - } catch (err) { - // Most handler failures are transient (a D1 hiccup, a brief blip). - // We have NOT recorded this event as processed, so 500 and let Stripe - // redeliver - the retry reprocesses cleanly. A deterministic handler - // bug will retry uselessly for Stripe's retry window then give up, - // which is still far better than silently and permanently dropping a - // billing state change. - console.error(`Stripe webhook handler for ${event.type} failed:`, err); - return errorResponse(Errors.INTERNAL); - } - - // Handler succeeded - record the event so any later replay is a no-op. - await env.DB.prepare( - "INSERT OR IGNORE INTO webhook_events (event_id, type, processed_at) VALUES (?, ?, ?)", - ).bind(event.id, event.type, Date.now()).run(); - - return new Response("ok", { status: 200 }); -} - -// checkout.session.completed: links the Stripe customer + subscription -// IDs to our user row. The actual plan flip happens on the subsequent -// customer.subscription.created event. -async function handleCheckoutCompleted(env: Env, sessionObj: Stripe.Checkout.Session): Promise { - const userId = sessionObj.client_reference_id; - if (!userId) { - console.warn("checkout.session.completed missing client_reference_id", sessionObj.id); - return; - } - const customerId = typeof sessionObj.customer === "string" ? sessionObj.customer : sessionObj.customer?.id ?? null; - const subscriptionId = typeof sessionObj.subscription === "string" ? sessionObj.subscription : sessionObj.subscription?.id ?? null; - - if (!customerId) return; - - // The two COALESCE clauses are intentionally asymmetric (preserved from - // pre-split behavior, see migration 0023): - // - stripe_customer_id: prefer the EXISTING value. Once we've linked a - // customer, it should never get overwritten by a later checkout (e.g. a - // duplicate/replayed event), since a different customer id would - // orphan all subsequent invoice lookups. - // - stripe_subscription_id: prefer the INCOMING value. A new checkout - // means a new subscription; the old sub id (if any) is by definition - // stale at this point. - await env.DB.prepare( - `INSERT INTO user_billing (user_id, stripe_customer_id, stripe_subscription_id) - VALUES (?, ?, ?) - ON CONFLICT(user_id) DO UPDATE SET - stripe_customer_id = COALESCE(user_billing.stripe_customer_id, excluded.stripe_customer_id), - stripe_subscription_id = COALESCE(excluded.stripe_subscription_id, user_billing.stripe_subscription_id)`, - ).bind(userId, customerId, subscriptionId).run(); -} - -// customer.subscription.created/updated: source of truth for plan, -// status, and period end. We resolve the user by metadata.userId -// (stamped during Checkout) so this works even if it arrives before -// checkout.session.completed. -async function handleSubscriptionUpsert(env: Env, eventSub: Stripe.Subscription): Promise { - // Stripe doesn't guarantee delivery order, and a failed delivery is retried - // later - so a stale created/updated (status active) can land AFTER - // subscription.deleted and would re-grant Ink forever. Persist the live - // subscription state, never the event snapshot. A retrieve failure throws, - // which 500s and lets Stripe redeliver. - const sub = await getStripe(env.STRIPE_SECRET_KEY).subscriptions.retrieve(eventSub.id); - if (sub.status === "canceled" || sub.status === "incomplete_expired") { - await handleSubscriptionDeleted(env, sub); - return; - } - - const userId = sub.metadata?.userId; - if (!userId) { - console.warn("subscription event missing metadata.userId", sub.id); - return; - } - - // Bind the Ink grant to the actual product purchased. Without this, ANY - // priced subscription carrying metadata.userId (a future second product, a - // sub created out-of-band on a different price) would flip the user to Ink. - // Only the configured Ink price grants the plan. (A promo/100%-off code on - // the Ink price itself still counts - that's a legitimate Ink subscription.) - const inkPriceId = env.STRIPE_INK_PRICE_ID; - if (inkPriceId && !sub.items.data.some(item => item.price?.id === inkPriceId)) { - console.warn(`subscription ${sub.id} for user ${userId} is not the Ink price; not granting Ink`); - return; - } - - const customerId = typeof sub.customer === "string" ? sub.customer : sub.customer.id; - // Stripe moved current_period_end from the subscription to per-item in - // newer api versions. Try both - older SDK type defs still expose it - // on Subscription, newer payloads only have it on items. - const periodEnd = - (sub as unknown as { current_period_end?: number }).current_period_end - ?? (sub.items.data[0] as unknown as { current_period_end?: number } | undefined)?.current_period_end - ?? null; - const status = sub.status; - const plan = "ink"; - const now = Date.now(); - - // sub.cancel_at is populated when the user has scheduled a - // cancel-at-period-end via Customer Portal; null when not pending or - // when they've resumed. Status remains 'active' until Stripe actually - // transitions to canceled (which fires subscription.deleted). - const cancelAt = sub.cancel_at ? sub.cancel_at * 1000 : null; - - // Only set personal_plan_started_at if it's not already populated - - // preserves the original supporter date across cancel/resub cycles. - await env.DB.prepare( - `INSERT INTO user_billing ( - user_id, stripe_customer_id, stripe_subscription_id, - personal_plan, personal_plan_status, personal_period_end, - personal_plan_cancel_at, personal_plan_started_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(user_id) DO UPDATE SET - stripe_customer_id = excluded.stripe_customer_id, - stripe_subscription_id = excluded.stripe_subscription_id, - personal_plan = excluded.personal_plan, - personal_plan_status = excluded.personal_plan_status, - personal_period_end = excluded.personal_period_end, - personal_plan_cancel_at = excluded.personal_plan_cancel_at, - personal_plan_started_at = COALESCE(user_billing.personal_plan_started_at, excluded.personal_plan_started_at)`, - ).bind( - userId, - customerId, - sub.id, - plan, - status, - periodEnd ? periodEnd * 1000 : null, - cancelAt, - now, - ).run(); -} - -// customer.subscription.deleted: clear plan + status. Keep -// stripe_customer_id and personal_plan_started_at so a resubscribe -// preserves the supporter-since date. -async function handleSubscriptionDeleted(env: Env, sub: Stripe.Subscription): Promise { - const userId = sub.metadata?.userId; - if (!userId) return; - - // Only clear the plan when this is the subscription on record (or none is): - // a late deletion of an OLD subscription must not cancel a newer one. - await env.DB.prepare( - `UPDATE user_billing - SET personal_plan = NULL, - personal_plan_status = 'canceled', - personal_period_end = NULL, - personal_plan_cancel_at = NULL, - stripe_subscription_id = NULL - WHERE user_id = ? AND (stripe_subscription_id IS NULL OR stripe_subscription_id = ?)`, - ).bind(userId, sub.id).run(); -} - -// invoice.payment_failed: flip status to past_due. The plan resolver -// keeps perks active during past_due so users get a grace period; the -// frontend banners them to update their payment method. -async function handleInvoicePaymentFailed(env: Env, invoice: Stripe.Invoice): Promise { - const subscriptionId = extractSubscriptionId(invoice); - if (!subscriptionId) return; - - await env.DB.prepare( - `UPDATE user_billing - SET personal_plan_status = 'past_due' - WHERE stripe_subscription_id = ?`, - ).bind(subscriptionId).run(); -} - -// invoice.paid: confirm active status and refresh period_end. This is -// also the renewal heartbeat - fired every billing cycle on success. -async function handleInvoicePaid(env: Env, invoice: Stripe.Invoice): Promise { - const subscriptionId = extractSubscriptionId(invoice); - if (!subscriptionId) return; - - // invoice.lines exposes the period the invoice covers; the latest - // line's period.end is the new period_end. - const lastPeriodEnd = invoice.lines.data - .map(l => l.period?.end ?? 0) - .reduce((a, b) => Math.max(a, b), 0); - - await env.DB.prepare( - `UPDATE user_billing - SET personal_plan_status = 'active', - personal_period_end = ? - WHERE stripe_subscription_id = ?`, - ).bind(lastPeriodEnd ? lastPeriodEnd * 1000 : null, subscriptionId).run(); -} - -// Stripe types put `subscription` in different places across Invoice -// shapes / api versions; this normalizes it to a string id or null. -function extractSubscriptionId(invoice: Stripe.Invoice): string | null { - const direct = (invoice as unknown as { subscription?: string | { id: string } | null }).subscription; - if (typeof direct === "string") return direct; - if (direct && typeof direct === "object" && "id" in direct) return direct.id; - - // Newer api versions may put it on the parent.subscription_details: - const parent = (invoice as unknown as { parent?: { subscription_details?: { subscription?: string | { id: string } } } }).parent; - const fromParent = parent?.subscription_details?.subscription; - if (typeof fromParent === "string") return fromParent; - if (fromParent && typeof fromParent === "object" && "id" in fromParent) return fromParent.id; - - return null; -} diff --git a/packages/auth/src/routes/totp-backup-codes-generate.test.ts b/packages/auth/src/routes/totp-backup-codes-generate.test.ts deleted file mode 100644 index 69077747..00000000 --- a/packages/auth/src/routes/totp-backup-codes-generate.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleTotpBackupCodesGenerate } from "./totp-backup-codes-generate"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), - hashCode: vi.fn(async (c: string) => `hash:${c}`), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA, hashCode } from "../mfa"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(row: { totp_secret: string | null } | null) { - const run = vi.fn().mockResolvedValue({}); - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ run, first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Parameters[1], prepare, bind, run }; -} - -function req(body: unknown) { - return new Request("http://localhost/totp/backup-codes/generate", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue(null as never); - vi.mocked(hashCode).mockImplementation(async (c: string) => `hash:${c}`); -}); - -describe("handleTotpBackupCodesGenerate", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpBackupCodesGenerate(req({ totpCode: "123456" }), env); - expect(res.status).toBe(401); - }); - - it("rejects when TOTP isn't enabled", async () => { - const { env, run } = makeEnv({ totp_secret: null }); - const res = await handleTotpBackupCodesGenerate(req({ totpCode: "123456" }), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("totp_not_enabled"); - expect(run).not.toHaveBeenCalled(); - }); - - it("propagates an MFA failure without regenerating", async () => { - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 401 }) as never, - ); - const { env, run } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpBackupCodesGenerate(req({}), env); - expect(res.status).toBe(401); - expect(run).not.toHaveBeenCalled(); - }); - - it("returns 8 fresh codes and hashes each before storing", async () => { - const { env, run } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpBackupCodesGenerate(req({ totpCode: "123456" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { codes: string[] } }; - expect(json.data.codes).toHaveLength(8); - // each plaintext code looks like XXXXX-XXXXX - for (const c of json.data.codes) expect(c).toMatch(/^[A-Z0-9]{5}-[A-Z0-9]{5}$/); - // plaintext is hashed, never stored raw - expect(hashCode).toHaveBeenCalledTimes(8); - // 1 DELETE + 8 INSERTs - expect(run).toHaveBeenCalledTimes(9); - }); -}); diff --git a/packages/auth/src/routes/totp-backup-codes-generate.ts b/packages/auth/src/routes/totp-backup-codes-generate.ts deleted file mode 100644 index 1dc24ab1..00000000 --- a/packages/auth/src/routes/totp-backup-codes-generate.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { requireMFA, hashCode } from "../mfa"; -import type { Env } from "../index"; - -const CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; - -function generateCode(): string { - const bytes = crypto.getRandomValues(new Uint8Array(10)); - let result = ""; - for (let i = 0; i < 10; i++) { - result += CHARSET[bytes[i] % CHARSET.length]; - if (i === 4) result += "-"; - } - return result; -} - -export async function handleTotpBackupCodesGenerate(request: Request, env: Env): Promise { - const body = await request.json<{ - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare( - "SELECT totp_secret FROM users WHERE id = ?", - ).bind(session.userId).first<{ totp_secret: string | null }>(); - - if (!user) return errorResponse(Errors.UNAUTHORIZED); - if (!user.totp_secret) return Response.json({ ok: false, error: "totp_not_enabled" }, { status: 400 }); - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - // Delete all existing backup codes - await env.DB.prepare("DELETE FROM backup_codes WHERE user_id = ?").bind(session.userId).run(); - - // Generate 8 new codes - const codes: string[] = []; - const inserts: Promise[] = []; - - for (let i = 0; i < 8; i++) { - const code = generateCode(); - codes.push(code); - const id = crypto.randomUUID(); - const hash = await hashCode(code); - inserts.push( - env.DB.prepare( - "INSERT INTO backup_codes (id, user_id, code_hash) VALUES (?, ?, ?)", - ).bind(id, session.userId, hash).run(), - ); - } - - await Promise.all(inserts); - - return okResponse({ codes }); -} diff --git a/packages/auth/src/routes/totp-disable.test.ts b/packages/auth/src/routes/totp-disable.test.ts deleted file mode 100644 index 34b6c381..00000000 --- a/packages/auth/src/routes/totp-disable.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleTotpDisable } from "./totp-disable"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA } from "../mfa"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(row: { totp_secret: string | null } | null) { - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ first }); - const updateBind = vi.fn().mockReturnValue({}); - const deleteBind = vi.fn().mockReturnValue({}); - const prepare = vi.fn() - .mockReturnValueOnce({ bind }) - .mockReturnValueOnce({ bind: updateBind }) - .mockReturnValueOnce({ bind: deleteBind }); - const batch = vi.fn().mockResolvedValue([]); - const env = { DB: { prepare, batch } } as unknown as Parameters[1]; - return { env, prepare, updateBind, deleteBind, batch }; -} - -function req(body: unknown) { - return new Request("http://localhost/totp/disable", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue(null as never); -}); - -describe("handleTotpDisable", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpDisable(req({ totpCode: "123456" }), env); - expect(res.status).toBe(401); - }); - - it("returns 404 when the user is gone", async () => { - const { env } = makeEnv(null); - const res = await handleTotpDisable(req({ totpCode: "123456" }), env); - expect(res.status).toBe(404); - }); - - it("rejects when TOTP isn't enabled", async () => { - const { env, batch } = makeEnv({ totp_secret: null }); - const res = await handleTotpDisable(req({ totpCode: "123456" }), env); - expect(res.status).toBe(400); - expect(batch).not.toHaveBeenCalled(); - }); - - it("propagates an MFA failure without clearing the secret", async () => { - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 401 }) as never, - ); - const { env, batch } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpDisable(req({}), env); - expect(res.status).toBe(401); - expect(batch).not.toHaveBeenCalled(); - }); - - it("atomically clears the TOTP state and its recovery codes on valid MFA", async () => { - const { env, batch, updateBind, deleteBind, prepare } = makeEnv({ totp_secret: "S" }); - const res = await handleTotpDisable(req({ totpCode: "123456" }), env); - expect(res.status).toBe(200); - expect(batch).toHaveBeenCalledOnce(); - expect(batch.mock.calls[0][0]).toHaveLength(2); - expect(updateBind).toHaveBeenCalledWith("user-1"); - expect(deleteBind).toHaveBeenCalledWith("user-1"); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("totp_secret = NULL")); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("totp_last_used_step = NULL")); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("DELETE FROM backup_codes")); - }); -}); diff --git a/packages/auth/src/routes/totp-disable.ts b/packages/auth/src/routes/totp-disable.ts deleted file mode 100644 index 8255836e..00000000 --- a/packages/auth/src/routes/totp-disable.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { requireMFA } from "../mfa"; -import type { Env } from "../index"; - -export async function handleTotpDisable(request: Request, env: Env): Promise { - const body = await request.json<{ - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare( - "SELECT totp_secret FROM users WHERE id = ?", - ).bind(session.userId).first<{ totp_secret: string | null }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - if (!user.totp_secret) return errorResponse(Errors.BAD_REQUEST); - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - // Clear the replay guard and invalidate every recovery code from this TOTP - // enrollment. D1 batch executes atomically, so the old codes can never be - // resurrected by a disable/re-enable sequence. - await env.DB.batch([ - env.DB.prepare("UPDATE users SET totp_secret = NULL, totp_last_used_step = NULL WHERE id = ?") - .bind(session.userId), - env.DB.prepare("DELETE FROM backup_codes WHERE user_id = ?") - .bind(session.userId), - ]); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/totp-enable.test.ts b/packages/auth/src/routes/totp-enable.test.ts deleted file mode 100644 index c7bb560b..00000000 --- a/packages/auth/src/routes/totp-enable.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleTotpEnable } from "./totp-enable"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../totp", () => ({ - verifyTOTP: vi.fn(), -})); -vi.mock("../mfa", () => ({ - requireEnrollmentStepUp: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { verifyTOTP } from "../totp"; -import { requireEnrollmentStepUp } from "../mfa"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(row: { totp_secret: string | null } | null) { - const run = vi.fn().mockResolvedValue({}); - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ run, first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Parameters[1], prepare, bind, run }; -} - -function req(body: unknown) { - return new Request("http://localhost/totp/enable", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireEnrollmentStepUp).mockResolvedValue(null as never); - vi.mocked(verifyTOTP).mockResolvedValue(true); -}); - -describe("handleTotpEnable", () => { - it("rejects a body missing secret/code", async () => { - const { env } = makeEnv({ totp_secret: null }); - const res = await handleTotpEnable(req({ secret: "S" }), env); - expect(res.status).toBe(400); - }); - - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv({ totp_secret: null }); - const res = await handleTotpEnable(req({ secret: "S", code: "123456" }), env); - expect(res.status).toBe(401); - }); - - it("refuses to re-enable when TOTP is already on", async () => { - const { env } = makeEnv({ totp_secret: "EXISTING" }); - const res = await handleTotpEnable(req({ secret: "S", code: "123456" }), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("totp_already_enabled"); - }); - - it("propagates an MFA challenge failure", async () => { - vi.mocked(requireEnrollmentStepUp).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 401 }) as never, - ); - const { env, run } = makeEnv({ totp_secret: null }); - const res = await handleTotpEnable(req({ secret: "S", code: "123456" }), env); - expect(res.status).toBe(401); - expect(run).not.toHaveBeenCalled(); - }); - - it("rejects an invalid enrollment code", async () => { - vi.mocked(verifyTOTP).mockResolvedValue(false); - const { env, run } = makeEnv({ totp_secret: null }); - const res = await handleTotpEnable(req({ secret: "S", code: "000000" }), env); - expect(res.status).toBe(401); - expect(run).not.toHaveBeenCalled(); - }); - - it("enables TOTP and persists the secret on a valid code", async () => { - const { env, run, bind } = makeEnv({ totp_secret: null }); - const res = await handleTotpEnable(req({ secret: "NEWSECRET", code: "123456" }), env); - expect(res.status).toBe(200); - expect(run).toHaveBeenCalledOnce(); - expect(bind).toHaveBeenLastCalledWith("NEWSECRET", "user-1"); - }); - - it("passes current password and recovery-code step-up to first-factor enrollment", async () => { - const { env } = makeEnv({ totp_secret: null }); - await handleTotpEnable(req({ - secret: "NEWSECRET", - code: "123456", - currentPassword: "current-password", - backupCode: "ABCD-1234", - }), env); - - expect(requireEnrollmentStepUp).toHaveBeenCalledWith(env, "user-1", expect.objectContaining({ - currentPassword: "current-password", - backupCode: "ABCD-1234", - })); - }); -}); diff --git a/packages/auth/src/routes/totp-enable.ts b/packages/auth/src/routes/totp-enable.ts deleted file mode 100644 index 4e8bf5b7..00000000 --- a/packages/auth/src/routes/totp-enable.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { verifyTOTP } from "../totp"; -import { requireEnrollmentStepUp } from "../mfa"; -import type { Env } from "../index"; - -export async function handleTotpEnable(request: Request, env: Env): Promise { - const body = await request.json<{ - secret: string; - code: string; - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - currentPassword?: string; - }>(); - if (!body.secret || !body.code) return errorResponse(Errors.BAD_REQUEST); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const existing = await env.DB.prepare( - "SELECT totp_secret FROM users WHERE id = ?", - ).bind(session.userId).first<{ totp_secret: string | null }>(); - if (!existing) return errorResponse(Errors.NOT_FOUND); - - if (existing.totp_secret) { - return Response.json({ ok: false, error: "totp_already_enabled" }, { status: 400 }); - } - - const mfaError = await requireEnrollmentStepUp(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - currentPassword: body.currentPassword, - }); - if (mfaError) return mfaError; - - // Plain verify - the enrollment code's step is deliberately NOT consumed, so - // the user can enable TOTP and sign in within the same 30s code window. The - // login path's replay guard starts consuming from the first login onward. - const valid = await verifyTOTP(body.secret, body.code); - if (!valid) return errorResponse(Errors.UNAUTHORIZED); - - await env.DB.prepare("UPDATE users SET totp_secret = ?, totp_last_used_step = NULL WHERE id = ?") - .bind(body.secret, session.userId) - .run(); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/totp-setup.test.ts b/packages/auth/src/routes/totp-setup.test.ts deleted file mode 100644 index fe861f8a..00000000 --- a/packages/auth/src/routes/totp-setup.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleTotpSetup } from "./totp-setup"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../totp", () => ({ - generateSecret: vi.fn(() => "GENERATEDSECRET"), - buildOtpauthUri: vi.fn(() => "otpauth://totp/Annex:test@example.com?secret=GENERATEDSECRET"), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { generateSecret, buildOtpauthUri } from "../totp"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(row: { email: string } | null) { - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Parameters[1], prepare, bind }; -} - -function req() { - return new Request("http://localhost/totp/setup", { method: "POST", headers: { Authorization: "Bearer t" } }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(generateSecret).mockReturnValue("GENERATEDSECRET"); - vi.mocked(buildOtpauthUri).mockReturnValue("otpauth://totp/Annex:test@example.com?secret=GENERATEDSECRET"); -}); - -describe("handleTotpSetup", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv({ email: "test@example.com" }); - const res = await handleTotpSetup(req(), env); - expect(res.status).toBe(401); - }); - - it("returns 404 when the user is gone", async () => { - const { env } = makeEnv(null); - const res = await handleTotpSetup(req(), env); - expect(res.status).toBe(404); - }); - - it("returns a fresh secret + otpauth uri bound to the user's email", async () => { - const { env } = makeEnv({ email: "test@example.com" }); - const res = await handleTotpSetup(req(), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { secret: string; uri: string } }; - expect(json.data.secret).toBe("GENERATEDSECRET"); - expect(json.data.uri).toContain("otpauth://"); - expect(buildOtpauthUri).toHaveBeenCalledWith("GENERATEDSECRET", "test@example.com"); - }); -}); diff --git a/packages/auth/src/routes/totp-setup.ts b/packages/auth/src/routes/totp-setup.ts deleted file mode 100644 index d2db6a90..00000000 --- a/packages/auth/src/routes/totp-setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { generateSecret, buildOtpauthUri } from "../totp"; -import type { Env } from "../index"; - -export async function handleTotpSetup(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare("SELECT email FROM users WHERE id = ?") - .bind(session.userId) - .first<{ email: string }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - const secret = generateSecret(); - const uri = buildOtpauthUri(secret, user.email); - - return okResponse({ secret, uri }); -} diff --git a/packages/auth/src/routes/totp-status.test.ts b/packages/auth/src/routes/totp-status.test.ts deleted file mode 100644 index f5d89360..00000000 --- a/packages/auth/src/routes/totp-status.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleTotpStatus } from "./totp-status"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(row: { totp_secret: string | null } | null) { - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Parameters[1], prepare, bind }; -} - -function req() { - return new Request("http://localhost/totp/status", { headers: { Authorization: "Bearer t" } }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleTotpStatus", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv({ totp_secret: null }); - const res = await handleTotpStatus(req(), env); - expect(res.status).toBe(401); - }); - - it("returns 404 when the user is gone", async () => { - const { env } = makeEnv(null); - const res = await handleTotpStatus(req(), env); - expect(res.status).toBe(404); - }); - - it("reports enabled:false when no secret is stored", async () => { - const { env } = makeEnv({ totp_secret: null }); - const res = await handleTotpStatus(req(), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { enabled: boolean } }; - expect(json.data.enabled).toBe(false); - }); - - it("reports enabled:true when a secret is stored", async () => { - const { env } = makeEnv({ totp_secret: "SECRET" }); - const res = await handleTotpStatus(req(), env); - const json = (await res.json()) as { data: { enabled: boolean } }; - expect(json.data.enabled).toBe(true); - }); -}); diff --git a/packages/auth/src/routes/totp-status.ts b/packages/auth/src/routes/totp-status.ts deleted file mode 100644 index daacdad3..00000000 --- a/packages/auth/src/routes/totp-status.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; - -export async function handleTotpStatus(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare("SELECT totp_secret FROM users WHERE id = ?") - .bind(session.userId) - .first<{ totp_secret: string | null }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - return okResponse({ enabled: user.totp_secret !== null }); -} diff --git a/packages/auth/src/routes/update-bio.test.ts b/packages/auth/src/routes/update-bio.test.ts deleted file mode 100644 index 61983c95..00000000 --- a/packages/auth/src/routes/update-bio.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateBio } from "./update-bio"; -import type { PlanRow } from "../plan"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -const inkRow: PlanRow = { - granted_plan: "ink", - granted_plan_expires_at: null, - granted_plan_started_at: 1, - personal_plan: null, - personal_plan_status: null, - personal_plan_started_at: null, - personal_plan_cancel_at: null, - personal_plan_style: null, - personal_presence_color: null, - personal_crit_sparkles: null, -}; - -const freeRow: PlanRow = { ...inkRow, granted_plan: null, granted_plan_started_at: null }; - -// The handler calls .first() for the plan-gate query and .run() for the upsert, -// both off the same prepare().bind() chain, so the chain exposes both. -function makeEnv(planRow: PlanRow | null) { - const first = vi.fn().mockResolvedValue(planRow); - const run = vi.fn().mockResolvedValue({}); - const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - first, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-bio", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleUpdateBio", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(inkRow); - const res = await handleUpdateBio(req({ bio: "hello" }), env); - expect(res.status).toBe(401); - }); - - it("rejects a body without a bio field", async () => { - const { env, prepare } = makeEnv(inkRow); - const res = await handleUpdateBio(req({}), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a bio over the length cap", async () => { - const { env } = makeEnv(inkRow); - const res = await handleUpdateBio(req({ bio: "x".repeat(281) }), env); - expect(res.status).toBe(400); - }); - - it("returns 403 for a free (non-Ink) user", async () => { - const { env, run } = makeEnv(freeRow); - const res = await handleUpdateBio(req({ bio: "supporter" }), env); - expect(res.status).toBe(403); - expect(run).not.toHaveBeenCalled(); - }); - - it("returns 404 when the user row is missing", async () => { - const { env } = makeEnv(null); - const res = await handleUpdateBio(req({ bio: "supporter" }), env); - expect(res.status).toBe(404); - }); - - it("writes a trimmed bio for an Ink user", async () => { - const { env, run, bind } = makeEnv(inkRow); - const res = await handleUpdateBio(req({ bio: " My bio " }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { bio: string | null } }; - expect(json.data.bio).toBe("My bio"); - expect(run).toHaveBeenCalledOnce(); - expect(bind).toHaveBeenLastCalledWith("user-1", "My bio"); - }); - - it("treats an empty/whitespace bio as a clear (null)", async () => { - const { env, bind } = makeEnv(inkRow); - const res = await handleUpdateBio(req({ bio: " " }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { bio: string | null } }; - expect(json.data.bio).toBeNull(); - expect(bind).toHaveBeenLastCalledWith("user-1", null); - }); - - it("treats explicit null as a clear", async () => { - const { env, bind } = makeEnv(inkRow); - const res = await handleUpdateBio(req({ bio: null }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenLastCalledWith("user-1", null); - }); -}); diff --git a/packages/auth/src/routes/update-bio.ts b/packages/auth/src/routes/update-bio.ts deleted file mode 100644 index 7cc1ada3..00000000 --- a/packages/auth/src/routes/update-bio.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { resolvePersonalPlan } from "../plan"; -import type { Env } from "../index"; - -const MAX_BIO_LENGTH = 280; - -// PATCH the supporter bio. Pass `null` (or empty/whitespace string) to clear. -// -// Gated to active Ink plan via resolvePersonalPlan, mirroring update-ink-prefs: -// refusing here rather than just hiding the UI prevents a downgrade race -// (sub canceled mid-session, request submitted before JWT refresh) from -// silently writing. -export async function handleUpdateBio(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ bio?: string | null }>(); - if (!("bio" in body)) return errorResponse(Errors.BAD_REQUEST); - - let normalized: string | null; - if (body.bio === null) { - normalized = null; - } else if (typeof body.bio === "string") { - const trimmed = body.bio.trim(); - if (trimmed.length === 0) { - normalized = null; - } else if (trimmed.length > MAX_BIO_LENGTH) { - return errorResponse(Errors.BAD_REQUEST); - } else { - normalized = trimmed; - } - } else { - return errorResponse(Errors.BAD_REQUEST); - } - - const planRow = await env.DB.prepare( - `SELECT p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, - b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, - b.personal_plan_cancel_at, - b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at - FROM users u - LEFT JOIN user_billing b ON b.user_id = u.id - LEFT JOIN user_preferences p ON p.user_id = u.id - WHERE u.id = ?`, - ).bind(session.userId).first<{ - personal_plan: string | null; - personal_plan_status: string | null; - personal_plan_started_at: number | null; - personal_plan_cancel_at: number | null; - personal_plan_style: string | null; - personal_presence_color: string | null; - personal_crit_sparkles: number | null; - granted_plan: string | null; - granted_plan_expires_at: number | null; - granted_plan_started_at: number | null; - }>(); - if (!planRow) return errorResponse(Errors.NOT_FOUND); - - const resolved = resolvePersonalPlan(planRow); - if (resolved.plan !== "ink") return errorResponse(Errors.FORBIDDEN); - - await env.DB.prepare( - `INSERT INTO user_preferences (user_id, bio) VALUES (?, ?) - ON CONFLICT(user_id) DO UPDATE SET bio = excluded.bio`, - ).bind(session.userId, normalized).run(); - - return okResponse({ bio: normalized }); -} diff --git a/packages/auth/src/routes/update-handle.test.ts b/packages/auth/src/routes/update-handle.test.ts deleted file mode 100644 index 55b2ff3e..00000000 --- a/packages/auth/src/routes/update-handle.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../../api/src/test/sqliteD1"; -import { handleUpdateHandle } from "./update-handle"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -// Real SQLite with every auth migration applied, so uniqueness is the actual -// partial unique index from 0035 rather than a mocked error. -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../migrations", import.meta.url)); - -function makeEnv() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const user = sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, 'U', 'x', datetime('now'))"); - user.run("user-1", "a@example.com"); - user.run("user-2", "b@example.com"); - const handleOf = (userId: string) => - (sqlite.prepare("SELECT handle FROM user_preferences WHERE user_id = ?").get(userId) as { handle: string | null } | undefined)?.handle; - return { env: { DB: db } as unknown as Parameters[1], sqlite, handleOf }; -} - -function as(userId: string) { - vi.mocked(requireAuthenticatedSession).mockResolvedValue({ userId, email: `${userId}@example.com`, expiresAt: Date.now() + 3600_000 }); -} - -function req(body: unknown) { - return new Request("http://localhost/update-handle", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - as("user-1"); -}); - -describe("handleUpdateHandle", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - const res = await handleUpdateHandle(req({ handle: "someone" }), env); - expect(res.status).toBe(401); - }); - - it("rejects a body without a handle field", async () => { - const { env } = makeEnv(); - expect((await handleUpdateHandle(req({}), env)).status).toBe(400); - expect((await handleUpdateHandle(req({ handle: 42 }), env)).status).toBe(400); - }); - - it("rejects invalid and reserved handles with a reason, writing nothing", async () => { - const { env, handleOf } = makeEnv(); - for (const [handle, reason] of [["ab", "length"], ["bad name", "characters"], ["admin", "reserved"]] as const) { - const res = await handleUpdateHandle(req({ handle }), env); - expect(res.status, handle).toBe(400); - expect(((await res.json()) as { reason: string }).reason).toBe(reason); - } - expect(handleOf("user-1")).toBeUndefined(); - }); - - it("creates the satellite row and stores the normalized handle", async () => { - const { env, handleOf } = makeEnv(); - const res = await handleUpdateHandle(req({ handle: " @Cubity_First " }), env); - expect(res.status).toBe(200); - expect(((await res.json()) as { data: { handle: string } }).data.handle).toBe("cubity_first"); - expect(handleOf("user-1")).toBe("cubity_first"); - }); - - it("updates an existing preferences row without touching other columns", async () => { - const { env, sqlite, handleOf } = makeEnv(); - sqlite.prepare("INSERT INTO user_preferences (user_id, bio) VALUES ('user-1', 'hello')").run(); - await handleUpdateHandle(req({ handle: "first" }), env); - await handleUpdateHandle(req({ handle: "second" }), env); - expect(handleOf("user-1")).toBe("second"); - expect((sqlite.prepare("SELECT bio FROM user_preferences WHERE user_id = 'user-1'").get() as { bio: string }).bio).toBe("hello"); - }); - - it("re-saving your own handle is not a conflict", async () => { - const { env } = makeEnv(); - await handleUpdateHandle(req({ handle: "mine" }), env); - expect((await handleUpdateHandle(req({ handle: "MINE" }), env)).status).toBe(200); - }); - - it("returns 409 when another user holds the handle, case-insensitively", async () => { - const { env, handleOf } = makeEnv(); - await handleUpdateHandle(req({ handle: "taken" }), env); - as("user-2"); - const res = await handleUpdateHandle(req({ handle: "Taken" }), env); - expect(res.status).toBe(409); - expect(handleOf("user-2")).toBeUndefined(); - }); - - it("an admin lock blocks claiming, renaming and clearing (403 locked)", async () => { - const { env, sqlite, handleOf } = makeEnv(); - // Locked with no handle: the user can't claim one. - sqlite.prepare("INSERT INTO user_preferences (user_id, handle_locked) VALUES ('user-1', 1)").run(); - let res = await handleUpdateHandle(req({ handle: "wanted" }), env); - expect(res.status).toBe(403); - expect(((await res.json()) as { reason: string }).reason).toBe("locked"); - expect(handleOf("user-1")).toBeNull(); - - // Locked with an admin-assigned handle: can't rename or clear it. - sqlite.prepare("UPDATE user_preferences SET handle = 'official' WHERE user_id = 'user-1'").run(); - expect((await handleUpdateHandle(req({ handle: "other" }), env)).status).toBe(403); - expect((await handleUpdateHandle(req({ handle: null }), env)).status).toBe(403); - expect(handleOf("user-1")).toBe("official"); - }); - - it("the write itself re-checks the lock (lock lands after the pre-read)", async () => { - const { env, sqlite, handleOf } = makeEnv(); - sqlite.prepare("INSERT INTO user_preferences (user_id, handle) VALUES ('user-1', 'before')").run(); - // Simulate the admin lock landing between the handler's lock read and its - // write: the first SELECT sees unlocked, then the row flips to locked. - const realPrepare = env.DB.prepare.bind(env.DB); - let lockReads = 0; - (env.DB as unknown as { prepare: (sql: string) => D1PreparedStatement }).prepare = (sql: string) => { - if (sql.startsWith("SELECT handle_locked") && lockReads++ === 0) { - const stmt = realPrepare(sql); - return { - bind: (...args: unknown[]) => { - const bound = stmt.bind(...args); - return { - first: async () => { - const row = await bound.first(); - sqlite.prepare("UPDATE user_preferences SET handle_locked = 1 WHERE user_id = 'user-1'").run(); - return row; - }, - }; - }, - } as unknown as D1PreparedStatement; - } - return realPrepare(sql); - }; - const res = await handleUpdateHandle(req({ handle: "after" }), env); - expect(res.status).toBe(403); - expect(handleOf("user-1")).toBe("before"); - }); - - it("clearing (null or blank) releases the handle for someone else", async () => { - const { env, handleOf } = makeEnv(); - await handleUpdateHandle(req({ handle: "shared" }), env); - const res = await handleUpdateHandle(req({ handle: " " }), env); - expect(((await res.json()) as { data: { handle: null } }).data.handle).toBeNull(); - expect(handleOf("user-1")).toBeNull(); - - as("user-2"); - expect((await handleUpdateHandle(req({ handle: "shared" }), env)).status).toBe(200); - as("user-1"); - expect((await handleUpdateHandle(req({ handle: null }), env)).status).toBe(200); - }); -}); diff --git a/packages/auth/src/routes/update-handle.ts b/packages/auth/src/routes/update-handle.ts deleted file mode 100644 index bf371ef0..00000000 --- a/packages/auth/src/routes/update-handle.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors, isUniqueConstraintError } from "../lib"; -import { normalizeHandle, handleProblem } from "../handle"; -import type { Env } from "../index"; - -// Set or clear the caller's public profile handle (the opt-in `/@` -// link). `{ handle: null }` (or an empty string) turns the link off and -// releases the name. Not plan-gated. Refused (403, reason "locked") while an -// admin has locked the user's handle. -// -// Uniqueness is enforced by the partial unique index on -// user_preferences.handle (0035), so a concurrent claim of the same name loses -// with a 409 rather than racing a SELECT-then-write check. -export async function handleUpdateHandle(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - let body: { handle?: unknown }; - try { - body = await request.json<{ handle?: unknown }>(); - } catch { - return errorResponse(Errors.BAD_REQUEST); - } - if (!body || typeof body !== "object" || !("handle" in body)) return errorResponse(Errors.BAD_REQUEST); - - let handle: string | null; - if (body.handle === null) { - handle = null; - } else if (typeof body.handle === "string") { - const normalized = normalizeHandle(body.handle); - if (normalized.length === 0) { - handle = null; - } else { - const problem = handleProblem(normalized); - if (problem) { - return Response.json({ ok: false, ...Errors.BAD_REQUEST, reason: problem }, { status: 400 }); - } - handle = normalized; - } - } else { - return errorResponse(Errors.BAD_REQUEST); - } - - // Admin lock (0035 handle_locked): the user can't change their handle at - // all - neither claim one nor rename/clear an admin-assigned one. The - // guard is repeated inside each write's WHERE so a lock applied between - // this read and the write still wins. - if (await isLocked(env, session.userId)) return lockedResponse(); - - if (handle === null) { - // Clearing never needs to create a satellite row. Zero changes is normal - // (no row / already clear) unless a lock landed since the read above. - const res = await env.DB.prepare("UPDATE user_preferences SET handle = NULL WHERE user_id = ? AND handle_locked = 0") - .bind(session.userId).run(); - if (res.meta.changes === 0 && await isLocked(env, session.userId)) return lockedResponse(); - return okResponse({ handle: null }); - } - - let changes: number; - try { - const res = await env.DB.prepare( - `INSERT INTO user_preferences (user_id, handle) VALUES (?, ?) - ON CONFLICT(user_id) DO UPDATE SET handle = excluded.handle - WHERE user_preferences.handle_locked = 0`, - ).bind(session.userId, handle).run(); - changes = res.meta.changes; - } catch (err) { - if (isUniqueConstraintError(err)) return errorResponse(Errors.CONFLICT); - throw err; - } - // The upsert always touches one row unless the DO UPDATE's lock guard held. - if (changes === 0) return lockedResponse(); - - return okResponse({ handle }); -} - -async function isLocked(env: Env, userId: string): Promise { - const row = await env.DB.prepare("SELECT handle_locked FROM user_preferences WHERE user_id = ?") - .bind(userId).first<{ handle_locked: number }>(); - return !!row?.handle_locked; -} - -function lockedResponse(): Response { - return Response.json({ ok: false, ...Errors.FORBIDDEN, reason: "locked" }, { status: 403 }); -} diff --git a/packages/auth/src/routes/update-ink-prefs.test.ts b/packages/auth/src/routes/update-ink-prefs.test.ts deleted file mode 100644 index 3f37f22d..00000000 --- a/packages/auth/src/routes/update-ink-prefs.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateInkPrefs } from "./update-ink-prefs"; -import type { PlanRow } from "../plan"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -const inkRow: PlanRow = { - granted_plan: "ink", - granted_plan_expires_at: null, - granted_plan_started_at: 1, - personal_plan: null, - personal_plan_status: null, - personal_plan_started_at: null, - personal_plan_cancel_at: null, - personal_plan_style: null, - personal_presence_color: null, - personal_crit_sparkles: null, -}; - -const freeRow: PlanRow = { ...inkRow, granted_plan: null, granted_plan_started_at: null }; - -function makeEnv(planRow: PlanRow | null) { - const first = vi.fn().mockResolvedValue(planRow); - const run = vi.fn().mockResolvedValue({}); - const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - first, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-ink-prefs", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleUpdateInkPrefs", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); - expect(res.status).toBe(401); - }); - - it("rejects an empty body", async () => { - const { env, prepare } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({}), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a bogus ring style", async () => { - const { env } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({ style: "rainbow" }), env); - expect(res.status).toBe(400); - }); - - it("rejects a non-hex presence colour", async () => { - const { env } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({ presenceColor: "red" }), env); - expect(res.status).toBe(400); - }); - - it("rejects a non-boolean critSparkles", async () => { - const { env } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({ critSparkles: "yes" }), env); - expect(res.status).toBe(400); - }); - - it("returns 403 for a free (non-Ink) user", async () => { - const { env, run } = makeEnv(freeRow); - const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); - expect(res.status).toBe(403); - expect(run).not.toHaveBeenCalled(); - }); - - it("writes a valid style for an Ink user", async () => { - const { env, run, bind } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { style: string | null } }; - expect(json.data.style).toBe("aurora"); - expect(run).toHaveBeenCalledOnce(); - expect(bind).toHaveBeenLastCalledWith("user-1", "aurora"); - }); - - it("persists critSparkles as 0/1", async () => { - const { env, bind } = makeEnv(inkRow); - await handleUpdateInkPrefs(req({ critSparkles: false }), env); - expect(bind).toHaveBeenLastCalledWith("user-1", 0); - }); - - it("writes all three prefs together", async () => { - const { env, bind } = makeEnv(inkRow); - const res = await handleUpdateInkPrefs( - req({ style: "ember", presenceColor: "#aabbcc", critSparkles: true }), - env, - ); - expect(res.status).toBe(200); - expect(bind).toHaveBeenLastCalledWith("user-1", "ember", "#aabbcc", 1); - }); -}); diff --git a/packages/auth/src/routes/update-ink-prefs.ts b/packages/auth/src/routes/update-ink-prefs.ts deleted file mode 100644 index 5b2f8ff4..00000000 --- a/packages/auth/src/routes/update-ink-prefs.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { resolvePersonalPlan, isInkRingStyle, isInkPresenceColor } from "../plan"; -import type { Env } from "../index"; - -// Patch Ink supporter cosmetic prefs: ring style + presence colour. Both -// fields are optional in the body; pass `null` to reset back to default -// (NULL on the row means "use the deterministic default" - see plan.ts). -// -// Gated on the caller having an active Ink plan via resolvePersonalPlan, so -// expired-grant or canceled-paid users can't keep tweaking. Refusing here -// rather than just hiding the UI in the frontend stops a pre-emptive -// downgrade race (sub canceled mid-session, user submits update before the -// JWT refresh) from silently writing. -export async function handleUpdateInkPrefs(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ style?: string | null; presenceColor?: string | null; critSparkles?: boolean | null }>(); - - if (!("style" in body) && !("presenceColor" in body) && !("critSparkles" in body)) return errorResponse(Errors.BAD_REQUEST); - - if ("style" in body && body.style !== null && !isInkRingStyle(body.style)) { - return errorResponse(Errors.BAD_REQUEST); - } - if ("presenceColor" in body && body.presenceColor !== null && !isInkPresenceColor(body.presenceColor)) { - return errorResponse(Errors.BAD_REQUEST); - } - if ("critSparkles" in body && body.critSparkles !== null && typeof body.critSparkles !== "boolean") { - return errorResponse(Errors.BAD_REQUEST); - } - - const planRow = await env.DB.prepare( - `SELECT p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, - b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, - b.personal_plan_cancel_at, - b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at - FROM users u - LEFT JOIN user_billing b ON b.user_id = u.id - LEFT JOIN user_preferences p ON p.user_id = u.id - WHERE u.id = ?`, - ).bind(session.userId).first<{ - personal_plan: string | null; - personal_plan_status: string | null; - personal_plan_started_at: number | null; - personal_plan_cancel_at: number | null; - personal_plan_style: string | null; - personal_presence_color: string | null; - personal_crit_sparkles: number | null; - granted_plan: string | null; - granted_plan_expires_at: number | null; - granted_plan_started_at: number | null; - }>(); - if (!planRow) return errorResponse(Errors.NOT_FOUND); - - const resolved = resolvePersonalPlan(planRow); - if (resolved.plan !== "ink") return errorResponse(Errors.FORBIDDEN); - - // Upsert only the touched columns into user_preferences (see update-reading-font.ts - // for the same pattern). - const cols: string[] = []; - const placeholders: string[] = []; - const updates: string[] = []; - const values: unknown[] = []; - if ("style" in body) { - cols.push("personal_plan_style"); placeholders.push("?"); - updates.push("personal_plan_style = excluded.personal_plan_style"); - values.push(body.style ?? null); - } - if ("presenceColor" in body) { - cols.push("personal_presence_color"); placeholders.push("?"); - updates.push("personal_presence_color = excluded.personal_presence_color"); - values.push(body.presenceColor ?? null); - } - if ("critSparkles" in body) { - cols.push("personal_crit_sparkles"); placeholders.push("?"); - updates.push("personal_crit_sparkles = excluded.personal_crit_sparkles"); - // NULL means "use the default" (on). Persist 0/1 for explicit values. - values.push(body.critSparkles === null ? null : body.critSparkles ? 1 : 0); - } - - await env.DB.prepare( - `INSERT INTO user_preferences (user_id, ${cols.join(", ")}) VALUES (?, ${placeholders.join(", ")}) - ON CONFLICT(user_id) DO UPDATE SET ${updates.join(", ")}`, - ).bind(session.userId, ...values).run(); - - return okResponse({ - style: "style" in body ? (body.style ?? null) : resolved.style, - presenceColor: "presenceColor" in body ? (body.presenceColor ?? null) : resolved.presenceColor, - critSparkles: "critSparkles" in body ? (body.critSparkles ?? true) : resolved.critSparkles, - }); -} diff --git a/packages/auth/src/routes/update-name.test.ts b/packages/auth/src/routes/update-name.test.ts deleted file mode 100644 index 08d9b98a..00000000 --- a/packages/auth/src/routes/update-name.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateName } from "./update-name"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(changes = 1) { - const run = vi.fn().mockResolvedValue({ meta: { changes } }); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-name", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleUpdateName", () => { - it("rejects an empty name before touching auth/DB", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateName(req({ name: " " }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a missing name", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateName(req({}), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env, prepare } = makeEnv(); - const res = await handleUpdateName(req({ name: "New Name" }), env); - expect(res.status).toBe(401); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a name longer than 100 chars", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateName(req({ name: "a".repeat(101) }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("writes a trimmed name and echoes it back", async () => { - const { env, prepare, bind } = makeEnv(); - const res = await handleUpdateName(req({ name: " Jane Doe " }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { name: string } }; - expect(json.ok).toBe(true); - expect(json.data.name).toBe("Jane Doe"); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("UPDATE users SET name")); - expect(bind).toHaveBeenCalledWith("Jane Doe", "user-1"); - }); - - it("returns 404 when no row was updated (user gone)", async () => { - const { env } = makeEnv(0); - const res = await handleUpdateName(req({ name: "Jane" }), env); - expect(res.status).toBe(404); - }); -}); diff --git a/packages/auth/src/routes/update-name.ts b/packages/auth/src/routes/update-name.ts deleted file mode 100644 index 53de18f6..00000000 --- a/packages/auth/src/routes/update-name.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; - -export async function handleUpdateName(request: Request, env: Env): Promise { - const body = await request.json<{ name: string }>(); - if (!body.name?.trim()) return errorResponse(Errors.BAD_REQUEST); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - if (typeof body.name !== "string" || body.name.trim().length === 0 || body.name.length > 100) { - return errorResponse(Errors.BAD_REQUEST); - } - - const result = await env.DB.prepare( - "UPDATE users SET name = ? WHERE id = ?", - ).bind(body.name.trim(), session.userId).run(); - - if (!result.meta.changes) return errorResponse(Errors.NOT_FOUND); - - return okResponse({ name: body.name.trim() }); -} diff --git a/packages/auth/src/routes/update-reading-font.test.ts b/packages/auth/src/routes/update-reading-font.test.ts deleted file mode 100644 index ac27bf8e..00000000 --- a/packages/auth/src/routes/update-reading-font.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateReadingFont } from "./update-reading-font"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv() { - const run = vi.fn().mockResolvedValue({}); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-reading-font", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleUpdateReadingFont", () => { - it("returns 401 when session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: "mono" }), env); - expect(res.status).toBe(401); - }); - - it("rejects empty body", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateReadingFont(req({}), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects bogus readingFont value", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: "comic-sans" }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects bogus editingFont value", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateReadingFont(req({ editingFont: "papyrus" }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("writes valid readingFont and returns echo", async () => { - const { env, prepare, run, bind } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: "dyslexic" }), env); - expect(res.status).toBe(200); - const json = await res.json() as { ok: boolean; data: { readingFont: string | null } }; - expect(json.ok).toBe(true); - expect(json.data.readingFont).toBe("dyslexic"); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("reading_font")); - // user_id leads (UPSERT key), then the column values - expect(bind).toHaveBeenCalledWith("user-1", "dyslexic"); - expect(run).toHaveBeenCalledOnce(); - }); - - it("writes both fields when both are present", async () => { - const { env, prepare, bind } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: "sans", editingFont: "mono" }), env); - expect(res.status).toBe(200); - const sql = prepare.mock.calls[0]?.[0] as string; - expect(sql).toContain("reading_font"); - expect(sql).toContain("editing_font"); - expect(bind).toHaveBeenCalledWith("user-1", "sans", "mono"); - }); - - it("writes uiFont when present", async () => { - const { env, prepare, bind } = makeEnv(); - const res = await handleUpdateReadingFont(req({ uiFont: "dyslexic" }), env); - expect(res.status).toBe(200); - expect(prepare.mock.calls[0]?.[0]).toContain("ui_font"); - expect(bind).toHaveBeenCalledWith("user-1", "dyslexic"); - }); - - it("rejects bogus uiFont value", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateReadingFont(req({ uiFont: "wingdings" }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("writes all three fields together", async () => { - const { env, bind } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: "sans", editingFont: "mono", uiFont: "dyslexic" }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("user-1", "sans", "mono", "dyslexic"); - }); - - it("treats null as a reset (NULL on the row)", async () => { - const { env, bind } = makeEnv(); - const res = await handleUpdateReadingFont(req({ readingFont: null }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("user-1", null); - }); -}); diff --git a/packages/auth/src/routes/update-reading-font.ts b/packages/auth/src/routes/update-reading-font.ts deleted file mode 100644 index ffc24d84..00000000 --- a/packages/auth/src/routes/update-reading-font.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { isFontChoice } from "../fonts"; -import type { Env } from "../index"; - -// Patch the user's prose-font choices for reading and editing modes. Both -// fields are optional in the body; pass `null` to reset to the default -// (NULL on the row → frontend falls back to the default sans stack). -// -// Unlike update-ink-prefs, this is NOT gated on the Ink plan - OpenDyslexic -// in particular is an accessibility feature, so every user can pick it. -export async function handleUpdateReadingFont(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ readingFont?: string | null; editingFont?: string | null; uiFont?: string | null }>(); - - if (!("readingFont" in body) && !("editingFont" in body) && !("uiFont" in body)) return errorResponse(Errors.BAD_REQUEST); - - if ("readingFont" in body && body.readingFont !== null && !isFontChoice(body.readingFont)) { - return errorResponse(Errors.BAD_REQUEST); - } - if ("editingFont" in body && body.editingFont !== null && !isFontChoice(body.editingFont)) { - return errorResponse(Errors.BAD_REQUEST); - } - if ("uiFont" in body && body.uiFont !== null && !isFontChoice(body.uiFont)) { - return errorResponse(Errors.BAD_REQUEST); - } - - // Build an upsert that only touches the columns the caller actually sent. - // INSERT supplies values for those columns (user_id always first); ON CONFLICT - // mirrors the same SET clause so existing rows aren't clobbered for unrelated - // pref columns. - const cols: string[] = []; - const placeholders: string[] = []; - const updates: string[] = []; - const values: unknown[] = []; - if ("readingFont" in body) { - cols.push("reading_font"); placeholders.push("?"); - updates.push("reading_font = excluded.reading_font"); - values.push(body.readingFont ?? null); - } - if ("editingFont" in body) { - cols.push("editing_font"); placeholders.push("?"); - updates.push("editing_font = excluded.editing_font"); - values.push(body.editingFont ?? null); - } - if ("uiFont" in body) { - cols.push("ui_font"); placeholders.push("?"); - updates.push("ui_font = excluded.ui_font"); - values.push(body.uiFont ?? null); - } - - await env.DB.prepare( - `INSERT INTO user_preferences (user_id, ${cols.join(", ")}) VALUES (?, ${placeholders.join(", ")}) - ON CONFLICT(user_id) DO UPDATE SET ${updates.join(", ")}`, - ).bind(session.userId, ...values).run(); - - return okResponse({ - readingFont: "readingFont" in body ? (body.readingFont ?? null) : undefined, - editingFont: "editingFont" in body ? (body.editingFont ?? null) : undefined, - uiFont: "uiFont" in body ? (body.uiFont ?? null) : undefined, - }); -} diff --git a/packages/auth/src/routes/update-theme.test.ts b/packages/auth/src/routes/update-theme.test.ts deleted file mode 100644 index a78bdf96..00000000 --- a/packages/auth/src/routes/update-theme.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateTheme } from "./update-theme"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const adminSession = { userId: "user-1", email: "a@example.com", expiresAt: Date.now() + 3600_000, isAdmin: true }; - -function makeEnv() { - const run = vi.fn().mockResolvedValue({}); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-theme", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(adminSession); -}); - -describe("handleUpdateTheme", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - expect((await handleUpdateTheme(req({ theme: "dark" }), env)).status).toBe(401); - }); - - // The admin / custom-theming gate intentionally lives in the API worker's - // PATCH /me/theme, NOT in this handler - so a non-admin session still writes - // here. This guards against the handler accidentally growing its own gate. - it("does not self-gate on admin (gate lives in the API worker's PATCH /me/theme)", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue({ ...adminSession, isAdmin: false }); - const { env, prepare } = makeEnv(); - const res = await handleUpdateTheme(req({ theme: "light" }), env); - expect(res.status).toBe(200); - expect(prepare).toHaveBeenCalled(); - }); - - it("rejects a missing / unknown theme", async () => { - const { env, prepare } = makeEnv(); - expect((await handleUpdateTheme(req({}), env)).status).toBe(400); - expect((await handleUpdateTheme(req({ theme: "solarized" }), env)).status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects custom without a valid #rrggbb colour", async () => { - const { env, prepare } = makeEnv(); - expect((await handleUpdateTheme(req({ theme: "custom" }), env)).status).toBe(400); - expect((await handleUpdateTheme(req({ theme: "custom", customColor: "teal" }), env)).status).toBe(400); - expect((await handleUpdateTheme(req({ theme: "custom", customColor: "#abc" }), env)).status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("writes dark and nulls the custom colour", async () => { - const { env, prepare, bind, run } = makeEnv(); - const res = await handleUpdateTheme(req({ theme: "dark" }), env); - expect(res.status).toBe(200); - const json = await res.json() as { ok: boolean; data: { theme: string; customColor: string | null } }; - expect(json.ok).toBe(true); - expect(json.data).toEqual({ theme: "dark", customColor: null }); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("theme_mode")); - expect(bind).toHaveBeenCalledWith("user-1", "dark", null); - expect(run).toHaveBeenCalledOnce(); - }); - - it("writes light and ignores any supplied colour", async () => { - const { env, bind } = makeEnv(); - const res = await handleUpdateTheme(req({ theme: "light", customColor: "#2e7d6b" }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("user-1", "light", null); - }); - - it("writes custom with a normalised (lower-cased) colour", async () => { - const { env, bind } = makeEnv(); - const res = await handleUpdateTheme(req({ theme: "custom", customColor: "#2E7D6B" }), env); - expect(res.status).toBe(200); - const json = await res.json() as { data: { theme: string; customColor: string | null } }; - expect(json.data).toEqual({ theme: "custom", customColor: "#2e7d6b" }); - expect(bind).toHaveBeenCalledWith("user-1", "custom", "#2e7d6b"); - }); -}); diff --git a/packages/auth/src/routes/update-theme.ts b/packages/auth/src/routes/update-theme.ts deleted file mode 100644 index 7a7e9eb2..00000000 --- a/packages/auth/src/routes/update-theme.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { isThemeMode, isHexColor } from "../theme"; -import type { Env } from "../index"; - -// Sets the user's site theme (dark / light / custom). Available to any -// authenticated user - callers are responsible for Flagship flag gating. -// -// `customColor` is only persisted for the 'custom' mode; any other mode nulls -// it so a stale colour doesn't linger and re-apply if the user flips back to -// custom later. Both columns are written every time (single radio on the UI), -// so no partial-column upsert juggling like update-reading-font. -export async function handleUpdateTheme(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ theme?: unknown; customColor?: unknown }>(); - - if (!isThemeMode(body.theme)) return errorResponse(Errors.BAD_REQUEST); - - let customColor: string | null = null; - if (body.theme === "custom") { - if (!isHexColor(body.customColor)) return errorResponse(Errors.BAD_REQUEST); - customColor = body.customColor.toLowerCase(); - } - - await env.DB.prepare( - `INSERT INTO user_preferences (user_id, theme_mode, theme_custom_color) VALUES (?, ?, ?) - ON CONFLICT(user_id) DO UPDATE SET theme_mode = excluded.theme_mode, theme_custom_color = excluded.theme_custom_color`, - ).bind(session.userId, body.theme, customColor).run(); - - return okResponse({ theme: body.theme, customColor }); -} diff --git a/packages/auth/src/routes/update-timezone.test.ts b/packages/auth/src/routes/update-timezone.test.ts deleted file mode 100644 index d4c4b0a6..00000000 --- a/packages/auth/src/routes/update-timezone.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleUpdateTimezone } from "./update-timezone"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv() { - const run = vi.fn().mockResolvedValue({}); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare } } as unknown as Parameters[1], - prepare, - bind, - run, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/update-timezone", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleUpdateTimezone", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env, prepare } = makeEnv(); - const res = await handleUpdateTimezone(req({ timezone: "Europe/London" }), env); - expect(res.status).toBe(401); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a non-string timezone", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateTimezone(req({ timezone: 42 }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects an unknown IANA zone", async () => { - const { env, prepare } = makeEnv(); - const res = await handleUpdateTimezone(req({ timezone: "Mars/Olympus_Mons" }), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("writes a valid IANA zone", async () => { - const { env, prepare, bind } = makeEnv(); - const res = await handleUpdateTimezone(req({ timezone: "Europe/London" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { timezone: string } }; - expect(json.data.timezone).toBe("Europe/London"); - expect(prepare).toHaveBeenCalledWith(expect.stringContaining("timezone")); - expect(bind).toHaveBeenCalledWith("user-1", "Europe/London"); - }); - - it("treats null as a reset", async () => { - const { env, bind } = makeEnv(); - const res = await handleUpdateTimezone(req({ timezone: null }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("user-1", null); - }); -}); diff --git a/packages/auth/src/routes/update-timezone.ts b/packages/auth/src/routes/update-timezone.ts deleted file mode 100644 index 2262602a..00000000 --- a/packages/auth/src/routes/update-timezone.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; - -export async function handleUpdateTimezone(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const body = await request.json<{ timezone: string | null }>(); - - if (body.timezone !== null) { - if (typeof body.timezone !== "string") return errorResponse(Errors.BAD_REQUEST); - try { - new Intl.DateTimeFormat("en-US", { timeZone: body.timezone }); - } catch { - return errorResponse(Errors.BAD_REQUEST); - } - } - - await env.DB.prepare( - `INSERT INTO user_preferences (user_id, timezone) VALUES (?, ?) - ON CONFLICT(user_id) DO UPDATE SET timezone = excluded.timezone`, - ).bind(session.userId, body.timezone).run(); - - return okResponse({ timezone: body.timezone }); -} diff --git a/packages/auth/src/routes/verify-email-resend.test.ts b/packages/auth/src/routes/verify-email-resend.test.ts deleted file mode 100644 index 332d7dac..00000000 --- a/packages/auth/src/routes/verify-email-resend.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleVerifyEmailResend } from "./verify-email-resend"; - -vi.mock("../verification", () => ({ - createVerificationToken: vi.fn(), -})); -vi.mock("../email", () => ({ - sendVerificationEmail: vi.fn(), -})); - -import { createVerificationToken } from "../verification"; -import { sendVerificationEmail } from "../email"; - -function makeEnv(row: { id: string } | null) { - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { DB: { prepare }, APP_ORIGIN: "https://app.example.com" } as unknown as Parameters[1], - prepare, - bind, - first, - }; -} - -function req(body: unknown) { - return new Request("http://localhost/verify-email/resend", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(createVerificationToken).mockResolvedValue("tok-123"); - vi.mocked(sendVerificationEmail).mockResolvedValue(undefined as never); -}); - -describe("handleVerifyEmailResend", () => { - it("returns {sent:true} without querying when no email is given (no enumeration)", async () => { - const { env, prepare } = makeEnv({ id: "user-1" }); - const res = await handleVerifyEmailResend(req({}), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { sent: boolean } }; - expect(json.data.sent).toBe(true); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("returns {sent:true} but sends nothing for an unknown/verified email", async () => { - const { env } = makeEnv(null); - const res = await handleVerifyEmailResend(req({ email: "ghost@example.com" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { sent: boolean } }; - expect(json.data.sent).toBe(true); - expect(sendVerificationEmail).not.toHaveBeenCalled(); - }); - - it("mints a token and emails an unverified user (normalizing the address)", async () => { - const { env, bind } = makeEnv({ id: "user-1" }); - const res = await handleVerifyEmailResend(req({ email: " Test@Example.com " }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("test@example.com"); - expect(createVerificationToken).toHaveBeenCalledWith(env, "user-1"); - expect(sendVerificationEmail).toHaveBeenCalledWith( - env, - "test@example.com", - "https://app.example.com/verify-email?token=tok-123", - ); - }); -}); diff --git a/packages/auth/src/routes/verify-email-resend.ts b/packages/auth/src/routes/verify-email-resend.ts deleted file mode 100644 index b0b2a576..00000000 --- a/packages/auth/src/routes/verify-email-resend.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { okResponse, normalizeEmail } from "../lib"; -import { createVerificationToken } from "../verification"; -import { sendVerificationEmail } from "../email"; -import type { Env } from "../index"; - -export async function handleVerifyEmailResend(request: Request, env: Env): Promise { - const body = await request.json<{ email?: string }>(); - - // Always return ok - don't leak whether an email exists or is already verified - if (!body.email || typeof body.email !== "string") return okResponse({ sent: true }); - - const email = normalizeEmail(body.email); - - const row = await env.DB.prepare( - "SELECT id FROM users WHERE email = ? AND email_verified = 0", - ).bind(email).first<{ id: string }>(); - - if (row) { - const token = await createVerificationToken(env, row.id); - const verifyUrl = `${env.APP_ORIGIN}/verify-email?token=${token}`; - await sendVerificationEmail(env, email, verifyUrl); - } - - return okResponse({ sent: true }); -} diff --git a/packages/auth/src/routes/verify-email.test.ts b/packages/auth/src/routes/verify-email.test.ts deleted file mode 100644 index 77aecdbd..00000000 --- a/packages/auth/src/routes/verify-email.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleVerifyEmail } from "./verify-email"; - -vi.mock("../verification", () => ({ - consumeVerificationToken: vi.fn(), -})); -vi.mock("../sessions", () => ({ - createSession: vi.fn(), - SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, -})); -vi.mock("../jwt", () => ({ - signJwt: vi.fn(), -})); -vi.mock("../email", () => ({ - sendEmailChangedNotice: vi.fn().mockResolvedValue(true), -})); -vi.mock("../stripe-client", () => ({ - syncStripeCustomerEmail: vi.fn().mockResolvedValue(undefined), -})); - -import { consumeVerificationToken } from "../verification"; -import { createSession } from "../sessions"; -import { signJwt } from "../jwt"; -import { sendEmailChangedNotice } from "../email"; -import { syncStripeCustomerEmail } from "../stripe-client"; - -const userRow = { id: "user-1", email: "test@example.com", name: "Test", created_at: "2026-01-01T00:00:00Z" }; - -// .run() for the UPDATE, then .first() for the SELECT, both off the same chain. -function makeEnv(row: typeof userRow | null) { - const run = vi.fn().mockResolvedValue({}); - const first = vi.fn().mockResolvedValue(row); - const bind = vi.fn().mockReturnValue({ run, first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare }, JWT_SECRET: "secret" } as unknown as Parameters[1], prepare, bind, run, first }; -} - -// Queue-based mock for the change-confirm path, where the SELECT and UPDATE -// need distinct results (and the UPDATE may reject on a UNIQUE violation). -function makeQueueEnv(opts: { userEmail: string | null; moderation?: number; updateError?: Error }) { - const bindCalls: unknown[][] = []; - const sqls: string[] = []; - const first = vi.fn().mockResolvedValue( - opts.userEmail !== null ? { email: opts.userEmail, moderation: opts.moderation ?? 0 } : null, - ); - const run = opts.updateError - ? vi.fn().mockRejectedValue(opts.updateError) - : vi.fn().mockResolvedValue({}); - const prepare = vi.fn((sql: string) => { - sqls.push(sql); - return { bind: vi.fn((...args: unknown[]) => { bindCalls.push(args); return { first, run }; }) }; - }); - return { env: { DB: { prepare }, JWT_SECRET: "secret" } as unknown as Parameters[1], prepare, sqls, bindCalls, run, first }; -} - -function req(body: unknown) { - return new Request("http://localhost/verify-email", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(consumeVerificationToken).mockResolvedValue({ userId: "user-1", email: null }); - vi.mocked(createSession).mockResolvedValue("sess-new"); - vi.mocked(signJwt).mockResolvedValue("signed.jwt.token"); -}); - -describe("handleVerifyEmail", () => { - it("rejects a missing token", async () => { - const { env, prepare } = makeEnv(userRow); - const res = await handleVerifyEmail(req({}), env); - expect(res.status).toBe(400); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("returns 400 for an invalid/expired token", async () => { - vi.mocked(consumeVerificationToken).mockResolvedValue(null); - // The dead-token lookup finds no row (unknown or GC'd token). - const { env } = makeEnv(null); - const res = await handleVerifyEmail(req({ token: "bad" }), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { ok: boolean; error: string }; - expect(json.error).toBe("invalid_or_expired_token"); - }); - - it("returns change_link_expired for a dead change token", async () => { - vi.mocked(consumeVerificationToken).mockResolvedValue(null); - // The dead-token lookup finds a consumed/expired row carrying a pending email. - const { env } = makeQueueEnv({ userEmail: "pending@example.com" }); - const res = await handleVerifyEmail(req({ token: "stale-change" }), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { ok: boolean; error: string }; - expect(json.error).toBe("change_link_expired"); - }); - - it("returns 404 when the user vanished after token consumption", async () => { - const { env } = makeEnv(null); - const res = await handleVerifyEmail(req({ token: "good" }), env); - expect(res.status).toBe(404); - }); - - it("marks the email verified and retires other signup links, but does NOT mint a session", async () => { - const { env, run, prepare } = makeEnv(userRow); - const res = await handleVerifyEmail(req({ token: "good" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { verified: boolean; token?: string; user?: unknown } }; - expect(json.data.verified).toBe(true); - // Resend hands a link to anyone who names an unverified address, so a - // session here would let bare mailbox access skip password + MFA. - expect(json.data.token).toBeUndefined(); - expect(json.data.user).toBeUndefined(); - expect(createSession).not.toHaveBeenCalled(); - expect(signJwt).not.toHaveBeenCalled(); - const sqls = prepare.mock.calls.map(c => c[0] as string); - expect(sqls.some(q => q.includes("UPDATE users SET email_verified = 1"))).toBe(true); - expect(sqls.some(q => q.includes("DELETE FROM email_verification_tokens WHERE user_id = ? AND email IS NULL"))).toBe(true); - expect(run).toHaveBeenCalled(); - }); - - describe("change-confirm tokens (token carries a pending email)", () => { - beforeEach(() => { - vi.mocked(consumeVerificationToken).mockResolvedValue({ userId: "user-1", email: "new@example.com" }); - }); - - it("applies the new email, notifies the old address, and does NOT mint a session", async () => { - const { env, sqls, bindCalls } = makeQueueEnv({ userEmail: "old@example.com" }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { ok: boolean; data: { verified: boolean; emailChanged: boolean; userId: string; email: string; token?: string; user?: unknown } }; - expect(json.data.emailChanged).toBe(true); - expect(json.data.userId).toBe("user-1"); - expect(json.data.email).toBe("new@example.com"); - // Deliberately no session: mailbox access must not bypass the - // password+MFA gate that protected the change request. - expect(json.data.token).toBeUndefined(); - expect(json.data.user).toBeUndefined(); - expect(createSession).not.toHaveBeenCalled(); - expect(signJwt).not.toHaveBeenCalled(); - - const updateIdx = sqls.findIndex(s => s.includes("UPDATE users SET email = ?")); - expect(updateIdx).toBeGreaterThanOrEqual(0); - expect(sqls[updateIdx]).toContain("email_verified = 1"); - expect(bindCalls[updateIdx][0]).toBe("new@example.com"); - expect(bindCalls[updateIdx][2]).toBe("user-1"); - - expect(sendEmailChangedNotice).toHaveBeenCalledWith(env, "old@example.com", "new@example.com"); - expect(syncStripeCustomerEmail).toHaveBeenCalledWith(env, "user-1", "new@example.com"); - }); - - it("returns 409 email_taken when the address was claimed before confirmation", async () => { - const { env } = makeQueueEnv({ userEmail: "old@example.com", updateError: new Error("UNIQUE constraint failed: users.email") }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(409); - const json = (await res.json()) as { ok: boolean; error: string }; - expect(json.error).toBe("email_taken"); - expect(sendEmailChangedNotice).not.toHaveBeenCalled(); - expect(syncStripeCustomerEmail).not.toHaveBeenCalled(); - }); - - it("returns 404 when the user vanished", async () => { - const { env } = makeQueueEnv({ userEmail: null }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(404); - }); - - it("refuses to apply for a disabled account", async () => { - const { env, run } = makeQueueEnv({ userEmail: "old@example.com", moderation: -1 }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(403); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("account_disabled"); - expect(run).not.toHaveBeenCalled(); - }); - - it("refuses to apply for a currently-suspended account", async () => { - const until = Math.floor(Date.now() / 1000) + 3600; - const { env, run } = makeQueueEnv({ userEmail: "old@example.com", moderation: until }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(403); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("account_suspended"); - expect(run).not.toHaveBeenCalled(); - }); - - it("applies normally once a past suspension has lapsed", async () => { - const lapsed = Math.floor(Date.now() / 1000) - 3600; - const { env } = makeQueueEnv({ userEmail: "old@example.com", moderation: lapsed }); - const res = await handleVerifyEmail(req({ token: "change" }), env); - expect(res.status).toBe(200); - }); - - it("rethrows a non-UNIQUE update failure instead of reporting email_taken", async () => { - const { env } = makeQueueEnv({ - userEmail: "old@example.com", - updateError: new Error("D1_ERROR: network timeout"), - }); - await expect(handleVerifyEmail(req({ token: "change" }), env)).rejects.toThrow("network timeout"); - expect(sendEmailChangedNotice).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/packages/auth/src/routes/verify-email.ts b/packages/auth/src/routes/verify-email.ts deleted file mode 100644 index cab8d918..00000000 --- a/packages/auth/src/routes/verify-email.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { okResponse, errorResponse, Errors, isUniqueConstraintError } from "../lib"; -import { consumeVerificationToken } from "../verification"; -import { sendEmailChangedNotice } from "../email"; -import { syncStripeCustomerEmail } from "../stripe-client"; -import type { Env } from "../index"; - -export async function handleVerifyEmail(request: Request, env: Env): Promise { - const body = await request.json<{ token?: string }>(); - if (!body.token) return errorResponse(Errors.BAD_REQUEST); - - const consumed = await consumeVerificationToken(env, body.token); - if (!consumed) { - // Dead change links (expired or already consumed - rows persist until the - // lazy GC) get a distinct error so the frontend can point the user back to - // Settings instead of offering the signup resend form, which can't help. - const dead = await env.DB.prepare( - "SELECT email FROM email_verification_tokens WHERE id = ?", - ).bind(body.token).first<{ email: string | null }>(); - if (dead && dead.email !== null) { - return Response.json({ ok: false, error: "change_link_expired" }, { status: 400 }); - } - return Response.json({ ok: false, error: "invalid_or_expired_token" }, { status: 400 }); - } - const { userId, email: pendingEmail } = consumed; - - // Change-confirm token: apply the pending new address. Deliberately does NOT - // mint a session - the link lands in a mailbox never before tied to the - // account, and a session here would let bare mailbox access bypass the - // password+MFA gate that protected the change request. - if (pendingEmail !== null) { - const user = await env.DB.prepare( - "SELECT email, moderation FROM users WHERE id = ?", - ).bind(userId).first<{ email: string; moderation: number }>(); - if (!user) return errorResponse(Errors.NOT_FOUND); - - // The request path was session-gated, but the account can have been - // moderated between request and confirm - don't let a disabled/suspended - // account keep mutating its identity via a pre-issued link. - if (user.moderation === -1) { - return Response.json({ ok: false, error: "account_disabled" }, { status: 403 }); - } - if (user.moderation > 0 && Math.floor(Date.now() / 1000) < user.moderation) { - return Response.json({ ok: false, error: "account_suspended" }, { status: 403 }); - } - - try { - await env.DB.prepare( - "UPDATE users SET email = ?, email_verified = 1, email_verified_at = ? WHERE id = ?", - ).bind(pendingEmail, new Date().toISOString(), userId).run(); - } catch (err) { - // Another account claimed the address between request and confirm. The - // token is already consumed - the user re-requests from settings. Any - // other error is a real failure, not "email taken." - if (!isUniqueConstraintError(err)) throw err; - return Response.json({ ok: false, error: "email_taken" }, { status: 409 }); - } - - await sendEmailChangedNotice(env, user.email, pendingEmail); - await syncStripeCustomerEmail(env, userId, pendingEmail); - - return okResponse({ verified: true, emailChanged: true, userId, email: pendingEmail }); - } - - // Signup-verify token. Like the change-confirm branch this deliberately does - // NOT mint a session: /verify-email/resend hands a fresh link to anyone who - // asks for an unverified address, so a session here would turn bare mailbox - // access into a login that skips the password and any TOTP/WebAuthn factor. - // The user signs in normally afterwards (the frontend shows "Go to sign in"). - const verified = await env.DB.prepare( - "UPDATE users SET email_verified = 1, email_verified_at = ? WHERE id = ? RETURNING id", - ).bind(new Date().toISOString(), userId).first<{ id: string }>(); - if (!verified) return errorResponse(Errors.NOT_FOUND); - - // Retire any other outstanding signup links for this account. - await env.DB.prepare( - "DELETE FROM email_verification_tokens WHERE user_id = ? AND email IS NULL", - ).bind(userId).run(); - - return okResponse({ verified: true }); -} diff --git a/packages/auth/src/routes/verify.ts b/packages/auth/src/routes/verify.ts deleted file mode 100644 index f15ccfc2..00000000 --- a/packages/auth/src/routes/verify.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; -import { loadCurrentSession, sessionResultToResponse } from "../session"; - -export async function handleVerify( - request: Request, - env: Env, - ctx: ExecutionContext, -): Promise { - const authHeader = request.headers.get("Authorization"); - if (!authHeader?.startsWith("Bearer ")) return errorResponse(Errors.UNAUTHORIZED); - - const result = await loadCurrentSession(authHeader.slice(7), env.DB, env.JWT_SECRET, ctx); - if (result.kind === "ok") return okResponse(result.session); - return sessionResultToResponse(result); -} diff --git a/packages/auth/src/routes/webauthn-auth-finish.test.ts b/packages/auth/src/routes/webauthn-auth-finish.test.ts deleted file mode 100644 index 62adc050..00000000 --- a/packages/auth/src/routes/webauthn-auth-finish.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -vi.mock("../webauthn", () => ({ - verifyWebauthnAssertion: vi.fn(), -})); -vi.mock("../verification", () => ({ - isEmailVerificationEnabled: vi.fn(), -})); -vi.mock("../jwt", () => ({ - signJwt: vi.fn(async () => "signed.jwt"), -})); -vi.mock("../sessions", () => ({ - createSession: vi.fn(async () => "session-1"), - SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, -})); - -import { handleWebauthnAuthFinish } from "./webauthn-auth-finish"; -import { verifyWebauthnAssertion } from "../webauthn"; -import { isEmailVerificationEnabled } from "../verification"; -import { createSession } from "../sessions"; - -function request() { - return new Request("http://localhost/webauthn/auth/finish", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - userId: "user-1", - email: "user@example.com", - challengeId: "challenge-1", - response: { id: "credential-1" }, - }), - }); -} - -function makeEnv(emailVerified: number) { - const first = vi.fn().mockResolvedValue({ - id: "user-1", - email: "user@example.com", - name: "User", - created_at: "2026-01-01", - moderation: 0, - force_password_change: 0, - is_admin: 0, - email_verified: emailVerified, - }); - const bind = vi.fn().mockReturnValue({ first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - DB: { prepare }, - JWT_SECRET: "secret", - } as unknown as Parameters[1]; -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyWebauthnAssertion).mockResolvedValue(null); - vi.mocked(isEmailVerificationEnabled).mockResolvedValue(false); -}); - -describe("handleWebauthnAuthFinish email verification", () => { - it("blocks an unverified account before consuming its assertion challenge", async () => { - vi.mocked(isEmailVerificationEnabled).mockResolvedValue(true); - - const response = await handleWebauthnAuthFinish(request(), makeEnv(0)); - - expect(response.status).toBe(403); - expect(await response.json()).toMatchObject({ error: "email_not_verified" }); - expect(verifyWebauthnAssertion).not.toHaveBeenCalled(); - expect(createSession).not.toHaveBeenCalled(); - }); - - it("does not consult the feature flag for an already verified account", async () => { - const response = await handleWebauthnAuthFinish(request(), makeEnv(1)); - - expect(response.status).toBe(200); - expect(isEmailVerificationEnabled).not.toHaveBeenCalled(); - expect(verifyWebauthnAssertion).toHaveBeenCalledOnce(); - }); -}); diff --git a/packages/auth/src/routes/webauthn-auth-finish.ts b/packages/auth/src/routes/webauthn-auth-finish.ts deleted file mode 100644 index 706360ee..00000000 --- a/packages/auth/src/routes/webauthn-auth-finish.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { okResponse, errorResponse, Errors, normalizeEmail } from "../lib"; -import { verifyWebauthnAssertion } from "../webauthn"; -import { signJwt } from "../jwt"; -import { checkModeration } from "./login"; -import { createSession, SESSION_TTL_MS } from "../sessions"; -import { isEmailVerificationEnabled } from "../verification"; -import type { Env } from "../index"; - -export async function handleWebauthnAuthFinish(request: Request, env: Env): Promise { - const body = await request.json<{ - userId: string; - challengeId: string; - response: Record; - email: string; - }>(); - - if (!body.userId || !body.challengeId || !body.response || !body.email) { - return errorResponse(Errors.BAD_REQUEST); - } - - const user = await env.DB.prepare( - "SELECT id, email, name, created_at, moderation, force_password_change, is_admin, email_verified FROM users WHERE id = ? AND email = ?", - ) - .bind(body.userId, normalizeEmail(body.email)) - .first<{ id: string; email: string; name: string; created_at: string; moderation: number; force_password_change: number; is_admin: number; email_verified: number }>(); - if (!user) return errorResponse(Errors.UNAUTHORIZED); - - const moderationResponse = checkModeration(user.moderation); - if (moderationResponse) return moderationResponse; - - // Password and passkey login must enforce the same account gates. Check this - // before consuming the one-time assertion challenge so the user can verify - // their email and retry the ceremony normally. - if (!user.email_verified && await isEmailVerificationEnabled(env, user.id)) { - return Response.json({ ok: false, error: "email_not_verified" }, { status: 403 }); - } - - const assertionError = await verifyWebauthnAssertion(env, body.userId, body.challengeId, body.response, "webauthn-auth-finish"); - if (assertionError) return assertionError; - - if (user.force_password_change) { - // Same single-use nonce flow as /login - see that handler for context. - const cti = crypto.randomUUID(); - await env.DB.prepare("UPDATE users SET change_token_id = ? WHERE id = ?") - .bind(cti, user.id).run(); - const changeToken = await signJwt( - { userId: user.id, email: user.email, expiresAt: Date.now() + 15 * 60 * 1000, isAdmin: Boolean(user.is_admin), forcePasswordChange: true, cti }, - env.JWT_SECRET, - ); - return Response.json({ ok: false, error: "password_change_required", changeToken }, { status: 200 }); - } - - const expiresAt = Date.now() + SESSION_TTL_MS; - const sid = await createSession(env, user.id, request, expiresAt); - const token = await signJwt( - { userId: user.id, email: user.email, expiresAt, isAdmin: Boolean(user.is_admin), sid }, - env.JWT_SECRET, - ); - - return okResponse({ - token, - user: { id: user.id, email: user.email, name: user.name, createdAt: user.created_at }, - }); -} diff --git a/packages/auth/src/routes/webauthn-auth-start.test.ts b/packages/auth/src/routes/webauthn-auth-start.test.ts deleted file mode 100644 index 8b31315e..00000000 --- a/packages/auth/src/routes/webauthn-auth-start.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, it, expect, vi } from "vitest"; -import { handleWebauthnAuthStart } from "./webauthn-auth-start"; - -// Minimal D1 mock: createAuthenticationOptions reads the user's credentials -// (.all → `creds`) and inserts a challenge row (.run). No `users` lookup happens -// anymore - that existence check was the oracle this endpoint must not have. -function makeEnv(creds: Array<{ id: string; transports: string | null }> = []) { - const db = { - prepare: vi.fn(() => ({ - bind: vi.fn(() => ({ - all: vi.fn().mockResolvedValue({ results: creds }), - run: vi.fn().mockResolvedValue({ meta: { changes: 1 } }), - first: vi.fn().mockResolvedValue(null), - })), - })), - }; - return { - DB: db, - WEBAUTHN_RP_ID: "localhost", - WEBAUTHN_RP_NAME: "Test", - WEBAUTHN_ORIGIN: "http://localhost", - } as unknown as Parameters[1]; -} - -function req(body: unknown) { - return new Request("http://localhost/webauthn/auth/start", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(body), - }); -} - -describe("handleWebauthnAuthStart - no account-existence oracle", () => { - it("returns options (200) even for an unknown user, instead of 401", async () => { - const res = await handleWebauthnAuthStart(req({ userId: "does-not-exist" }), makeEnv()); - expect(res.status).toBe(200); - const body = await res.json<{ ok: boolean; data: { options: unknown; challengeId: string } }>(); - expect(body.ok).toBe(true); - expect(body.data.options).toBeDefined(); - expect(typeof body.data.challengeId).toBe("string"); - }); - - it("still rejects a request with no userId", async () => { - const res = await handleWebauthnAuthStart(req({}), makeEnv()); - expect(res.status).toBe(400); - }); -}); - -describe("handleWebauthnAuthStart - transports hint in allowCredentials", () => { - async function allowCredentials(creds: Array<{ id: string; transports: string | null }>) { - const res = await handleWebauthnAuthStart(req({ userId: "u1" }), makeEnv(creds)); - const body = await res.json<{ - data: { options: { allowCredentials?: Array<{ transports?: string[] }> } }; - }>(); - return body.data.options.allowCredentials ?? []; - } - - it("echoes the stored transports back", async () => { - const list = await allowCredentials([{ id: "AQIDBA", transports: '["internal","hybrid"]' }]); - expect(list).toHaveLength(1); - expect(list[0].transports).toEqual(["internal", "hybrid"]); - }); - - it("falls back to internal+hybrid when transports are NULL (legacy credential)", async () => { - const list = await allowCredentials([{ id: "AQIDBA", transports: null }]); - expect(list[0].transports).toEqual(["internal", "hybrid"]); - }); - - it("falls back to the default when transports JSON is malformed", async () => { - const list = await allowCredentials([{ id: "AQIDBA", transports: "not json" }]); - expect(list[0].transports).toEqual(["internal", "hybrid"]); - }); -}); diff --git a/packages/auth/src/routes/webauthn-auth-start.ts b/packages/auth/src/routes/webauthn-auth-start.ts deleted file mode 100644 index 9126987c..00000000 --- a/packages/auth/src/routes/webauthn-auth-start.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { okResponse, errorResponse, Errors } from "../lib"; -import { createAuthenticationOptions } from "../webauthn"; -import type { Env } from "../index"; - -export async function handleWebauthnAuthStart(request: Request, env: Env): Promise { - const body = await request.json<{ userId: string }>(); - if (!body.userId) return errorResponse(Errors.BAD_REQUEST); - - // Do NOT branch on whether the user exists. Returning UNAUTHORIZED for an - // unknown userId (vs options for a known one) is an account-existence - // oracle. For a non-existent / credential-less user createAuthenticationOptions - // just yields empty allowCredentials; the ceremony then fails at /finish the - // same way an invalid assertion does, so existence never leaks. This mirrors - // how /login and /register avoid existence leaks. The endpoint is - // IP-rate-limited (RATE_LIMITER_AUTH) so the extra challenge row is bounded. - const { options, challengeId } = await createAuthenticationOptions(env, body.userId); - - return okResponse({ options, challengeId }); -} diff --git a/packages/auth/src/routes/webauthn-credentials-delete.test.ts b/packages/auth/src/routes/webauthn-credentials-delete.test.ts deleted file mode 100644 index 2d27cffb..00000000 --- a/packages/auth/src/routes/webauthn-credentials-delete.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleWebauthnCredentialsDelete } from "./webauthn-credentials-delete"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); -vi.mock("../mfa", () => ({ - requireMFA: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { requireMFA } from "../mfa"; - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv(changes = 1) { - const run = vi.fn().mockResolvedValue({ meta: { changes } }); - const bind = vi.fn().mockReturnValue({ run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { env: { DB: { prepare } } as unknown as Parameters[1], prepare, bind, run }; -} - -function req(body: unknown) { - return new Request("http://localhost/webauthn/credentials/delete", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(requireMFA).mockResolvedValue(null as never); -}); - -describe("handleWebauthnCredentialsDelete", () => { - it("rejects a missing credentialId before touching auth", async () => { - const { env } = makeEnv(); - const res = await handleWebauthnCredentialsDelete(req({}), env); - expect(res.status).toBe(400); - expect(requireAuthenticatedSession).not.toHaveBeenCalled(); - }); - - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - const res = await handleWebauthnCredentialsDelete(req({ credentialId: "c1" }), env); - expect(res.status).toBe(401); - }); - - it("requires MFA before deleting", async () => { - vi.mocked(requireMFA).mockResolvedValue( - Response.json({ ok: false, error: "mfa_required" }, { status: 401 }) as never, - ); - const { env, run } = makeEnv(); - const res = await handleWebauthnCredentialsDelete(req({ credentialId: "c1" }), env); - expect(res.status).toBe(401); - expect(run).not.toHaveBeenCalled(); - }); - - it("deletes the credential scoped to the caller", async () => { - const { env, bind } = makeEnv(); - const res = await handleWebauthnCredentialsDelete(req({ credentialId: "c1", totpCode: "123456" }), env); - expect(res.status).toBe(200); - expect(bind).toHaveBeenCalledWith("c1", "user-1"); - }); - - it("returns 404 when the credential isn't the caller's", async () => { - const { env } = makeEnv(0); - const res = await handleWebauthnCredentialsDelete(req({ credentialId: "foreign", totpCode: "123456" }), env); - expect(res.status).toBe(404); - }); -}); diff --git a/packages/auth/src/routes/webauthn-credentials-delete.ts b/packages/auth/src/routes/webauthn-credentials-delete.ts deleted file mode 100644 index 01866a92..00000000 --- a/packages/auth/src/routes/webauthn-credentials-delete.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { requireMFA } from "../mfa"; -import type { Env } from "../index"; - -export async function handleWebauthnCredentialsDelete(request: Request, env: Env): Promise { - const body = await request.json<{ - credentialId: string; - totpCode?: string; - challengeId?: string; - webauthnResponse?: unknown; - backupCode?: string; - }>(); - if (!body.credentialId) return errorResponse(Errors.BAD_REQUEST); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const mfaError = await requireMFA(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - }); - if (mfaError) return mfaError; - - const result = await env.DB.prepare( - "DELETE FROM webauthn_credentials WHERE id = ? AND user_id = ?", - ).bind(body.credentialId, session.userId).run(); - - if (!result.meta.changes || result.meta.changes === 0) return errorResponse(Errors.NOT_FOUND); - - return okResponse({}); -} diff --git a/packages/auth/src/routes/webauthn-credentials-list.test.ts b/packages/auth/src/routes/webauthn-credentials-list.test.ts deleted file mode 100644 index 67c473ac..00000000 --- a/packages/auth/src/routes/webauthn-credentials-list.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../../api/src/test/sqliteD1"; -import { handleWebauthnCredentialsList } from "./webauthn-credentials-list"; - -vi.mock("../auth-session", () => ({ - requireAuthenticatedSession: vi.fn(), -})); - -import { requireAuthenticatedSession } from "../auth-session"; - -// Real SQLite with every auth migration applied, so the user scoping and -// ordering are actually evaluated. -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../migrations", import.meta.url)); - -const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; - -function makeEnv() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const user = sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, 'U', 'x', datetime('now'))"); - user.run("user-1", "a@example.com"); - user.run("user-2", "b@example.com"); - const cred = sqlite.prepare("INSERT INTO webauthn_credentials (id, user_id, name, public_key, created_at) VALUES (?, ?, ?, 'pk', ?)"); - cred.run("c2", "user-1", "Phone", "2026-02-01"); - cred.run("c1", "user-1", "Yubikey", "2026-01-01"); - cred.run("c3", "user-2", "Not mine", "2026-01-15"); - return { env: { DB: db } as unknown as Parameters[1] }; -} - -function req() { - return new Request("http://localhost/webauthn/credentials", { headers: { Authorization: "Bearer t" } }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); -}); - -describe("handleWebauthnCredentialsList", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(); - const res = await handleWebauthnCredentialsList(req(), env); - expect(res.status).toBe(401); - }); - - it("lists only the caller's credentials, oldest first, without key material", async () => { - const { env } = makeEnv(); - const res = await handleWebauthnCredentialsList(req(), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { credentials: unknown[] } }; - expect(json.data.credentials).toEqual([ - { id: "c1", name: "Yubikey", created_at: "2026-01-01" }, - { id: "c2", name: "Phone", created_at: "2026-02-01" }, - ]); - }); -}); diff --git a/packages/auth/src/routes/webauthn-credentials-list.ts b/packages/auth/src/routes/webauthn-credentials-list.ts deleted file mode 100644 index f77c26df..00000000 --- a/packages/auth/src/routes/webauthn-credentials-list.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import type { Env } from "../index"; - -export async function handleWebauthnCredentialsList(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const result = await env.DB.prepare( - "SELECT id, name, created_at FROM webauthn_credentials WHERE user_id = ? ORDER BY created_at ASC", - ).bind(session.userId).all<{ id: string; name: string; created_at: string }>(); - - return okResponse({ credentials: result.results }); -} diff --git a/packages/auth/src/routes/webauthn-register-finish.ts b/packages/auth/src/routes/webauthn-register-finish.ts deleted file mode 100644 index 882c66ab..00000000 --- a/packages/auth/src/routes/webauthn-register-finish.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { - consumeChallenge, - verifyRegistrationResponse, - uint8ArrayToBase64url, -} from "../webauthn"; -import { requireEnrollmentStepUp } from "../mfa"; -import type { Env } from "../index"; - -export async function handleWebauthnRegisterFinish(request: Request, env: Env): Promise { - const body = await request.json<{ - challengeId: string; - response: Record; - name?: string; - totpCode?: string; - challengeId2fa?: string; - webauthnResponse?: unknown; - backupCode?: string; - currentPassword?: string; - }>(); - if (!body.challengeId || !body.response) return errorResponse(Errors.BAD_REQUEST); - - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const mfaError = await requireEnrollmentStepUp(env, session.userId, { - totpCode: body.totpCode, - challengeId: body.challengeId2fa, - webauthnResponse: body.webauthnResponse, - backupCode: body.backupCode, - currentPassword: body.currentPassword, - }); - if (mfaError) return mfaError; - - const challenge = await consumeChallenge(env, body.challengeId, session.userId, "registration"); - if (!challenge) return errorResponse(Errors.BAD_REQUEST); - - let verification: Awaited>; - try { - verification = await verifyRegistrationResponse({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - response: body.response as any, - expectedChallenge: challenge, - expectedOrigin: env.WEBAUTHN_ORIGIN, - expectedRPID: env.WEBAUTHN_RP_ID, - }); - } catch (err) { - console.error("[webauthn-register-finish] verifyRegistrationResponse threw:", err); - return errorResponse(Errors.BAD_REQUEST); - } - - if (!verification.verified || !verification.registrationInfo) { - return errorResponse(Errors.UNAUTHORIZED); - } - - const { credentialID, credentialPublicKey, counter } = verification.registrationInfo; - const credentialId = uint8ArrayToBase64url(credentialID); - const publicKey = uint8ArrayToBase64url(credentialPublicKey); - - // Transports the authenticator reported (e.g. ["internal","hybrid"] for a - // password-manager / platform passkey). Echoed back in allowCredentials at - // auth time so the browser surfaces the right authenticator UI. May be absent - // on some authenticators - store NULL and we fall back to a sensible default. - const transports = (body.response as { response?: { transports?: string[] } }).response?.transports; - const transportsJson = - Array.isArray(transports) && transports.length > 0 ? JSON.stringify(transports) : null; - - await env.DB.prepare( - "INSERT INTO webauthn_credentials (id, user_id, name, public_key, counter, created_at, transports) VALUES (?, ?, ?, ?, ?, ?, ?)", - ) - .bind(credentialId, session.userId, body.name ?? "Security Key", publicKey, counter, new Date().toISOString(), transportsJson) - .run(); - - return okResponse({ credentialId }); -} diff --git a/packages/auth/src/routes/webauthn-register-start.ts b/packages/auth/src/routes/webauthn-register-start.ts deleted file mode 100644 index c890d203..00000000 --- a/packages/auth/src/routes/webauthn-register-start.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { okResponse, errorResponse, Errors } from "../lib"; -import { createRegistrationOptions } from "../webauthn"; -import type { Env } from "../index"; - -export async function handleWebauthnRegisterStart(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - const user = await env.DB.prepare("SELECT name, email FROM users WHERE id = ?") - .bind(session.userId).first<{ name: string; email: string }>(); - if (!user) return errorResponse(Errors.UNAUTHORIZED); - - const { options, challengeId } = await createRegistrationOptions( - env, - session.userId, - user.name, - user.email, - ); - - return okResponse({ options, challengeId }); -} diff --git a/packages/auth/src/session.ts b/packages/auth/src/session.ts deleted file mode 100644 index 9ad14cbb..00000000 --- a/packages/auth/src/session.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { verifyJwt } from "./jwt"; -import { errorResponse, Errors, type Session } from "./lib"; -import { resolvePersonalPlan } from "./plan"; - -interface SessionUserRow { - id: string; - email: string; - moderation: number; - force_password_change: number; - is_admin: number; - personal_plan: string | null; - personal_plan_status: string | null; - personal_plan_started_at: number | null; - personal_plan_cancel_at: number | null; - personal_plan_style: string | null; - personal_presence_color: string | null; - personal_crit_sparkles: number | null; - granted_plan: string | null; - granted_plan_expires_at: number | null; - granted_plan_started_at: number | null; - reading_font: string | null; - editing_font: string | null; - ui_font: string | null; - theme_mode: string | null; - theme_custom_color: string | null; -} - -interface SessionStateRow { - id: string; - expires_at: number; - revoked_at: number | null; - last_used_at: number; -} - -export type SessionLoadResult = - | { kind: "ok"; session: Session } - | { kind: "disabled" } - | { kind: "suspended"; until: number } - | { kind: "invalid" }; - -// How stale `last_used_at` is allowed to get before a refresh write. -// 10 min is fine-grained enough for the "Active sessions" UI without -// turning every authenticated request into a database write. -const LAST_USED_REFRESH_MS = 10 * 60 * 1000; - -// Loads, validates, and re-derives a session in a single D1 round-trip. -// One batch fetches both the user row (for moderation / admin / forced-reset -// state) and the matching session row (for revocation / expiry). The JWT -// itself is treated as proof of authentication, never as a source of truth -// for any claim that can change. -// -// Takes `db` + `jwtSecret` as primitives rather than an `Env` so the API -// worker can reuse this against its `AUTH_DB` binding without depending on -// the auth worker's specific Env shape. -// -// `ctx` is optional: when provided (the per-request /verify path), a stale -// `last_used_at` triggers a fire-and-forget refresh via waitUntil. Routes -// that aren't on the hot path can omit it and skip the bookkeeping. -export async function loadCurrentSession( - token: string, - db: D1Database, - jwtSecret: string, - ctx?: ExecutionContext, -): Promise { - const tokenSession = await verifyJwt(token, jwtSecret); - if (!tokenSession || tokenSession.forcePasswordChange) return { kind: "invalid" }; - if (!tokenSession.sid) return { kind: "invalid" }; - - const [userResult, sessionResult] = await db.batch([ - db.prepare( - `SELECT u.id, u.email, u.moderation, u.force_password_change, u.is_admin, - p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, - p.reading_font, p.editing_font, p.ui_font, - p.theme_mode, p.theme_custom_color, - b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, - b.personal_plan_cancel_at, - b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at - FROM users u - LEFT JOIN user_billing b ON b.user_id = u.id - LEFT JOIN user_preferences p ON p.user_id = u.id - WHERE u.id = ?`, - ).bind(tokenSession.userId), - db.prepare( - "SELECT id, expires_at, revoked_at, last_used_at FROM sessions WHERE id = ? AND user_id = ?", - ).bind(tokenSession.sid, tokenSession.userId), - ]); - - const user = (userResult.results as SessionUserRow[])[0]; - const sessionRow = (sessionResult.results as SessionStateRow[])[0]; - - if (!user) return { kind: "invalid" }; - if (user.force_password_change) return { kind: "invalid" }; - - if (!sessionRow) return { kind: "invalid" }; - if (sessionRow.revoked_at !== null) return { kind: "invalid" }; - const now = Date.now(); - if (sessionRow.expires_at <= now) return { kind: "invalid" }; - - // Account moderation states take priority so the frontend can show a - // specific message instead of a generic "session expired." - if (user.moderation === -1) return { kind: "disabled" }; - if (user.moderation > 0) { - const nowSeconds = Math.floor(now / 1000); - if (nowSeconds < user.moderation) { - return { kind: "suspended", until: user.moderation }; - } - } - - // Lazy "last seen" bookkeeping. Bounded to one write per session per - // ~10 min regardless of request rate; runs after the response is sent. - if (ctx && now - sessionRow.last_used_at > LAST_USED_REFRESH_MS) { - ctx.waitUntil( - db.prepare("UPDATE sessions SET last_used_at = ? WHERE id = ?") - .bind(now, sessionRow.id).run(), - ); - } - - const resolved = resolvePersonalPlan({ - granted_plan: user.granted_plan, - granted_plan_expires_at: user.granted_plan_expires_at, - granted_plan_started_at: user.granted_plan_started_at, - personal_plan: user.personal_plan, - personal_plan_status: user.personal_plan_status, - personal_plan_started_at: user.personal_plan_started_at, - personal_plan_cancel_at: user.personal_plan_cancel_at, - personal_plan_style: user.personal_plan_style, - personal_presence_color: user.personal_presence_color, - personal_crit_sparkles: user.personal_crit_sparkles, - }, now); - - return { - kind: "ok", - session: { - userId: user.id, - email: user.email, - expiresAt: tokenSession.expiresAt, - isAdmin: Boolean(user.is_admin), - sid: sessionRow.id, - personalPlan: resolved.plan, - personalPlanSince: resolved.since, - personalPlanStatus: resolved.status, - personalPlanCancelAt: resolved.cancelAt, - personalPlanStyle: resolved.style, - personalPresenceColor: resolved.presenceColor, - personalCritSparkles: resolved.critSparkles, - readingFont: user.reading_font, - editingFont: user.editing_font, - uiFont: user.ui_font, - themeMode: user.theme_mode, - themeCustomColor: user.theme_custom_color, - }, - }; -} - -export async function requireCurrentSessionToken(token: string, db: D1Database, jwtSecret: string): Promise { - const result = await loadCurrentSession(token, db, jwtSecret); - if (result.kind === "ok") return result.session; - return sessionResultToResponse(result); -} - -export function sessionResultToResponse( - result: Exclude, -): Response { - if (result.kind === "disabled") { - return Response.json({ ok: false, error: "account_disabled" }, { status: 403 }); - } - if (result.kind === "suspended") { - return Response.json({ ok: false, error: "account_suspended", until: result.until }, { status: 403 }); - } - return errorResponse(Errors.UNAUTHORIZED); -} diff --git a/packages/auth/src/sessions.ts b/packages/auth/src/sessions.ts deleted file mode 100644 index a2d0ce39..00000000 --- a/packages/auth/src/sessions.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { clientIp } from "./lib"; -import type { Env } from "./index"; - -export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; - -// Admin-panel sessions are the highest-privilege token in the product and -// live in the admin SPA's sessionStorage - keep them to a working day, not a -// week. Re-acquiring one is a single silent handoff redirect when the docs -// session is still alive, so the short TTL costs the operator one click. -export const ADMIN_SESSION_TTL_MS = 12 * 60 * 60 * 1000; - -export type DeviceKind = "phone" | "tablet" | "laptop" | "desktop"; - -export interface SessionRow { - id: string; - user_id: string; - created_at: number; - expires_at: number; - last_used_at: number; - device_kind: DeviceKind | null; - client_label: string | null; - ip: string | null; - revoked_at: number | null; -} - -// Derive a coarse device kind and friendly client label from the User-Agent -// at session-creation time. We store only these derived values so we don't -// retain the full UA fingerprint. -export function parseUserAgent(ua: string | null): { deviceKind: DeviceKind | null; clientLabel: string | null } { - if (!ua) return { deviceKind: null, clientLabel: null }; - - const deviceKind: DeviceKind = - /iPad/.test(ua) || (/Android/.test(ua) && !/Mobile/.test(ua)) ? "tablet" : - /iPhone|Android.*Mobile|Mobile.*Firefox|Windows Phone/.test(ua) ? "phone" : - /Macintosh|Mac OS X/.test(ua) ? "laptop" : - "desktop"; - - const browser = - /Edg\//.test(ua) ? "Edge" : - /Firefox\//.test(ua) ? "Firefox" : - /Chrome\//.test(ua) ? "Chrome" : - /Safari\//.test(ua) ? "Safari" : - "Browser"; - - const os = - /Windows/.test(ua) ? "Windows" : - /Mac OS X/.test(ua) ? "macOS" : - /Android/.test(ua) ? "Android" : - /iPhone|iPad|iOS/.test(ua) ? "iOS" : - /Linux/.test(ua) ? "Linux" : - ""; - - const clientLabel = os ? `${browser} on ${os}` : browser; - return { deviceKind, clientLabel }; -} - -// Creates a new session row and returns the id (used as the JWT's `sid` claim). -// Captures UA/IP at creation time only - there's no per-request write. -export async function createSession( - env: Env, - userId: string, - request: Request, - expiresAt: number, -): Promise { - const id = crypto.randomUUID(); - const now = Date.now(); - const { deviceKind, clientLabel } = parseUserAgent(request.headers.get("User-Agent")); - const ip = clientIp(request); - - // Opportunistic GC: drop expired/revoked rows for this user so the table - // doesn't grow unbounded for users who never log out properly. Batched - // with the INSERT - one round trip on every login. - await env.DB.batch([ - env.DB.prepare( - "DELETE FROM sessions WHERE user_id = ? AND (expires_at <= ? OR revoked_at IS NOT NULL)", - ).bind(userId, now), - env.DB.prepare( - `INSERT INTO sessions (id, user_id, created_at, expires_at, last_used_at, device_kind, client_label, ip) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - ).bind(id, userId, now, expiresAt, now, deviceKind, clientLabel, ip), - ]); - - return id; -} - -// Marks a single session as revoked. Returns true if a row was actually -// updated (i.e. the session existed and belonged to this user and wasn't -// already revoked). -export async function revokeSession( - env: Env, - sessionId: string, - userId: string, -): Promise { - const result = await env.DB.prepare( - "UPDATE sessions SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL", - ).bind(Date.now(), sessionId, userId).run(); - return (result.meta.changes ?? 0) > 0; -} - -// Revokes every active session for a user, optionally keeping one alive -// (the caller's current session). Used by change-password (keep current), -// force-change-password (keep none), and sessions-revoke-others. Note that -// admin moderation does NOT revoke sessions: disabling a user leaves their -// rows intact (every request re-checks moderation, so they're inert), which -// means re-enabling the user resurrects any still-unexpired sessions. -export async function revokeAllSessions( - env: Env, - userId: string, - exceptSessionId?: string, -): Promise { - const now = Date.now(); - if (exceptSessionId) { - await env.DB.prepare( - "UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND id != ? AND revoked_at IS NULL", - ).bind(now, userId, exceptSessionId).run(); - } else { - await env.DB.prepare( - "UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL", - ).bind(now, userId).run(); - } -} - -export interface ActiveSessionView { - id: string; - createdAt: number; - lastUsedAt: number; - expiresAt: number; - deviceKind: DeviceKind | null; - clientLabel: string | null; - ip: string | null; - current: boolean; -} - -export async function listActiveSessions( - env: Env, - userId: string, - currentSessionId: string | undefined, -): Promise { - const now = Date.now(); - const rows = await env.DB.prepare( - `SELECT id, created_at, last_used_at, expires_at, device_kind, client_label, ip - FROM sessions - WHERE user_id = ? AND revoked_at IS NULL AND expires_at > ? - ORDER BY last_used_at DESC`, - ).bind(userId, now).all<{ - id: string; - created_at: number; - last_used_at: number; - expires_at: number; - device_kind: DeviceKind | null; - client_label: string | null; - ip: string | null; - }>(); - - return rows.results.map((r) => ({ - id: r.id, - createdAt: r.created_at, - lastUsedAt: r.last_used_at, - expiresAt: r.expires_at, - deviceKind: r.device_kind, - clientLabel: r.client_label, - ip: r.ip, - current: r.id === currentSessionId, - })); -} diff --git a/packages/auth/src/stripe-client.ts b/packages/auth/src/stripe-client.ts deleted file mode 100644 index 8a4b575f..00000000 --- a/packages/auth/src/stripe-client.ts +++ /dev/null @@ -1,37 +0,0 @@ -import Stripe from "stripe"; -import type { Env } from "./index"; - -// Stripe SDK initialized for the Workers runtime. The default Node http -// client + crypto won't work even with nodejs_compat - we have to plug -// in fetch and SubtleCrypto explicitly. -let cached: Stripe | null = null; -let cachedKey: string | null = null; - -export function getStripe(secretKey: string): Stripe { - if (cached && cachedKey === secretKey) return cached; - cached = new Stripe(secretKey, { - httpClient: Stripe.createFetchHttpClient(), - }); - cachedKey = secretKey; - return cached; -} - -export function getStripeWebhookCryptoProvider(): Stripe.CryptoProvider { - return Stripe.createSubtleCryptoProvider(); -} - -// Best-effort: keep the Stripe customer's email in sync when the account email -// changes, so receipts/dunning mail follows the user. stripe_customer_id is the -// durable link - a failure here never blocks the email change itself. -export async function syncStripeCustomerEmail(env: Env, userId: string, newEmail: string): Promise { - if (!env.STRIPE_SECRET_KEY) return; - try { - const row = await env.DB.prepare( - "SELECT stripe_customer_id FROM user_billing WHERE user_id = ?", - ).bind(userId).first<{ stripe_customer_id: string | null }>(); - if (!row?.stripe_customer_id) return; - await getStripe(env.STRIPE_SECRET_KEY).customers.update(row.stripe_customer_id, { email: newEmail }); - } catch (err) { - console.error("syncStripeCustomerEmail failed", { userId, err }); - } -} diff --git a/packages/auth/src/theme.test.ts b/packages/auth/src/theme.test.ts deleted file mode 100644 index 3cd68e64..00000000 --- a/packages/auth/src/theme.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { isThemeMode, isHexColor, THEME_MODES } from "./theme"; - -describe("isThemeMode", () => { - it("accepts every value in THEME_MODES", () => { - for (const v of THEME_MODES) expect(isThemeMode(v)).toBe(true); - }); - - it("rejects unknown / wrong-case strings", () => { - expect(isThemeMode("solarized")).toBe(false); - expect(isThemeMode("")).toBe(false); - expect(isThemeMode("DARK")).toBe(false); - }); - - it("rejects non-strings", () => { - expect(isThemeMode(null)).toBe(false); - expect(isThemeMode(undefined)).toBe(false); - expect(isThemeMode(1)).toBe(false); - expect(isThemeMode({})).toBe(false); - }); -}); - -describe("isHexColor", () => { - it("accepts #rrggbb in either case", () => { - expect(isHexColor("#2e7d6b")).toBe(true); - expect(isHexColor("#ABCDEF")).toBe(true); - }); - - it("rejects short form, missing hash, bad digits", () => { - expect(isHexColor("#abc")).toBe(false); - expect(isHexColor("2e7d6b")).toBe(false); - expect(isHexColor("#2e7d6g")).toBe(false); - expect(isHexColor("#2e7d6b ")).toBe(false); - }); - - it("rejects non-strings", () => { - expect(isHexColor(null)).toBe(false); - expect(isHexColor(undefined)).toBe(false); - expect(isHexColor(0xffffff)).toBe(false); - }); -}); diff --git a/packages/auth/src/theme.ts b/packages/auth/src/theme.ts deleted file mode 100644 index 72984fad..00000000 --- a/packages/auth/src/theme.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Allowed theme modes for the theme_mode column on user_preferences. NULL on -// the row means "use the default" (dark) - the frontend treats a missing / -// unknown value as dark. 'custom' additionally stores a #rrggbb base in -// theme_custom_color, from which the frontend derives the full palette. -// -// Setting the theme is gated to global site admins - see -// packages/auth/src/routes/update-theme.ts. Keep this list in sync with -// THEME_MODES in packages/frontend/src/lib/theme.ts. -export const THEME_MODES = ["dark", "light", "custom"] as const; -export type ThemeMode = typeof THEME_MODES[number]; - -export function isThemeMode(value: unknown): value is ThemeMode { - return typeof value === "string" && (THEME_MODES as readonly string[]).includes(value); -} - -const HEX_RE = /^#[0-9a-fA-F]{6}$/; - -export function isHexColor(value: unknown): value is string { - return typeof value === "string" && HEX_RE.test(value); -} diff --git a/packages/auth/src/totp.test.ts b/packages/auth/src/totp.test.ts deleted file mode 100644 index 04214b80..00000000 --- a/packages/auth/src/totp.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { base32Encode, base32Decode, buildOtpauthUri, verifyTOTP, matchTotpStep, generateSecret } from "./totp"; -import { toArrayBuffer } from "./crypto"; - -// Reimplements HOTP so tests can generate expected codes independently. -async function computeTOTP(secret: string, timeMs: number): Promise { - const secretBytes = base32Decode(secret); - const counter = Math.floor(timeMs / 1000 / 30); - const key = await crypto.subtle.importKey( - "raw", toArrayBuffer(secretBytes), - { name: "HMAC", hash: "SHA-1" }, - false, ["sign"], - ); - const counterBuffer = new ArrayBuffer(8); - new DataView(counterBuffer).setBigUint64(0, BigInt(counter), false); - const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBuffer)); - const offset = hmac[19] & 0x0f; - const code = ( - ((hmac[offset] & 0x7f) << 24) | - ((hmac[offset + 1] & 0xff) << 16) | - ((hmac[offset + 2] & 0xff) << 8) | - (hmac[offset + 3] & 0xff) - ) % 1_000_000; - return code.toString().padStart(6, "0"); -} - -// ── base32Encode / base32Decode ────────────────────────────────────────────── - -describe("base32Encode / base32Decode", () => { - it("round-trips arbitrary bytes", () => { - const original = new Uint8Array([104, 101, 108, 108, 111]); // "hello" - expect(base32Decode(base32Encode(original))).toEqual(original); - }); - - it("encodes to uppercase A-Z 2-7 characters only", () => { - const bytes = new Uint8Array([0, 255, 128, 64, 32]); - expect(base32Encode(bytes)).toMatch(/^[A-Z2-7]+$/); - }); - - it("base32Decode is case-insensitive", () => { - expect(base32Decode("JBSWY3DP")).toEqual(base32Decode("jbswy3dp")); - }); - - it("base32Decode strips padding and non-alphabet characters", () => { - expect(base32Decode("JBSWY3DP====")).toEqual(base32Decode("JBSWY3DP")); - }); -}); - -// ── generateSecret ─────────────────────────────────────────────────────────── - -describe("generateSecret", () => { - - it("generates unique values each time", () => { - expect(generateSecret()).not.toBe(generateSecret()); - }); - - it("decodes to exactly 20 bytes (160 bits)", () => { - expect(base32Decode(generateSecret()).length).toBe(20); - }); -}); - -// ── buildOtpauthUri ────────────────────────────────────────────────────────── - -describe("buildOtpauthUri", () => { - it("produces a valid otpauth://totp/ URI", () => { - expect(buildOtpauthUri("SECRET", "user@example.com")).toMatch(/^otpauth:\/\/totp\//); - }); - - it("includes the secret in the URI", () => { - expect(buildOtpauthUri("MYSECRET", "u@e.com")).toContain("MYSECRET"); - }); - - it("URL-encodes the email in the label", () => { - const uri = buildOtpauthUri("S", "user@example.com"); - expect(uri).toContain(encodeURIComponent("user@example.com")); - }); - - it("uses Annex as the default issuer", () => { - expect(buildOtpauthUri("S", "u@e.com")).toContain("issuer=Annex"); - }); - - it("uses a custom issuer when provided", () => { - expect(buildOtpauthUri("S", "u@e.com", "MyApp")).toContain("issuer=MyApp"); - }); - - it("specifies SHA1 algorithm, 6 digits, 30 second period", () => { - const uri = buildOtpauthUri("S", "u@e.com"); - expect(uri).toContain("algorithm=SHA1"); - expect(uri).toContain("digits=6"); - expect(uri).toContain("period=30"); - }); -}); - -// ── verifyTOTP ─────────────────────────────────────────────────────────────── - -describe("verifyTOTP", () => { - const SECRET = "JBSWY3DPEHPK3PXP"; - const NOW = 1_700_000_000_000; // fixed ms timestamp for deterministic tests - - it("accepts the current time step's code", async () => { - const code = await computeTOTP(SECRET, NOW); - expect(await verifyTOTP(SECRET, code, NOW)).toBe(true); - }); - - it("rejects a code from two steps in the past", async () => { - const code = await computeTOTP(SECRET, NOW - 60_000); - expect(await verifyTOTP(SECRET, code, NOW)).toBe(false); - }); - - it("rejects a code for a different secret", async () => { - const code = await computeTOTP("AAAAAAAAAAAAAAAA", NOW); - expect(await verifyTOTP(SECRET, code, NOW)).toBe(false); - }); - - it("rejects a 5-digit code (too short)", async () => { - expect(await verifyTOTP(SECRET, "12345", NOW)).toBe(false); - }); - - it("rejects a 7-digit code (too long)", async () => { - expect(await verifyTOTP(SECRET, "1234567", NOW)).toBe(false); - }); - - it("rejects an empty string", async () => { - expect(await verifyTOTP(SECRET, "", NOW)).toBe(false); - }); - - it("rejects a non-numeric code", async () => { - expect(await verifyTOTP(SECRET, "abcdef", NOW)).toBe(false); - }); -}); - -// ── matchTotpStep ──────────────────────────────────────────────────────────── - -describe("matchTotpStep", () => { - const SECRET = "JBSWY3DPEHPK3PXP"; - const NOW = 1_700_000_000_000; - const STEP_NOW = Math.floor(NOW / 1000 / 30); - - it("returns the current step for the current code", async () => { - const code = await computeTOTP(SECRET, NOW); - expect(await matchTotpStep(SECRET, code, NOW)).toBe(STEP_NOW); - }); - - it("returns the previous step for a one-step-old code", async () => { - const code = await computeTOTP(SECRET, NOW - 30_000); - expect(await matchTotpStep(SECRET, code, NOW)).toBe(STEP_NOW - 1); - }); - - it("returns the next step for a one-step-ahead code", async () => { - const code = await computeTOTP(SECRET, NOW + 30_000); - expect(await matchTotpStep(SECRET, code, NOW)).toBe(STEP_NOW + 1); - }); -}); diff --git a/packages/auth/src/totp.ts b/packages/auth/src/totp.ts deleted file mode 100644 index a1d7d7ce..00000000 --- a/packages/auth/src/totp.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { toArrayBuffer } from "./crypto"; - -const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - -export function base32Encode(bytes: Uint8Array): string { - let result = ""; - let bits = 0; - let value = 0; - for (const byte of bytes) { - value = (value << 8) | byte; - bits += 8; - while (bits >= 5) { - bits -= 5; - result += BASE32_ALPHABET[(value >>> bits) & 31]; - } - } - if (bits > 0) { - result += BASE32_ALPHABET[(value << (5 - bits)) & 31]; - } - return result; -} - -export function base32Decode(str: string): Uint8Array { - const clean = str.toUpperCase().replace(/[^A-Z2-7]/g, ""); - const bytes: number[] = []; - let bits = 0; - let value = 0; - for (const char of clean) { - const idx = BASE32_ALPHABET.indexOf(char); - if (idx === -1) continue; - value = (value << 5) | idx; - bits += 5; - if (bits >= 8) { - bits -= 8; - bytes.push((value >>> bits) & 255); - } - } - return new Uint8Array(bytes); -} - -async function hotp(secretBytes: Uint8Array, counter: bigint): Promise { - const key = await crypto.subtle.importKey( - "raw", toArrayBuffer(secretBytes), - { name: "HMAC", hash: "SHA-1" }, - false, ["sign"], - ); - const counterBuffer = new ArrayBuffer(8); - new DataView(counterBuffer).setBigUint64(0, counter, false); - const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBuffer)); - const offset = hmac[19] & 0x0f; - const code = ( - ((hmac[offset] & 0x7f) << 24) | - ((hmac[offset + 1] & 0xff) << 16) | - ((hmac[offset + 2] & 0xff) << 8) | - (hmac[offset + 3] & 0xff) - ) % 1_000_000; - return code; -} - -// Returns the 30-second time step the code matched (within the ±1-step clock -// drift window), or null when invalid. Login-flow callers must go through -// verifyAndConsumeTotp (mfa.ts), which persists the step to enforce the -// RFC 6238 never-accept-the-same-or-earlier-OTP replay rule. -export async function matchTotpStep(secret: string, code: string, timeMs: number = Date.now()): Promise { - if (!/^\d{6}$/.test(code)) return null; - const secretBytes = base32Decode(secret); - const counter = Math.floor(timeMs / 1000 / 30); - for (let delta = -1; delta <= 1; delta++) { - const expected = await hotp(secretBytes, BigInt(counter + delta)); - if (expected.toString().padStart(6, "0") === code) return counter + delta; - } - return null; -} - -export async function verifyTOTP(secret: string, code: string, timeMs: number = Date.now()): Promise { - return (await matchTotpStep(secret, code, timeMs)) !== null; -} - -export function generateSecret(): string { - const bytes = crypto.getRandomValues(new Uint8Array(20)); - return base32Encode(bytes); -} - -export function buildOtpauthUri(secret: string, email: string, issuer = "Annex"): string { - const label = encodeURIComponent(`${issuer}:${email}`); - return `otpauth://totp/${label}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=30`; -} diff --git a/packages/auth/src/turnstile.ts b/packages/auth/src/turnstile.ts deleted file mode 100644 index f6e0e4ab..00000000 --- a/packages/auth/src/turnstile.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Cloudflare's documented always-pass test secret. siteverify returns -// success:true for any token under this secret, so the network round-trip -// from local dev only adds latency and a flake surface - short-circuit it. -const ALWAYS_PASS_TEST_SECRET = "1x0000000000000000000000000000000AA"; - -export async function verifyTurnstile(token: string, secret: string): Promise { - if (secret === ALWAYS_PASS_TEST_SECRET) return true; - - const body = new FormData(); - body.append("secret", secret); - body.append("response", token); - - const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { - method: "POST", - body, - }); - - const data = await res.json<{ success: boolean }>(); - return data.success; -} diff --git a/packages/auth/src/verification.test.ts b/packages/auth/src/verification.test.ts deleted file mode 100644 index f3e23bd2..00000000 --- a/packages/auth/src/verification.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, vi } from "vitest"; -import { isEmailVerificationEnabled } from "./verification"; - -function makeEnv(opts: { appOrigin?: string; devVar?: string; flagValue?: boolean }) { - const getBooleanValue = vi.fn().mockResolvedValue(opts.flagValue ?? false); - const env = { - APP_ORIGIN: opts.appOrigin, - DEV_EMAIL_VERIFICATION: opts.devVar, - FLAGS: opts.flagValue === undefined ? undefined : { getBooleanValue }, - } as unknown as Parameters[0]; - return { env, getBooleanValue }; -} - -describe("isEmailVerificationEnabled", () => { - it("bypasses (returns false) on a localhost deployment even when the flag is on", async () => { - const { env, getBooleanValue } = makeEnv({ appOrigin: "http://localhost:5173", flagValue: true }); - expect(await isEmailVerificationEnabled(env, "u1")).toBe(false); - // The flag isn't even consulted - dashboard flips can't gate local dev. - expect(getBooleanValue).not.toHaveBeenCalled(); - }); - - it("bypasses on a 127.0.0.1 deployment too", async () => { - const { env } = makeEnv({ appOrigin: "http://127.0.0.1:5173", flagValue: true }); - expect(await isEmailVerificationEnabled(env, "u1")).toBe(false); - }); - - it("DEV_EMAIL_VERIFICATION=true opts a localhost deployment back into the flag", async () => { - const { env, getBooleanValue } = makeEnv({ appOrigin: "http://localhost:5173", devVar: "true", flagValue: true }); - expect(await isEmailVerificationEnabled(env, "u1")).toBe(true); - expect(getBooleanValue).toHaveBeenCalledWith("email-verification", false, { userId: "u1" }); - }); - - it("reads the flag on a production origin", async () => { - const on = makeEnv({ appOrigin: "https://docs.cubityfir.st", flagValue: true }); - expect(await isEmailVerificationEnabled(on.env, "u1")).toBe(true); - - const off = makeEnv({ appOrigin: "https://docs.cubityfir.st", flagValue: false }); - expect(await isEmailVerificationEnabled(off.env, "u1")).toBe(false); - }); - - it("returns false when the FLAGS binding is absent", async () => { - const { env } = makeEnv({ appOrigin: "https://docs.cubityfir.st" }); - expect(await isEmailVerificationEnabled(env, "u1")).toBe(false); - }); - - it("does not treat an unset APP_ORIGIN as local (unit-test envs read the flag)", async () => { - const { env, getBooleanValue } = makeEnv({ flagValue: true }); - expect(await isEmailVerificationEnabled(env, "u1")).toBe(true); - expect(getBooleanValue).toHaveBeenCalled(); - }); -}); diff --git a/packages/auth/src/verification.ts b/packages/auth/src/verification.ts deleted file mode 100644 index 2a433998..00000000 --- a/packages/auth/src/verification.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { Env } from "./index"; - -const VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours - -// The `email-verification` Flagship flag, with a dev bypass. The dashboard -// flag state is shared with production and wrangler dev serves it verbatim, -// so flipping the flag on in prod must not start gating local login/register -// (it silently kills every login-dependent e2e/integration suite). Local -// deployments - detected by a localhost APP_ORIGIN, the same signal -// dev-quick-login trusts - therefore never enforce verification unless -// DEV_EMAIL_VERIFICATION=true is set in .dev.vars to opt back in for testing -// the verification flow itself. -export async function isEmailVerificationEnabled(env: Env, userId: string): Promise { - const isLocalDeploy = /\blocalhost\b|127\.0\.0\.1/.test(env.APP_ORIGIN ?? ""); - if (isLocalDeploy && env.DEV_EMAIL_VERIFICATION !== "true") return false; - return env.FLAGS - ? env.FLAGS.getBooleanValue("email-verification", false, { userId }) - : false; -} - -// `email` is the pending NEW address for an email-change request; NULL means -// the token verifies the account's current email (signup flow). -export async function createVerificationToken(env: Env, userId: string, email?: string): Promise { - const now = Date.now(); - - // Lazy GC: remove expired and already-consumed tokens for this user - await env.DB.prepare( - "DELETE FROM email_verification_tokens WHERE user_id = ? AND (expires_at <= ? OR consumed_at IS NOT NULL)", - ).bind(userId, now).run(); - - const token = crypto.randomUUID(); - const expiresAt = now + VERIFICATION_TTL_MS; - - await env.DB.prepare( - "INSERT INTO email_verification_tokens (id, user_id, created_at, expires_at, consumed_at, email) VALUES (?, ?, ?, ?, NULL, ?)", - ).bind(token, userId, now, expiresAt, email ?? null).run(); - - return token; -} - -// Returns { userId, email } on success (email = pending new address, or null -// for a plain signup-verification token), null if the token is -// invalid/expired/already-consumed. -export async function consumeVerificationToken( - env: Env, - token: string, -): Promise<{ userId: string; email: string | null } | null> { - const now = Date.now(); - - const result = await env.DB.prepare( - "UPDATE email_verification_tokens SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL AND expires_at > ? RETURNING user_id, email", - ).bind(now, token, now).first<{ user_id: string; email: string | null }>(); - - return result ? { userId: result.user_id, email: result.email } : null; -} diff --git a/packages/auth/src/webauthn-assertion.test.ts b/packages/auth/src/webauthn-assertion.test.ts deleted file mode 100644 index 1f6f4e68..00000000 --- a/packages/auth/src/webauthn-assertion.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from "vitest"; -import type { Env } from "./index"; - -vi.mock("@simplewebauthn/server", () => ({ - generateRegistrationOptions: vi.fn(), - verifyRegistrationResponse: vi.fn(), - generateAuthenticationOptions: vi.fn(), - verifyAuthenticationResponse: vi.fn(), -})); - -import { verifyAuthenticationResponse } from "@simplewebauthn/server"; -import { verifyDiscoverableAssertion, verifyWebauthnAssertion } from "./webauthn"; - -// verifyWebauthnAssertion runs: consumeChallenge (DELETE ... RETURNING .first), -// credential SELECT (.first), then the counter UPDATE (.run). -function makeEnv(counterChanges: number) { - const sqls: string[] = []; - const firsts: unknown[] = [ - { challenge: "chal", created_at: Date.now() }, - { id: "AQID", public_key: "AQID", counter: 4 }, - ]; - const first = vi.fn(async () => firsts.shift() ?? null); - const run = vi.fn(async () => ({ meta: { changes: counterChanges } })); - const prepare = vi.fn((sql: string) => { - sqls.push(sql); - return { bind: vi.fn(() => ({ first, run })) }; - }); - return { - env: { DB: { prepare }, WEBAUTHN_ORIGIN: "https://x", WEBAUTHN_RP_ID: "x" } as unknown as Env, - sqls, - run, - }; -} - -function verified(newCounter: number) { - vi.mocked(verifyAuthenticationResponse).mockResolvedValue({ - verified: true, - authenticationInfo: { newCounter }, - } as unknown as Awaited>); -} - -beforeEach(() => vi.clearAllMocks()); - -describe("verifyWebauthnAssertion signature counter", () => { - it("advances the counter with a conditional UPDATE and succeeds when it wins", async () => { - verified(5); - const { env, sqls } = makeEnv(1); - expect(await verifyWebauthnAssertion(env, "u1", "c1", { id: "AQID" })).toBeNull(); - expect(sqls.some(s => s.includes("SET counter = ? WHERE id = ? AND counter < ?"))).toBe(true); - }); - - it("rejects a concurrent assertion that lost the counter race (cloned authenticator)", async () => { - verified(5); - const { env } = makeEnv(0); - const res = await verifyWebauthnAssertion(env, "u1", "c1", { id: "AQID" }); - expect(res?.status).toBe(401); - }); - - it("does not touch the counter for counter-less authenticators (synced passkeys report 0)", async () => { - verified(0); - const { env, run } = makeEnv(0); - expect(await verifyWebauthnAssertion(env, "u1", "c1", { id: "AQID" })).toBeNull(); - expect(run).not.toHaveBeenCalled(); - }); -}); - -// verifyDiscoverableAssertion runs: consumeChallenge (.first), credential -// SELECT by id only (.first), then the shared verify + counter UPDATE (.run). -function makeDiscoverableEnv(cred: Record | null) { - const binds: unknown[][] = []; - const firsts: unknown[] = [{ challenge: "chal", created_at: Date.now() }, cred]; - const first = vi.fn(async () => firsts.shift() ?? null); - const run = vi.fn(async () => ({ meta: { changes: 1 } })); - const prepare = vi.fn(() => ({ - bind: vi.fn((...args: unknown[]) => { - binds.push(args); - return { first, run }; - }), - })); - return { - env: { DB: { prepare }, WEBAUTHN_ORIGIN: "https://x", WEBAUTHN_RP_ID: "x" } as unknown as Env, - binds, - }; -} - -const storedCred = { id: "AQID", user_id: "user-1", public_key: "AQID", counter: 0 }; - -describe("verifyDiscoverableAssertion", () => { - it("consumes only a user-less passkey challenge", async () => { - verified(0); - const { env, binds } = makeDiscoverableEnv(storedCred); - await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); - // consumeChallenge binds (id, user_id, type): sentinel user + its own type, - // so a user-bound authentication challenge can't be redeemed here. - expect(binds[0]).toEqual(["c1", "", "passkey"]); - }); - - it("resolves the account from the credential when userHandle matches", async () => { - verified(0); - const { env } = makeDiscoverableEnv(storedCred); - const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); - expect(result).toEqual({ userId: "user-1" }); - }); - - it.each([ - ["names another account", "user-2"], - ["is missing", undefined], - ])("rejects when userHandle %s, before verifying the signature", async (_label, userHandle) => { - verified(0); - const { env } = makeDiscoverableEnv(storedCred); - const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle } }); - expect((result as Response).status).toBe(401); - expect(verifyAuthenticationResponse).not.toHaveBeenCalled(); - }); - - it("rejects an unknown credential", async () => { - verified(0); - const { env } = makeDiscoverableEnv(null); - const result = await verifyDiscoverableAssertion(env, "c1", { id: "nope", response: { userHandle: "user-1" } }); - expect((result as Response).status).toBe(401); - }); - - it("rejects a failed signature", async () => { - vi.mocked(verifyAuthenticationResponse).mockResolvedValue({ verified: false } as unknown as Awaited>); - const { env } = makeDiscoverableEnv(storedCred); - const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); - expect((result as Response).status).toBe(401); - }); -}); diff --git a/packages/auth/src/webauthn.test.ts b/packages/auth/src/webauthn.test.ts deleted file mode 100644 index eae16768..00000000 --- a/packages/auth/src/webauthn.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { fileURLToPath } from "node:url"; -import { createSqliteD1 } from "../../api/src/test/sqliteD1"; -import type { Env } from "./index"; -import { - consumeChallenge, - deleteExpiredWebauthnChallenges, - WEBAUTHN_CHALLENGE_TTL_MS, -} from "./webauthn"; - -// Real SQLite with every auth migration applied: both functions are a single -// scoped DELETE, so only running it shows which rows it actually takes. -const AUTH_MIGRATIONS = fileURLToPath(new URL("../migrations", import.meta.url)); - -function makeEnv(challenges: Array<{ id: string; userId?: string; type?: string; createdAt: number }>) { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const insert = sqlite.prepare("INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, ?, ?, ?, ?)"); - for (const c of challenges) insert.run(c.id, c.userId ?? "user-1", `challenge-of-${c.id}`, c.type ?? "authentication", c.createdAt); - const remaining = () => sqlite.prepare("SELECT id FROM webauthn_challenges ORDER BY id").all().map(r => r.id); - return { env: { DB: db } as unknown as Env, remaining }; -} - -describe("consumeChallenge", () => { - it("atomically deletes and returns a valid challenge", async () => { - const { env, remaining } = makeEnv([{ id: "challenge-1", createdAt: Date.now() }, { id: "challenge-2", createdAt: Date.now() }]); - - expect(await consumeChallenge(env, "challenge-1", "user-1", "authentication")) - .toBe("challenge-of-challenge-1"); - expect(remaining()).toEqual(["challenge-2"]); - // Single use: a replay finds nothing. - expect(await consumeChallenge(env, "challenge-1", "user-1", "authentication")).toBeNull(); - }); - - it("refuses (and leaves in place) a challenge for another user or ceremony type", async () => { - const { env, remaining } = makeEnv([{ id: "challenge-1", createdAt: Date.now() }]); - - expect(await consumeChallenge(env, "challenge-1", "user-2", "authentication")).toBeNull(); - expect(await consumeChallenge(env, "challenge-1", "user-1", "registration")).toBeNull(); - expect(remaining()).toEqual(["challenge-1"]); - }); - - it("still consumes an expired challenge before rejecting it", async () => { - const { env, remaining } = makeEnv([{ id: "challenge-1", createdAt: Date.now() - WEBAUTHN_CHALLENGE_TTL_MS - 1 }]); - - expect(await consumeChallenge(env, "challenge-1", "user-1", "authentication")) - .toBeNull(); - expect(remaining()).toEqual([]); - }); -}); - -describe("deleteExpiredWebauthnChallenges", () => { - it("deletes challenges at or beyond the ceremony TTL", async () => { - const now = 1_700_000_000_000; - const { env, remaining } = makeEnv([ - { id: "older", createdAt: now - WEBAUTHN_CHALLENGE_TTL_MS - 1 }, - { id: "at-ttl", createdAt: now - WEBAUTHN_CHALLENGE_TTL_MS }, - { id: "fresh", createdAt: now - WEBAUTHN_CHALLENGE_TTL_MS + 1 }, - ]); - - await deleteExpiredWebauthnChallenges(env, now); - - expect(remaining()).toEqual(["fresh"]); - }); -}); diff --git a/packages/auth/src/webauthn.ts b/packages/auth/src/webauthn.ts deleted file mode 100644 index 21faf7ca..00000000 --- a/packages/auth/src/webauthn.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { - generateRegistrationOptions, - verifyRegistrationResponse, - generateAuthenticationOptions, - verifyAuthenticationResponse, -} from "@simplewebauthn/server"; -// The fixed set of WebAuthn transport hints (the SDK's AuthenticatorTransportFuture -// isn't re-exported from @simplewebauthn/server's main entry, so we mirror it here). -type AuthenticatorTransportFuture = - | "ble" - | "cable" - | "hybrid" - | "internal" - | "nfc" - | "smart-card" - | "usb"; -import { errorResponse, Errors } from "./lib"; -import type { Env } from "./index"; - -export const WEBAUTHN_CHALLENGE_TTL_MS = 5 * 60 * 1000; - -export async function deleteExpiredWebauthnChallenges( - env: Env, - now = Date.now(), -): Promise { - await env.DB.prepare( - "DELETE FROM webauthn_challenges WHERE created_at <= ?", - ).bind(now - WEBAUTHN_CHALLENGE_TTL_MS).run(); -} - -export function uint8ArrayToBase64url(bytes: Uint8Array): string { - let binary = ""; - for (let i = 0; i < bytes.byteLength; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} - -export function base64urlToUint8Array(base64url: string): Uint8Array { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "="); - const binary = atob(padded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes; -} - -export async function createRegistrationOptions( - env: Env, - userId: string, - userName: string, - userEmail: string, -) { - const existing = await env.DB.prepare( - "SELECT id FROM webauthn_credentials WHERE user_id = ?", - ).bind(userId).all<{ id: string }>(); - - const options = await generateRegistrationOptions({ - rpName: env.WEBAUTHN_RP_NAME, - rpID: env.WEBAUTHN_RP_ID, - userID: userId, - userName: userEmail, - userDisplayName: userName, - excludeCredentials: existing.results.map((c) => ({ - id: base64urlToUint8Array(c.id), - type: "public-key" as const, - })), - authenticatorSelection: { - residentKey: "preferred", - // "required" means the authenticator must verify the user (PIN / - // biometric) - important because we treat WebAuthn as passwordless, - // so the key alone authenticates without a second factor. - userVerification: "required", - }, - }); - - const challengeId = crypto.randomUUID(); - await env.DB.prepare( - "INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, ?, ?, 'registration', ?)", - ).bind(challengeId, userId, options.challenge, Date.now()).run(); - - return { options, challengeId }; -} - -// Default transports for credentials registered before we persisted the hint -// (and for authenticators that report none). internal+hybrid tells the browser a -// platform / synced password-manager passkey is usable; without any hint Chrome -// on Android falls back to the external-key UI (USB / NFC / "use another device"). -const DEFAULT_TRANSPORTS = ["internal", "hybrid"] as const; - -function parseTransports(raw: string | null): AuthenticatorTransportFuture[] { - if (!raw) return [...DEFAULT_TRANSPORTS]; - try { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((t) => typeof t === "string")) { - return parsed as AuthenticatorTransportFuture[]; - } - } catch { - // fall through to default - } - return [...DEFAULT_TRANSPORTS]; -} - -export async function createAuthenticationOptions(env: Env, userId: string) { - // This endpoint is intentionally usable before authentication and creates a - // database row even for an invented user id. Bound storage growth by - // removing abandoned ceremonies before inserting the next challenge. - await deleteExpiredWebauthnChallenges(env); - - const credentials = await env.DB.prepare( - "SELECT id, transports FROM webauthn_credentials WHERE user_id = ?", - ).bind(userId).all<{ id: string; transports: string | null }>(); - - const options = await generateAuthenticationOptions({ - rpID: env.WEBAUTHN_RP_ID, - allowCredentials: credentials.results.map((c) => ({ - id: base64urlToUint8Array(c.id), - type: "public-key" as const, - transports: parseTransports(c.transports), - })), - userVerification: "required", - }); - - const challengeId = crypto.randomUUID(); - await env.DB.prepare( - "INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, ?, ?, 'authentication', ?)", - ).bind(challengeId, userId, options.challenge, Date.now()).run(); - - return { options, challengeId }; -} - -// Discoverable ("usernameless") passkey sign-in: the user isn't known until the -// authenticator picks a credential, so the challenge row carries this sentinel -// in its NOT NULL user_id column, under its own ceremony type so it can never -// be redeemed by (or redeem) a user-bound ceremony. -const DISCOVERABLE_CHALLENGE_USER = ""; -const DISCOVERABLE_CHALLENGE_TYPE = "passkey"; - -export async function createDiscoverableAuthenticationOptions(env: Env) { - // Unauthenticated row creation - same bound as createAuthenticationOptions. - await deleteExpiredWebauthnChallenges(env); - - // No allowCredentials: the browser offers every discoverable credential it - // holds for this RP ID and the chosen one names the account. - const options = await generateAuthenticationOptions({ - rpID: env.WEBAUTHN_RP_ID, - userVerification: "required", - }); - - const challengeId = crypto.randomUUID(); - await env.DB.prepare( - "INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, ?, ?, ?, ?)", - ).bind(challengeId, DISCOVERABLE_CHALLENGE_USER, options.challenge, DISCOVERABLE_CHALLENGE_TYPE, Date.now()).run(); - - return { options, challengeId }; -} - -export async function consumeChallenge( - env: Env, - challengeId: string, - userId: string, - type: string, -): Promise { - const row = await env.DB.prepare( - `DELETE FROM webauthn_challenges - WHERE id = ? AND user_id = ? AND type = ? - RETURNING challenge, created_at`, - ).bind(challengeId, userId, type).first<{ challenge: string; created_at: number }>(); - - if (!row) return null; - if (Date.now() - row.created_at > WEBAUTHN_CHALLENGE_TTL_MS) return null; - - return row.challenge; -} - -/** - * Verifies a WebAuthn authentication assertion end-to-end: - * consumes the challenge, looks up the stored credential, verifies the - * response, and updates the counter. - * - * Returns null on success, or an error Response on failure. - */ -export async function verifyWebauthnAssertion( - env: Env, - userId: string, - challengeId: string, - response: Record, - logPrefix = "webauthn", -): Promise { - const challenge = await consumeChallenge(env, challengeId, userId, "authentication"); - if (!challenge) return errorResponse(Errors.BAD_REQUEST); - - const responseId = (response as { id: string }).id; - const storedCred = await env.DB.prepare( - "SELECT id, public_key, counter FROM webauthn_credentials WHERE id = ? AND user_id = ?", - ).bind(responseId, userId).first(); - if (!storedCred) return errorResponse(Errors.UNAUTHORIZED); - - return verifyAgainstCredential(env, challenge, storedCred, response, logPrefix); -} - -/** - * Verifies a discoverable-credential (usernameless passkey) assertion: consumes - * the user-less challenge, resolves the account from the credential the - * authenticator chose, and requires the returned userHandle to name that same - * account (WebAuthn §7.2 step 6 - mandatory when allowCredentials was empty). - * - * Returns the authenticated user id, or an error Response. - */ -export async function verifyDiscoverableAssertion( - env: Env, - challengeId: string, - response: Record, -): Promise<{ userId: string } | Response> { - const challenge = await consumeChallenge(env, challengeId, DISCOVERABLE_CHALLENGE_USER, DISCOVERABLE_CHALLENGE_TYPE); - if (!challenge) return errorResponse(Errors.BAD_REQUEST); - - const responseId = response.id; - if (typeof responseId !== "string" || !responseId) return errorResponse(Errors.UNAUTHORIZED); - - const storedCred = await env.DB.prepare( - "SELECT id, user_id, public_key, counter FROM webauthn_credentials WHERE id = ?", - ).bind(responseId).first(); - if (!storedCred) return errorResponse(Errors.UNAUTHORIZED); - - // @simplewebauthn/browser v9 decodes userHandle to the UTF-8 user id we - // registered with (createRegistrationOptions passes userID: userId). - const userHandle = (response.response as { userHandle?: unknown } | undefined)?.userHandle; - if (userHandle !== storedCred.user_id) return errorResponse(Errors.UNAUTHORIZED); - - const error = await verifyAgainstCredential(env, challenge, storedCred, response, "passkey-auth-finish"); - return error ?? { userId: storedCred.user_id }; -} - -type StoredCredential = { id: string; public_key: string; counter: number }; - -async function verifyAgainstCredential( - env: Env, - challenge: string, - storedCred: StoredCredential, - response: Record, - logPrefix: string, -): Promise { - let verification: Awaited>; - try { - verification = await verifyAuthenticationResponse({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - response: response as any, - expectedChallenge: challenge, - expectedOrigin: env.WEBAUTHN_ORIGIN, - expectedRPID: env.WEBAUTHN_RP_ID, - authenticator: { - credentialID: base64urlToUint8Array(storedCred.id), - credentialPublicKey: base64urlToUint8Array(storedCred.public_key), - counter: storedCred.counter, - }, - }); - } catch (err) { - console.error(`[${logPrefix}] verifyAuthenticationResponse threw:`, err); - return errorResponse(Errors.UNAUTHORIZED); - } - - if (!verification.verified || !verification.authenticationInfo) { - return errorResponse(Errors.UNAUTHORIZED); - } - - // Advance the signature counter atomically. Two concurrent assertions from - // a cloned authenticator can both verify against the same stored counter; - // only one may win the conditional UPDATE. Authenticators that don't keep a - // counter (synced passkeys) always report 0 - nothing to advance or race. - const newCounter = verification.authenticationInfo.newCounter; - if (newCounter > 0) { - const res = await env.DB.prepare("UPDATE webauthn_credentials SET counter = ? WHERE id = ? AND counter < ?") - .bind(newCounter, storedCred.id, newCounter) - .run(); - if ((res.meta?.changes ?? 0) !== 1) return errorResponse(Errors.UNAUTHORIZED); - } - - return null; -} - -export { verifyRegistrationResponse, verifyAuthenticationResponse }; diff --git a/packages/auth/tsconfig.json b/packages/auth/tsconfig.json deleted file mode 100644 index f4eb407d..00000000 --- a/packages/auth/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["@cloudflare/workers-types"] - }, - "include": ["src"], - "exclude": ["src/**/*.test.ts"] -} diff --git a/packages/auth/wrangler.config.ts b/packages/auth/wrangler.config.ts deleted file mode 100644 index 4ce6473d..00000000 --- a/packages/auth/wrangler.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineWranglerConfig } from "wrangler/experimental-config"; - -// Wrangler build settings for `cf build` / `cf deploy` (Worker config and -// bindings live in cloudflare.config.ts). -// -// There is no wrangler.toml. Local dev (`pnpm dev`) runs -// `wrangler dev --experimental-new-config --persist-to ../../.wrangler/state`, -// which reads this file + cloudflare.config.ts directly: every worker must share -// one local state dir (the api worker reads the auth DB via AUTH_DB), and -// `cf dev` cannot set a persist directory yet. -export default defineWranglerConfig({ - // Match the previous `wrangler deploy` default (no source map upload). - uploadSourceMaps: false, -}); diff --git a/packages/frontend/src/components/UserAvatar.tsx b/packages/frontend/src/components/UserAvatar.tsx index 9f624906..391f4aa3 100644 --- a/packages/frontend/src/components/UserAvatar.tsx +++ b/packages/frontend/src/components/UserAvatar.tsx @@ -12,7 +12,7 @@ function initials(name: string): string { export type PersonalPlan = "free" | "ink"; -// Allowed values mirror INK_RING_STYLES in packages/auth/src/plan.ts. +// Allowed values mirror INK_RING_STYLES in packages/api/src/account/plan.ts. // Anything unrecognised falls back to the default shimmer style. // 'none' opts out of the ring entirely - the avatar renders bare. const KNOWN_INK_STYLES = new Set(["shimmer", "aurora", "ember", "mono", "none"]); diff --git a/packages/frontend/src/lib/fonts.ts b/packages/frontend/src/lib/fonts.ts index e4688af1..4c147b7d 100644 --- a/packages/frontend/src/lib/fonts.ts +++ b/packages/frontend/src/lib/fonts.ts @@ -1,6 +1,6 @@ // Font-stack catalogue used by both the wysiwyg editor (via CSS variables // on :root) and the user-settings preview. Keep these stacks in sync with -// the auth FONT_CHOICES list (packages/auth/src/fonts.ts) - a row added +// the API FONT_CHOICES list (packages/api/src/account/fonts.ts) - a row added // there needs a stack entry here. // // OpenDyslexic woff2 files are self-hosted under /public/fonts/ with an diff --git a/packages/frontend/src/lib/handle.test.ts b/packages/frontend/src/lib/handle.test.ts index 8d9dd5ec..cb6d4cd9 100644 --- a/packages/frontend/src/lib/handle.test.ts +++ b/packages/frontend/src/lib/handle.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "vitest"; import { normalizeHandle, handleProblem, profilePath } from "./handle"; -import * as server from "../../../auth/src/handle"; +import * as server from "../../../api/src/account/handle"; // The client copy only drives hints, but a drift would show "looks good" for a // name the server then rejects (or vice versa), so pin them together. diff --git a/packages/frontend/src/lib/handle.ts b/packages/frontend/src/lib/handle.ts index e5f71cf7..432be0ac 100644 --- a/packages/frontend/src/lib/handle.ts +++ b/packages/frontend/src/lib/handle.ts @@ -1,4 +1,4 @@ -// Client-side mirror of packages/auth/src/handle.ts - the rules for the opt-in +// Client-side mirror of packages/api/src/account/handle.ts - the rules for the opt-in // `/@` profile link. Used for instant validation hints in settings and // for spotting `/@…` paths in the router; the auth worker is authoritative. // handle.test.ts asserts the two stay in agreement. diff --git a/packages/frontend/src/lib/theme.ts b/packages/frontend/src/lib/theme.ts index 50366622..1419abe2 100644 --- a/packages/frontend/src/lib/theme.ts +++ b/packages/frontend/src/lib/theme.ts @@ -12,7 +12,7 @@ // // Setting the theme is admin-only - the settings UI is hidden and the write // route is 403-guarded unless the user is a global site admin. THEME_MODES -// must stay in sync with packages/auth/src/theme.ts. +// must stay in sync with packages/api/src/account/theme.ts. import { converter, formatCss, clampChroma } from "culori"; diff --git a/packages/frontend/src/pages/AuthCompletePage.test.tsx b/packages/frontend/src/pages/AuthCompletePage.test.tsx index b8898adc..84417f34 100644 --- a/packages/frontend/src/pages/AuthCompletePage.test.tsx +++ b/packages/frontend/src/pages/AuthCompletePage.test.tsx @@ -22,21 +22,21 @@ afterEach(() => { }); describe("AuthCompletePage", () => { - it("redeems the code once, stores the session and goes to the return path", async () => { + it("redeems the handoff cookie once, stores the session and goes to the return path", async () => { const fetchMock = vi.fn(async () => Response.json({ ok: true, data: { token: "session-jwt" } })); vi.stubGlobal("fetch", fetchMock); - renderAt("#code=abc123&return_to=%2Fprojects%2Fp1"); + renderAt("#status=ok&attempt=abc123&return_to=%2Fprojects%2Fp1"); expect(await screen.findByText("PROJECT P1")).toBeInTheDocument(); expect(localStorage.getItem("token")).toBe("session-jwt"); expect(fetchMock).toHaveBeenCalledTimes(1); - expect(JSON.parse(String((fetchMock.mock.calls[0] as unknown[])[1] && ((fetchMock.mock.calls[0] as unknown[])[1] as RequestInit).body))).toEqual({ code: "abc123" }); - // The code doesn't linger in the address bar. + // No code in the request: the HttpOnly cookie carries it. + expect(fetchMock).toHaveBeenCalledWith("/api/auth/exchange?attempt=abc123", { method: "POST" }); expect(window.location.hash).toBe(""); }); it("ignores an off-site return path", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ok: true, data: { token: "t" } }))); - renderAt("#code=abc123&return_to=https%3A%2F%2Fevil.test"); + renderAt("#status=ok&return_to=https%3A%2F%2Fevil.test"); expect(await screen.findByText("DASHBOARD")).toBeInTheDocument(); }); @@ -51,7 +51,7 @@ describe("AuthCompletePage", () => { it("explains a code that was already used or expired", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ok: false, error: "invalid_code" }, { status: 400 }))); - renderAt("#code=used"); + renderAt("#status=ok"); await waitFor(() => expect(screen.getByText(/took too long or was already used/i)).toBeInTheDocument()); expect(localStorage.getItem("token")).toBeNull(); }); diff --git a/packages/frontend/src/pages/AuthCompletePage.tsx b/packages/frontend/src/pages/AuthCompletePage.tsx index b24f63bd..97ba3db6 100644 --- a/packages/frontend/src/pages/AuthCompletePage.tsx +++ b/packages/frontend/src/pages/AuthCompletePage.tsx @@ -6,8 +6,11 @@ import { safeReturnTo, signInErrorMessage, startSignIn } from "@/lib/signIn"; // /auth/complete - where /api/auth/callback sends the browser. The outcome is // in the URL fragment (never sent to servers or in Referer headers): -// #code=&return_to=/path -> redeem for the session JWT -// #error= -> explain and offer a retry +// #status=ok&attempt=&return_to=/path +// -> redeem this attempt's single-use handoff +// cookie (HttpOnly; the code never appears +// in a URL) for the session JWT +// #error= -> explain and offer a retry export function AuthCompletePage() { const navigate = useNavigate(); const [error, setError] = useState(null); @@ -20,23 +23,20 @@ export function AuthCompletePage() { started.current = true; const fragment = new URLSearchParams(window.location.hash.slice(1)); - // Drop the code from the address bar and history straight away. + // Clean the address bar and history straight away. window.history.replaceState(null, "", window.location.pathname); const next = safeReturnTo(fragment.get("return_to")) ?? "/dashboard"; setReturnTo(next); - const code = fragment.get("code"); - if (!code) { + if (fragment.get("status") !== "ok") { setError(signInErrorMessage(fragment.get("error"))); return; } (async () => { try { - const res = await fetch("/api/auth/exchange", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ code }), - }); + // Same-origin POST: the browser sends the handoff cookie itself. + const attempt = encodeURIComponent(fragment.get("attempt") ?? ""); + const res = await fetch(`/api/auth/exchange?attempt=${attempt}`, { method: "POST" }); const json = (await res.json()) as { ok: boolean; data?: { token: string }; error?: string }; if (!json.ok || !json.data) { setError(signInErrorMessage(json.error ?? "invalid_code")); diff --git a/packages/frontend/src/pages/UserSettingsPage.tsx b/packages/frontend/src/pages/UserSettingsPage.tsx index 13a6a3d8..be3f7857 100644 --- a/packages/frontend/src/pages/UserSettingsPage.tsx +++ b/packages/frontend/src/pages/UserSettingsPage.tsx @@ -51,7 +51,7 @@ import { import { getAvatarVariant, type AvatarVariant } from "@/lib/avatarVariant"; import { toast as sonnerToast } from "sonner"; -// Mirrors INK_RING_STYLES in packages/auth/src/plan.ts. Order is the +// Mirrors INK_RING_STYLES in packages/api/src/account/plan.ts. Order is the // display order in the picker. 'shimmer' is the default - selecting it // stores NULL on the row. const INK_RING_STYLE_OPTIONS: { id: "shimmer" | "aurora" | "ember" | "mono" | "none"; label: string }[] = [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 68d00b59..d271ece1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -191,37 +191,6 @@ importers: specifier: ^4.156.0 version: 4.156.0(@cloudflare/workers-types@4.20260313.1)(@types/node@22.19.15) - packages/auth: - dependencies: - '@simplewebauthn/server': - specifier: ^9.0.0 - version: 9.0.3 - stripe: - specifier: ^17.0.0 - version: 17.7.0 - zxcvbn: - specifier: ^4.4.2 - version: 4.4.2 - devDependencies: - '@cloudflare/workers-types': - specifier: ^4.0.0 - version: 4.20260313.1 - '@types/zxcvbn': - specifier: ^4.4.5 - version: 4.4.5 - cf: - specifier: 1.0.0-beta.26 - version: 1.0.0-beta.26(@types/node@22.19.15) - typescript: - specifier: ^5.5.0 - version: 5.9.3 - vitest: - specifier: ^4.1.6 - version: 4.1.6(@types/node@22.19.15)(jsdom@25.0.1)(vite@6.4.2(@types/node@22.19.15)(jiti@2.6.1)(lightningcss@1.31.1)(sass@1.51.0)(terser@5.48.0)) - wrangler: - specifier: ^4.156.0 - version: 4.156.0(@cloudflare/workers-types@4.20260313.1)(@types/node@22.19.15) - packages/frontend: dependencies: '@codemirror/commands': @@ -1565,9 +1534,6 @@ packages: '@floating-ui/utils@0.2.11': resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==} - '@hexagon/base64@1.1.28': - resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==} - '@hono/node-server@2.1.5': resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==} engines: {node: '>=20'} @@ -1768,9 +1734,6 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - '@levischuck/tiny-cbor@0.2.11': - resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==} - '@lezer/common@1.5.2': resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==} @@ -1811,21 +1774,6 @@ packages: '@cfworker/json-schema': optional: true - '@peculiar/asn1-android@2.6.0': - resolution: {integrity: sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==} - - '@peculiar/asn1-ecc@2.6.1': - resolution: {integrity: sha512-+Vqw8WFxrtDIN5ehUdvlN2m73exS2JVG0UAyfVB31gIfor3zWEAQPD+K9ydCxaj3MLen9k0JhKpu9LqviuCE1g==} - - '@peculiar/asn1-rsa@2.6.1': - resolution: {integrity: sha512-1nVMEh46SElUt5CB3RUTV4EG/z7iYc7EoaDY5ECwganibQPkZ/Y2eMsTKB/LeyrUJ+W/tKoD9WUqIy8vB+CEdA==} - - '@peculiar/asn1-schema@2.6.0': - resolution: {integrity: sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==} - - '@peculiar/asn1-x509@2.6.1': - resolution: {integrity: sha512-O9jT5F1A2+t3r7C4VT7LYGXqkGLK7Kj1xFpz7U0isPrubwU5PbDoyYtx6MiGst29yq7pXN5vZbQFKRCP+lLZlA==} - '@playwright/test@1.59.1': resolution: {integrity: sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==} engines: {node: '>=18'} @@ -3075,14 +3023,6 @@ packages: '@shikijs/vscode-textmate@10.0.2': resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} - '@simplewebauthn/server@9.0.3': - resolution: {integrity: sha512-FMZieoBosrVLFxCnxPFD9Enhd1U7D8nidVDT4MsHc6l4fdVcjoeHjDueeXCloO1k5O/fZg1fsSXXPKbY2XTzDA==} - engines: {node: '>=16.0.0'} - - '@simplewebauthn/types@9.0.1': - resolution: {integrity: sha512-tGSRP1QvsAvsJmnOlRQyw/mvK9gnPtjEc5fg2+m8n+QUa+D7rvrKkOYyfpy42GTs90X3RDOnqJgfHt+qO67/+w==} - deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. - '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} engines: {node: '>=18'} @@ -3404,9 +3344,6 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} - '@types/zxcvbn@4.4.5': - resolution: {integrity: sha512-FZJgC5Bxuqg7Rhsm/bx6gAruHHhDQ55r+s0JhDh8CQ16fD7NsJJ+p8YMMQDhSQoIrSmjpqqYWA96oQVMNkjRyA==} - '@ungap/structured-clone@1.3.0': resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} @@ -3511,10 +3448,6 @@ packages: resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} engines: {node: '>= 0.4'} - asn1js@3.0.7: - resolution: {integrity: sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==} - engines: {node: '>=12.0.0'} - assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -3792,9 +3725,6 @@ packages: engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'} hasBin: true - cross-fetch@4.1.0: - resolution: {integrity: sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==} - cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -5120,15 +5050,6 @@ packages: resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==} engines: {node: '>=18'} - node-fetch@2.7.0: - resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} - engines: {node: 4.x || >=6.0.0} - peerDependencies: - encoding: ^0.1.0 - peerDependenciesMeta: - encoding: - optional: true - node-releases@2.0.36: resolution: {integrity: sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==} @@ -5314,13 +5235,6 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - pvtsutils@1.3.6: - resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==} - - pvutils@1.1.5: - resolution: {integrity: sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==} - engines: {node: '>=16.0.0'} - pwacompat@2.0.17: resolution: {integrity: sha512-6Du7IZdIy7cHiv7AhtDy4X2QRM8IAD5DII69mt5qWibC2d15ZU8DmBG1WdZKekG11cChSu4zkSUGPF9sweOl6w==} @@ -5859,9 +5773,6 @@ packages: resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==} engines: {node: '>=16'} - tr46@0.0.3: - resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} - tr46@1.0.1: resolution: {integrity: sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==} @@ -6150,9 +6061,6 @@ packages: resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} engines: {node: '>=18'} - webidl-conversions@3.0.1: - resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} - webidl-conversions@4.0.2: resolution: {integrity: sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==} @@ -6176,9 +6084,6 @@ packages: resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} engines: {node: '>=18'} - whatwg-url@5.0.0: - resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - whatwg-url@7.1.0: resolution: {integrity: sha512-WUu7Rg1DroM7oQvGWfOiAK21n74Gg+T4elXEQYkOhtyLeWiJFoOGLXPKI/9gzIie9CtwVLm8wtw6YJdKyxSjeg==} @@ -6380,9 +6285,6 @@ packages: zwitch@2.0.4: resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} - zxcvbn@4.4.2: - resolution: {integrity: sha512-Bq0B+ixT/DMyG8kgX2xWcI5jUvCwqrMxSFam7m0lAf78nf04hv6lNCsyLYdyYTrCVMqNDY/206K7eExYCeSyUQ==} - snapshots: '@adobe/css-tools@4.4.4': {} @@ -7599,8 +7501,6 @@ snapshots: '@floating-ui/utils@0.2.11': {} - '@hexagon/base64@1.1.28': {} - '@hono/node-server@2.1.5(hono@4.12.21)': dependencies: hono: 4.12.21 @@ -7750,8 +7650,6 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@levischuck/tiny-cbor@0.2.11': {} - '@lezer/common@1.5.2': {} '@lezer/css@1.3.3': @@ -7817,39 +7715,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@peculiar/asn1-android@2.6.0': - dependencies: - '@peculiar/asn1-schema': 2.6.0 - asn1js: 3.0.7 - tslib: 2.8.1 - - '@peculiar/asn1-ecc@2.6.1': - dependencies: - '@peculiar/asn1-schema': 2.6.0 - '@peculiar/asn1-x509': 2.6.1 - asn1js: 3.0.7 - tslib: 2.8.1 - - '@peculiar/asn1-rsa@2.6.1': - dependencies: - '@peculiar/asn1-schema': 2.6.0 - '@peculiar/asn1-x509': 2.6.1 - asn1js: 3.0.7 - tslib: 2.8.1 - - '@peculiar/asn1-schema@2.6.0': - dependencies: - asn1js: 3.0.7 - pvtsutils: 1.3.6 - tslib: 2.8.1 - - '@peculiar/asn1-x509@2.6.1': - dependencies: - '@peculiar/asn1-schema': 2.6.0 - asn1js: 3.0.7 - pvtsutils: 1.3.6 - tslib: 2.8.1 - '@playwright/test@1.59.1': dependencies: playwright: 1.59.1 @@ -9091,22 +8956,6 @@ snapshots: '@shikijs/vscode-textmate@10.0.2': {} - '@simplewebauthn/server@9.0.3': - dependencies: - '@hexagon/base64': 1.1.28 - '@levischuck/tiny-cbor': 0.2.11 - '@peculiar/asn1-android': 2.6.0 - '@peculiar/asn1-ecc': 2.6.1 - '@peculiar/asn1-rsa': 2.6.1 - '@peculiar/asn1-schema': 2.6.0 - '@peculiar/asn1-x509': 2.6.1 - '@simplewebauthn/types': 9.0.1 - cross-fetch: 4.1.0 - transitivePeerDependencies: - - encoding - - '@simplewebauthn/types@9.0.1': {} - '@sindresorhus/is@7.2.0': {} '@speed-highlight/core@1.2.17': {} @@ -9435,8 +9284,6 @@ snapshots: '@types/unist@3.0.3': {} - '@types/zxcvbn@4.4.5': {} - '@ungap/structured-clone@1.3.0': {} '@upsetjs/venn.js@2.0.0': @@ -9557,12 +9404,6 @@ snapshots: get-intrinsic: 1.3.0 is-array-buffer: 3.0.5 - asn1js@3.0.7: - dependencies: - pvtsutils: 1.3.6 - pvutils: 1.1.5 - tslib: 2.8.1 - assertion-error@2.0.1: {} async-function@1.0.0: {} @@ -9843,12 +9684,6 @@ snapshots: dependencies: cross-spawn: 7.0.6 - cross-fetch@4.1.0: - dependencies: - node-fetch: 2.7.0 - transitivePeerDependencies: - - encoding - cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -11519,10 +11354,6 @@ snapshots: dependencies: content-type: 2.1.0 - node-fetch@2.7.0: - dependencies: - whatwg-url: 5.0.0 - node-releases@2.0.36: {} node-releases@2.0.47: {} @@ -11697,12 +11528,6 @@ snapshots: punycode@2.3.1: {} - pvtsutils@1.3.6: - dependencies: - tslib: 2.8.1 - - pvutils@1.1.5: {} - pwacompat@2.0.17: {} qs@6.16.1: @@ -12441,8 +12266,6 @@ snapshots: dependencies: tldts: 6.1.86 - tr46@0.0.3: {} - tr46@1.0.1: dependencies: punycode: 2.3.1 @@ -12706,8 +12529,6 @@ snapshots: dependencies: xml-name-validator: 5.0.0 - webidl-conversions@3.0.1: {} - webidl-conversions@4.0.2: {} webidl-conversions@7.0.0: {} @@ -12725,11 +12546,6 @@ snapshots: tr46: 5.1.1 webidl-conversions: 7.0.0 - whatwg-url@5.0.0: - dependencies: - tr46: 0.0.3 - webidl-conversions: 3.0.1 - whatwg-url@7.1.0: dependencies: lodash.sortby: 4.7.0 @@ -13004,5 +12820,3 @@ snapshots: react: 19.2.4 zwitch@2.0.4: {} - - zxcvbn@4.4.2: {} diff --git a/scripts/d1-local.mjs b/scripts/d1-local.mjs index a722d981..9c6dbfa6 100644 --- a/scripts/d1-local.mjs +++ b/scripts/d1-local.mjs @@ -8,31 +8,31 @@ // database through a Wrangler config file. `cf d1 query --local` has no local // implementation yet either. So this goes through the running api dev server's // Local Explorer API (`/cdn-cgi/local/explorer/api/d1/database//raw`), -// which binds both databases (DB = cubedocs-main, AUTH_DB = cubedocs-auth) and -// reads/writes the exact same SQLite files as the dev servers. +// which binds cubedocs-main (DB) and reads/writes the exact same SQLite files +// as the dev servers. // // Requires the api worker to be running (`pnpm dev`, :8787). Override the // origin with ANNEX_DEV_API_ORIGIN (e.g. http://127.0.0.1:18787). // // CLI: -// node scripts/d1-local.mjs "" -// node scripts/d1-local.mjs --file path/to/file.sql +// node scripts/d1-local.mjs main "" +// node scripts/d1-local.mjs main --file path/to/file.sql // Prints each statement's result as JSON ({ columns, rows }). Exits non-zero on // any SQL or connection error. // // Programmatic (from Node/TS tests): // import { d1Local } from "../scripts/d1-local.mjs"; -// await d1Local("auth", "UPDATE users SET ..."); +// await d1Local("main", "UPDATE users SET ..."); // or, from synchronous code, spawn this file with execFileSync(process.execPath, // [script, db, sql]) - no shell, so SQL quoting is passed through verbatim. import { readFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; -// Database ids from packages/{api,auth}/cloudflare.config.ts. +// Database id from packages/api/cloudflare.config.ts. (cubedocs-auth is retired: +// accounts live on auth.cubityfir.st; Annex's users mirror is in cubedocs-main.) export const D1_DATABASES = { main: "267490be-7141-4d00-ab23-152742f2f6ef", // cubedocs-main - auth: "db327d85-b8c2-4fed-adaa-25e748778c86", // cubedocs-auth }; export function devApiOrigin() { @@ -42,13 +42,13 @@ export function devApiOrigin() { /** * Execute `sql` (one or more `;`-separated statements) against a local D1. * Resolves to the explorer's per-statement results; rejects on any error. - * @param {"main" | "auth"} db + * @param {"main"} db * @param {string} sql * @returns {Promise>} */ export async function d1Local(db, sql) { const id = D1_DATABASES[db]; - if (!id) throw new Error(`Unknown database "${db}" (expected "main" or "auth")`); + if (!id) throw new Error(`Unknown database "${db}" (expected "main")`); const url = `${devApiOrigin()}/cdn-cgi/local/explorer/api/d1/database/${id}/raw`; let res; try { diff --git a/scripts/import-auth-data.mjs b/scripts/import-auth-data.mjs index a48973ce..93594b73 100644 --- a/scripts/import-auth-data.mjs +++ b/scripts/import-auth-data.mjs @@ -26,7 +26,7 @@ import { buildImportStatements } from "./lib/auth-import.mjs"; const args = process.argv.slice(2); const outIdx = args.indexOf("--out"); const outFile = outIdx >= 0 ? args[outIdx + 1] : "migration-data/annex-import.sql"; -const input = args.find((a, i) => !a.startsWith("--") && i !== outIdx + 1); +const input = args.find((a, i) => !a.startsWith("--") && (outIdx < 0 || i !== outIdx + 1)); if (!input) { console.error("Usage: node scripts/import-auth-data.mjs [--out ]"); process.exit(1); diff --git a/scripts/migrate.mjs b/scripts/migrate.mjs index 884f4ecc..65861a55 100644 --- a/scripts/migrate.mjs +++ b/scripts/migrate.mjs @@ -24,13 +24,11 @@ function run(label, cmd, cwd) { } const apiDir = resolve(root, "packages/api"); -const authDir = resolve(root, "packages/auth"); // `cf d1 migrations apply` takes the database ID (see each package's // cloudflare.config.ts) and reads ./migrations by default. It applies to the // remote database unless --local is passed. const API_DB_ID = "267490be-7141-4d00-ab23-152742f2f6ef"; // cubedocs-main -const AUTH_DB_ID = "db327d85-b8c2-4fed-adaa-25e748778c86"; // cubedocs-auth if (mode === "local") { run( @@ -38,22 +36,12 @@ if (mode === "local") { `npx cf d1 migrations apply ${API_DB_ID} --local --persist-to ../../.wrangler/state`, apiDir ); - run( - "Auth local migrations", - `npx cf d1 migrations apply ${AUTH_DB_ID} --local --persist-to ../../.wrangler/state`, - authDir - ); } else { run( "API remote migrations", `npx cf d1 migrations apply ${API_DB_ID}`, apiDir ); - run( - "Auth remote migrations", - `npx cf d1 migrations apply ${AUTH_DB_ID}`, - authDir - ); } console.log("\nAll migrations complete."); diff --git a/scripts/oidc-check.mjs b/scripts/oidc-check.mjs new file mode 100644 index 00000000..eaaf6a19 --- /dev/null +++ b/scripts/oidc-check.mjs @@ -0,0 +1,70 @@ +#!/usr/bin/env node +// End-to-end check of Annex's "Sign in with cubityfir.st" client registration +// from a dev machine: real sign-in, real code exchange, the same id_token checks +// the API worker runs (oauth4webapi: iss, aud, exp, iat, nonce, RS256 pinned, +// signature against the JWKS), then prints the claims. +// +// Useful before the new API worker is deployed: the registered redirect URI is +// the production callback, so the browser lands there (it may show a 404 until +// the new code is live) and you paste that URL back here. The code is +// single-use and short-lived, and this script redeems it itself. +// +// Usage (PowerShell: $env:OIDC_CLIENT_SECRET = Read-Host -MaskInput): +// OIDC_CLIENT_SECRET=... node scripts/oidc-check.mjs +// Optional: OIDC_ISSUER (https only - oauth4webapi refuses http, so this +// doesn't work against a local identity worker), OIDC_CLIENT_ID, +// OIDC_REDIRECT_URI. +// The secret is read from the environment and never printed; tokens aren't +// printed either. +// +// This runs on a dev machine, so it fetches the issuer directly. Worker code +// must never do that (same-zone fetch) - it goes through the IDENTITY_OIDC +// service binding (packages/api/src/account/oidc.ts). + +import * as oauth from "../packages/api/node_modules/oauth4webapi/build/index.js"; +import { createInterface } from "node:readline/promises"; + +const issuer = new URL(process.env.OIDC_ISSUER ?? "https://auth.cubityfir.st"); +const clientId = process.env.OIDC_CLIENT_ID ?? "oidc_7369d6d5736d2bea35f1ab47"; +const redirectUri = process.env.OIDC_REDIRECT_URI ?? "https://docs.cubityfir.st/api/auth/callback"; +const secret = process.env.OIDC_CLIENT_SECRET; +if (!secret) { + console.error("Set OIDC_CLIENT_SECRET in the environment (it is never printed)."); + process.exit(1); +} + +const as = await oauth.processDiscoveryResponse(issuer, await oauth.discoveryRequest(issuer, { algorithm: "oidc" })); +const client = { client_id: clientId, id_token_signed_response_alg: "RS256" }; + +const verifier = oauth.generateRandomCodeVerifier(); +const state = oauth.generateRandomState(); +const nonce = oauth.generateRandomNonce(); +const authorize = new URL(as.authorization_endpoint); +for (const [k, v] of Object.entries({ + client_id: clientId, + redirect_uri: redirectUri, + response_type: "code", + scope: "openid profile email roles", + state, + nonce, + code_challenge: await oauth.calculatePKCECodeChallenge(verifier), + code_challenge_method: "S256", +})) authorize.searchParams.set(k, v); + +console.log("\n1. Open this URL in a browser and sign in:\n\n" + authorize.href); +console.log("\n2. After the redirect, copy the FULL address from the browser's address bar."); +const rl = createInterface({ input: process.stdin, output: process.stdout }); +const pasted = (await rl.question("\nPaste the callback URL: ")).trim(); +rl.close(); + +const params = oauth.validateAuthResponse(as, client, new URL(pasted), state); +const res = await oauth.authorizationCodeGrantRequest(as, client, oauth.ClientSecretBasic(secret), params, redirectUri, verifier); +const tokens = await oauth.processAuthorizationCodeResponse(as, client, res, { expectedNonce: nonce, requireIdToken: true }); +await oauth.validateApplicationLevelSignature(as, res); +const claims = oauth.getValidatedIdTokenClaims(tokens); +const header = JSON.parse(Buffer.from(tokens.id_token.split(".")[0], "base64url").toString()); + +console.log("\nid_token checks passed: signature (JWKS), alg, iss, aud, exp, iat, nonce, state, PKCE."); +console.log("header:", { alg: header.alg, kid: header.kid }); +console.log("claims:", claims); +console.log(`\nadmin (roles includes "admin"): ${Array.isArray(claims.roles) && claims.roles.includes("admin")}`);