diff --git a/CLAUDE.md b/CLAUDE.md index f91a8cd4..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 @@ -88,37 +90,28 @@ A site owner can map their **own domain** (e.g. `docs.example.com`) to their pub **Critical invariant:** the custom domain serves a **published, read-only** public site only - never the authenticated app (sessions/JWT are per-origin). Host detection (`isCustomDomain` in `lib/siteUrl.ts`) treats `localhost`/`*.cubityfir.st`/`*.workers.dev`/`*.pages.dev`/`*.local` as app hosts; anything else is a custom domain and boots `CustomDomainApp` (site-only routes). When `CF_API_TOKEN`/`CF_ZONE_ID` are unset the endpoints report "not configured" and never call Cloudflare. -## Sign in with Annex (OIDC provider) - -Annex is an **OpenID Connect identity provider** (authorization-code + PKCE, RS256 -id_tokens via JWKS) so other first-party services can offer "Sign in with Annex". -Issuer is the dedicated host **`https://auth.cubityfir.st`** (the auth worker serves -`/oauth/{token,userinfo,jwks}` + `/.well-known/openid-configuration` there via routes -in its `cloudflare.config.ts`); the browser-facing **authorization_endpoint is a SPA page on -the app origin** `docs.cubityfir.st/oauth/authorize` because the user's Annex session -lives there. **Anything touching `oauth_clients`/`oauth_codes` (`0028_*`), `src/oidc.ts`, -`routes/oauth-*.ts`, the `/oauth/authorize` proxy, the `RATE_LIMITER_OIDC` binding, -`OAuthAuthorizePage`, the `OIDC_*` vars/secret, the admin client-management surface -(`packages/admin` `routes/oauth.ts` proxy + `OAuthClientsPage` "OAuth" tab → auth worker -`/admin/oauth/clients*`), or the `scripts/{gen-oidc-key,register-oauth-client}.mjs` -helpers belongs to this system** - see `memories/Oidc-Provider.md` and `docs/oauth/README.md`. - -**Critical invariants:** exact redirect-URI match only (no wildcards; never redirect to an -unvalidated URI); PKCE S256 mandatory and verified *before* the single-use code is consumed; -RS256 signs with a dedicated `OIDC_PRIVATE_KEY` (never the session `JWT_SECRET`) and the verifier -pins `alg`; disabled clients + suspended users are refused at authorize, token, AND userinfo. +## Identity provider (auth.cubityfir.st) + +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 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 @@ -126,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`. @@ -141,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 = ''" ``` @@ -152,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/docs/oauth/CONSUMER_PROMPT.md b/docs/oauth/CONSUMER_PROMPT.md deleted file mode 100644 index 5a6b5f19..00000000 --- a/docs/oauth/CONSUMER_PROMPT.md +++ /dev/null @@ -1,86 +0,0 @@ -# Prompt: wire up "Sign in with Annex" (OIDC) - -Copy everything in the block below into the other project's Claude agent. First -replace the three `<…>` placeholders with the values from -`scripts/register-oauth-client.mjs` (and the exact callback URL you registered). - -> ⚠️ The callback/redirect URL you put below must be registered **exactly** with -> the Annex provider (it's an exact-match allowlist). If you change it, re-register. - ---- - -``` -Add "Sign in with Annex" to this project. Annex is a standard OpenID Connect -(OIDC) provider - use a well-maintained OIDC client library for this stack, not -a hand-rolled flow. - -PROVIDER (everything else is discoverable): -- Issuer: https://auth.cubityfir.st -- Discovery: https://auth.cubityfir.st/.well-known/openid-configuration -- Flow: Authorization Code + PKCE (S256). id_tokens are RS256; verify - offline via the provider's JWKS (in the discovery doc). -- Scopes: openid profile email -- Claims you get: sub (stable unique user id - key your users on THIS, never on - email), email, email_verified, name, picture (avatar URL; may - 404 if the user has no avatar - fall back to your own placeholder). - -CREDENTIALS (store the secret server-side only - never ship it to the browser): -- client_id: -- client_secret: (omit if this is a public/SPA client) -- redirect_uri: (e.g. https://app.example.com/api/auth/callback/annex) - -REQUIREMENTS: -1. Configure the OIDC client from the discovery URL - do NOT hardcode the - authorization/token/userinfo/jwks endpoints (the authorization endpoint is on - a different host than the issuer; discovery handles that for you). -2. Use Authorization Code flow with PKCE (code_challenge_method=S256). -3. Send and verify `state` (CSRF) and a `nonce` (bound into the id_token). -4. Request scope "openid profile email". -5. On callback: exchange the code at the token endpoint (send the PKCE - code_verifier; include the client_secret only for a confidential/server-side - client), then VERIFY the id_token: signature against JWKS, and the iss, aud - (== client_id), exp, and nonce claims. Most OIDC libraries do this for you - - make sure it's enabled, not skipped. -6. Establish your app's own session from the verified identity. Use `sub` as the - primary key for the Annex identity; treat email as mutable. -7. The redirect_uri registered with Annex must match byte-for-byte what your app - sends (scheme, host, port, path). -8. (If this client was granted the `roles` scope) the id_token / userinfo carry a - `roles` string array. Gate admin-only features on `roles.includes("admin")` - - do NOT hardcode a user id or email for admin access. - -STACK-SPECIFIC GUIDANCE (pick what fits this project): -- Next.js / Auth.js (NextAuth): add a custom OIDC provider with - `{ id: "annex", name: "Annex", type: "oidc", issuer: "https://auth.cubityfir.st", - clientId, clientSecret, authorization: { params: { scope: "openid profile email" } }, - checks: ["pkce", "state", "nonce"] }`. Auth.js fetches discovery + JWKS and - verifies the id_token automatically. -- Node/Express: use `openid-client`. `Issuer.discover("https://auth.cubityfir.st")`, - then a `Client`, then `generators.codeVerifier()`/`codeChallenge()`, `client.authorizationUrl(...)`, - and `client.callback(...)` (which validates the id_token, state, nonce, PKCE). -- Python: `authlib` (`authlib.integrations.*` OAuth with - `server_metadata_url=".../.well-known/openid-configuration"`). -- Go: `coreos/go-oidc` + `golang.org/x/oauth2` (provider via `oidc.NewProvider`, - verify with `provider.Verifier`). -- Anything else: any conformant OIDC/OAuth2-with-PKCE client works - point it at - the discovery URL. - -Then: -- Add a "Sign in with Annex" button that starts the flow. -- Store the client_secret in the project's secret manager / env (never in client - code or the repo). -- Tell me the EXACT callback URL you wired up so it can be registered with Annex - (or confirm it matches above). -- Verify end-to-end: click the button, sign in, confirm a session is created and - the id_token's signature/iss/aud/nonce are validated. Show me the verified - claims you receive. -``` - ---- - -## If it's a browser-only SPA (no backend) - -Register the client with `--public` (no secret), and have the agent use a -browser OIDC library with PKCE (e.g. `oidc-client-ts`). The token endpoint -accepts public clients with PKCE and no secret. Never embed a `client_secret` in -front-end code. diff --git a/docs/oauth/README.md b/docs/oauth/README.md index 1cd406d0..0951283e 100644 --- a/docs/oauth/README.md +++ b/docs/oauth/README.md @@ -1,185 +1,21 @@ -# Sign in with Annex - OIDC provider - -Annex is an **OpenID Connect (OIDC) identity provider**. Other services you run -can offer a "Sign in with Annex" button: the user authenticates once against -their Annex account (password + TOTP + passkeys all apply, because the real -Annex login is reused) and your service receives a verified identity. - -It is a standard **authorization-code + PKCE** flow, so consuming services use -any off-the-shelf OIDC client library - there is no Annex-specific SDK. - -- **Provider side** (this doc): how the flow is built, the one-time setup, and - how to register a connected service. -- **Consumer side**: hand [`CONSUMER_PROMPT.md`](./CONSUMER_PROMPT.md) to the - agent working on the other service, filled in with that service's `client_id`, - `client_secret`, and callback URL. - ---- - -## Endpoints - -| Purpose | URL | -| --- | --- | -| Issuer (`iss`) | `https://auth.cubityfir.st` | -| Discovery | `https://auth.cubityfir.st/.well-known/openid-configuration` | -| Authorization (browser) | `https://docs.cubityfir.st/oauth/authorize` | -| Token | `https://auth.cubityfir.st/oauth/token` | -| UserInfo | `https://auth.cubityfir.st/oauth/userinfo` | -| JWKS | `https://auth.cubityfir.st/oauth/jwks` | - -The **authorization endpoint lives on the app origin** (`docs.cubityfir.st`), -not the issuer host. That's deliberate: the user's Annex session is a -browser-local token on the app origin, so the consent/login step has to happen -there. OIDC allows endpoints on different hosts - every client reads the exact -URLs from the discovery document, so this is transparent to consumers. - -**Scopes:** `openid` (required, yields `sub`), `profile` (adds `name` and -`picture` - a URL to the user's avatar; it 404s for users who haven't uploaded -one, so fall back to your own placeholder), `email` -(adds `email`, `email_verified`), `roles` (adds a `roles` array - `["user","admin"]` -for Annex platform-admins, `["user"]` otherwise; read live from `users.is_admin`). -A client must be granted `roles` at registration to receive it; gate admin-only -features on `roles.includes("admin")`. -**Signing:** RS256. id_tokens and access tokens are verifiable offline against -the JWKS. This key is **separate** from the Annex session `JWT_SECRET` - no -Annex secret is ever shared with a connected service. -**Tokens:** `id_token` + `access_token` (both JWT, 1-hour lifetime). - ---- - -## One-time provider setup - -1. **Generate the RS256 signing key** and store it as a secret: - ```bash - node scripts/gen-oidc-key.mjs - cd packages/auth && npx wrangler secret put OIDC_PRIVATE_KEY - # paste the printed JSON line when prompted - ``` - The public half is derived automatically and published at `/oauth/jwks`. - -2. **Add DNS for the issuer host.** In the Cloudflare dashboard, on the - **`cubityfir.st`** zone, add a **proxied** (orange-cloud) DNS record for - `auth` - e.g. `AAAA auth 100::` (a placeholder; the Worker route handles the - request, the record just makes the hostname resolve to Cloudflare's edge). - The `auth.cubityfir.st/oauth/*` and `/.well-known/*` routes in - `packages/auth/cloudflare.config.ts` attach the auth worker to those paths only - - nothing else on the auth worker is reachable at that host. - -3. **Apply the migration** (creates `oauth_clients` + `oauth_codes`): - ```bash - pnpm migrations:remote # cf d1 migrations apply for both DBs - # local dev: pnpm migrations:local - ``` - -4. **Deploy** the three workers that gained code (new tables aren't read by - `loadCurrentSession`, so the auth/api/admin triple-redeploy rule does *not* - apply here - but auth, api, and frontend each changed): - ```bash - cd packages/auth && pnpm run deploy # endpoints + routes (cf deploy) - cd packages/api && pnpm run deploy # /oauth/authorize proxy - cd packages/frontend && pnpm run deploy # /oauth/authorize SPA page - ``` - -5. **Smoke-test discovery + JWKS:** - ```bash - curl https://auth.cubityfir.st/.well-known/openid-configuration - curl https://auth.cubityfir.st/oauth/jwks - ``` - ---- - -## Registering a connected service - -### Option A - Admin dashboard (recommended) - -In the admin app (`admin.cubityfir.st`) → **OAuth** tab → **Register client**. -Enter a name, the exact redirect URI(s), scopes, and whether it's trusted / -public. The `client_id` + `client_secret` are shown **once** in a dialog (with -copy buttons and the discovery URL) - store the secret immediately. The same -page lists existing clients and lets you disable/enable, rotate the secret, or -delete them. (Backed by admin-only endpoints on the auth worker, proxied through -the admin worker - `packages/admin/src/routes/oauth.ts` → `auth` `/admin/oauth/clients*`.) - -### Option B - CLI - -```bash -node scripts/register-oauth-client.mjs \ - --name "My Dashboard" \ - --redirect "https://app.example.com/api/auth/callback/annex" -# add more --redirect for additional EXACT callback URLs -# --require-consent -> show a consent screen (default: trusted/auto-approve) -# --public -> SPA/native client (no secret; PKCE only) -``` - -It prints the `client_id` + `client_secret` (**secret shown once**) and writes a -`.sql` file. Apply it: - -```bash -cd packages/auth && npx wrangler d1 execute cubedocs-auth --remote --file -# local dev (with `pnpm dev` running), from the repo root: -node scripts/d1-local.mjs auth --file -``` - -Either way, put `client_id` + `client_secret` (+ the discovery URL) into the -connected service's config and follow [`CONSUMER_PROMPT.md`](./CONSUMER_PROMPT.md). - -- `redirect_uris` are matched **exactly** - register the precise callback URL(s), - including scheme, host, port, and path. No wildcards or trailing-slash slack. -- First-party services you run should stay **trusted** (auto-approve, no consent - screen). Use `--require-consent` only for something you don't fully control. - ---- - -## How the flow works - -``` -Service Browser Annex app (docs) Annex issuer (auth) - │ redirect to authorization_endpoint │ │ - │─────────────────────────────────────▶ /oauth/authorize (SPA) │ - │ │ (logs in via real Annex login │ - │ │ if no session; consent if not │ - │ │ trusted) │ - │ │ POST /api/oauth/authorize ──────▶ mint single-use code - │ 302 redirect_uri?code&state ◀───────│ │ - │ POST code + PKCE verifier (+secret) ───────────────────────────────────▶ /oauth/token - │ ◀───────────────────────── id_token + access_token (RS256) ────────────│ - │ verify id_token via JWKS, optionally GET /oauth/userinfo │ -``` - -PKCE (S256) is **mandatory**. `state` (CSRF) is echoed back. `nonce`, if sent, -is bound into the id_token. Authorization codes are single-use and expire in -5 minutes; consuming one a second time fails. - ---- - -## Operations - -- **Disable a client** (stops new sign-ins; keeps history): - `UPDATE oauth_clients SET disabled = 1 WHERE client_id = '…';` -- **Rotate a client secret:** re-run the register script for a new client, or - `UPDATE oauth_clients SET client_secret_hash = '' …`. -- **Tokens are short (1h)** and stateless - there is no token revocation list. - Disabling a client is refused at authorize, token, **and** userinfo, so its - access tokens stop resolving claims immediately (an id_token already delivered - to the consumer stays offline-verifiable until it expires). Disabling or - suspending a *user* likewise takes effect immediately at token + userinfo - (account standing is re-checked there). -- **Rotate the signing key:** generate a new key with a new `kid`. To avoid - invalidating live tokens, publish both keys in JWKS during the 1-hour overlap - before swapping `OIDC_PRIVATE_KEY` (current code serves a single key; extend - `/oauth/jwks` to an array for a zero-downtime roll). - -## Security model (why it's safe to point other services at it) - -- **Exact** redirect-URI matching - the primary defence against open-redirect / - token theft. No prefix or wildcard matching anywhere. -- **PKCE S256 mandatory** for every client; confidential clients additionally - authenticate with a secret at the token endpoint. -- **Single-use codes**, consumed atomically (`UPDATE … WHERE consumed_at IS NULL`). -- **RS256 with a dedicated key** - `JWT_SECRET` is never exposed; consumers - verify offline via JWKS. The token verifier pins `alg: RS256` (no alg-confusion). -- **Live account checks** - disabled/suspended/force-password-change users can't - obtain or use tokens even mid-session. -- The issuer host exposes **only** `/oauth/*` and `/.well-known/*`; the public - CORS (`*`) is scoped to those read/exchange endpoints, never the app session - routes. +# Sign in with cubityfir.st + +Annex is no longer an OpenID Connect provider. Since 2026-11-18 the identity +provider for every cubityfir.st service, Annex included, is the standalone +`cubityfirst-auth` worker at **https://auth.cubityfir.st**: hosted sign-in, +registration, account and security pages, OIDC endpoints, and client +management at `https://auth.cubityfir.st/admin/clients`. + +- Discovery: `https://auth.cubityfir.st/.well-known/openid-configuration` +- Authorization endpoint: `https://auth.cubityfir.st/oauth/authorize` + (the old `https://docs.cubityfir.st/oauth/authorize` redirects there, query + string included) +- Issuer, `sub` values (= Annex user ids) and existing client ids are + unchanged; the signing key is new, so verify id_tokens against the JWKS + from discovery. + +To connect a service, follow `docs/CONNECTING.md` in the `cubityfirst-auth` +repository. Workers on the `cubityfir.st` zone must reach the provider over a +service binding to `cubityfirst-auth` for every server-side request +(discovery, JWKS, token, userinfo): a Worker's `fetch()` to another Worker's +hostname on the same zone goes to the origin, not to that Worker. 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/Oidc-Provider.md b/memories/Oidc-Provider.md deleted file mode 100644 index d1840e10..00000000 --- a/memories/Oidc-Provider.md +++ /dev/null @@ -1,72 +0,0 @@ -# Sign in with Annex - OIDC provider - -Annex is an OpenID Connect identity provider so other first-party services can -offer "Sign in with Annex". Standard **authorization-code + PKCE**, RS256 -id_tokens verifiable offline via JWKS - consumers use any OIDC client library. -Generalizes the single-purpose admin handoff (`admin_handoffs`, 0009). - -## Hosts / endpoints -- **Issuer** = `https://auth.cubityfir.st` (dedicated identity host, decoupled - from the app origin which may migrate). The auth worker serves - `/oauth/{token,userinfo,jwks}` + `/.well-known/openid-configuration` there - directly via two routes in `packages/auth/cloudflare.config.ts` (`auth.cubityfir.st/oauth/*`, - `/.well-known/*`). Needs a **proxied** DNS record for `auth.cubityfir.st` on - the `cubityfir.st` zone. -- **authorization_endpoint** = `https://docs.cubityfir.st/oauth/authorize` - a - SPA page on the APP origin (the user's Annex session/JWT lives there, not on - the issuer host). It POSTs to `/api/oauth/authorize` (frontend → api → auth - via the `AUTH` binding) with the user's Bearer JWT to mint a single-use code. - -## Key files -- `packages/auth/src/oidc.ts` - pure crypto/helpers: RS256 sign/verify, JWKS - derivation, PKCE (S256), `resolveScopes`, exact `redirectUriAllowed`, claim - builders. Scopes: `openid`/`profile`/`email`/`roles`. `profile` adds `name` + - `picture` (the latter built as `${APP_ORIGIN}/api/avatar/{id}` in the token + - userinfo handlers, not in `scopedClaims`; the avatar endpoint 404s for users - with no avatar). The `roles` scope adds a - `roles` array claim via `rolesForUser` (admins → `["user","admin"]`, else - `["user"]`), sourced live from `users.is_admin` at token+userinfo time - lets - connected services gate admin features on `roles.includes("admin")`. Unit-tested - in `oidc.test.ts` (PKCE RFC vectors, alg-confusion, exact redirect match, - RS256 round-trip, roles). -- `packages/auth/src/routes/oauth-{authorize,token,userinfo,discovery}.ts`. -- `packages/auth/src/routes/oauth-clients.ts` - **admin-only** client CRUD - (`/admin/oauth/clients` GET/POST + `/set-disabled`, `/delete`, `/rotate-secret`). - NOT on the public routes; reached only via the admin worker's `AUTH` binding; - each handler re-checks `session.isAdmin`. Secrets generated/hashed here. -- Admin UI: `packages/admin/src/routes/oauth.ts` (thin proxy under - `/api/oauth-clients`, gated by `enforceAdmin`) + `packages/admin/frontend/src/pages/OAuthClientsPage.tsx` - (the "OAuth" nav tab - register/list/disable/rotate/delete; secret shown once). -- `packages/auth/src/index.ts` - routing + **path-aware CORS** (public OIDC - paths = `*`; everything else locked to the app origin) + `RATE_LIMITER_OIDC`. -- `packages/auth/migrations/0028_add_oauth_clients.sql` - `oauth_clients` - (exact-match `redirect_uris` JSON, hashed secret, `trusted`/`disabled`) + - `oauth_codes` (single-use, PKCE-bound, 5-min). -- `packages/api/src/index.ts` - proxies `/oauth/authorize` only. -- `packages/frontend/src/pages/OAuthAuthorizePage.tsx` (+ App.tsx route). -- `scripts/gen-oidc-key.mjs` (RS256 key → `OIDC_PRIVATE_KEY` secret), - `scripts/register-oauth-client.mjs` (per-service client_id/secret + SQL). -- Docs: `docs/oauth/README.md` (provider/ops), `docs/oauth/CONSUMER_PROMPT.md` - (paste into the connected service's agent). - -## Security invariants -- **Exact** redirect-URI match only (no wildcard/prefix). The `/oauth/authorize` - endpoint NEVER emits a `redirectTo` until the URI is validated; pre-validation - failures (unknown/disabled client, bad redirect) return a plain 400 with no - redirect. -- **PKCE S256 mandatory** for all clients; verified **before** the code is - atomically consumed (so a bad verifier can't burn an unredeemed code). - Confidential clients also auth with a secret (Basic or post). -- Codes consumed atomically (`UPDATE … WHERE consumed_at IS NULL`, assert 1 row). -- **RS256 with a dedicated key** (`OIDC_PRIVATE_KEY`) - `JWT_SECRET` is NEVER - shared. Verifier pins `alg: RS256` (no alg-confusion). -- Live account standing re-checked at token + userinfo; **disabled client** - refused at authorize, token, AND userinfo (so disabling cuts off existing - access tokens, not just new ones). -- Tokens are stateless, 1h, no revocation list - disable the client to cut off. - -## Deploy -New tables aren't read by `loadCurrentSession`, so the auth/api/admin -triple-redeploy rule does NOT apply. But auth + api + frontend all changed: -migrate auth DB → deploy auth → api → frontend. See `docs/oauth/README.md` for -the full one-time setup (key, DNS, migrate, deploy, register client). 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 8495fa58..28d9b14d 100644 --- a/packages/admin/cloudflare.config.ts +++ b/packages/admin/cloudflare.config.ts @@ -4,10 +4,10 @@ export default defineConfig({ accountId: "d843ae90cab33e54f4d284bc65d2fd6a", worker: { name: "annex-admin", - // Keep in lockstep with the auth worker's compatibilityDate: this worker - // imports auth source (session.ts/jwt.ts) cross-package, so runtime-behavior - // differences between dates would make shared code behave differently per - // worker. + // Keep in lockstep with the api worker's compatibilityDate: this worker + // imports api source (account/*, routes/auth.ts) cross-package, so + // runtime-behavior differences between dates would make shared code behave + // differently per worker. compatibilityDate: "2026-02-24", entrypoint: "src/index.ts", workersDev: false, @@ -21,8 +21,8 @@ export default defineConfig({ "admin.cubityfir.st", ], triggers: [ - // Hourly: performs account deletions scheduled from the Users page once - // their grace window has passed (src/lib/userDeletion.ts + // Hourly: performs Annex-data deletions scheduled from the Users page + // once their grace window has passed (src/lib/userDeletion.ts // runDueUserDeletions). triggers.scheduled({ schedule: "17 * * * *", @@ -41,25 +41,34 @@ export default defineConfig({ name: "cubedocs-main", id: "267490be-7141-4d00-ab23-152742f2f6ef", }), - // Read+write: unlike the API worker's read-only-by-convention AUTH_DB - // binding, the admin worker writes users (moderation/ - // force_password_change), user_moderation_events, user_preferences - // (badges), user_billing (grant columns), and admin_audit_log directly. - // Credential/session/oauth_clients writes still go through the AUTH - // service binding. Migrations live only in packages/auth/migrations/. - AUTH_DB: bindings.d1({ - name: "cubedocs-auth", - id: "db327d85-b8c2-4fed-adaa-25e748778c86", + // 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 (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("oidc_07c81f4a5aa63dd2bd0b15cc"), + APP_ORIGIN: bindings.text("https://admin.cubityfir.st"), + // Identity service RPC (live standing + admin role, user lookups). + IDENTITY: bindings.worker({ + worker: "cubityfirst-auth", + exportName: "IdentityService", + }), + // The identity worker's HTTP surface (default export) for server-side + // OIDC requests (discovery, JWKS, token). Required: a Worker's fetch() + // to auth.cubityfir.st from this same zone goes to the origin, not to + // the identity worker. Only the browser redirects use the public URL. + IDENTITY_OIDC: bindings.worker({ + worker: "cubityfirst-auth", }), ASSETS: bindings.r2({ name: "cubedocs-assets", }), - AUTH: bindings.worker({ - worker: "annex-auth", - }), - // GA ratelimit bindings - simulated locally in dev. See the auth - // worker's cloudflare.config.ts. - // IP-keyed coarse abuse cap across every authenticated admin API route. + // GA ratelimit bindings - simulated locally in dev. + // IP-keyed coarse abuse cap across every authenticated admin API route + // and the sign-in endpoints. // Generous enough for an operator clicking around the dashboard; only // bites scripted abuse with a stolen admin token. RATE_LIMITER_ADMIN: bindings.rateLimit({ @@ -69,15 +78,6 @@ export default defineConfig({ period: 60, }, }), - // Tighter, separate bucket for the unauthenticated handoff-exchange - // proxy (the only pre-auth endpoint that hits the auth worker + DB). - RATE_LIMITER_ADMIN_HANDOFF: bindings.rateLimit({ - namespace: "2002", - simple: { - limit: 10, - period: 60, - }, - }), // Separate budget for the public avatar route: a 25-row dashboard page // costs 25 avatar fetches, which previously drained the shared admin // API budget and started 429ing the operator after ~2 searches/min. @@ -91,12 +91,12 @@ export default defineConfig({ SITE_ASSETS: bindings.assets(), // Secrets (set via `npx wrangler secret put --name annex-admin`; // existing secrets are kept across `cf deploy`): - // JWT_SECRET (same value as the auth worker's JWT_SECRET - the - // admin worker verifies sessions inline against - // AUTH_DB instead of calling auth's /verify route) - // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - same value as auth - // worker; only used for admin-driven cancellations - // triggered from the user details panel) + // JWT_SECRET (signs this panel's own 'admin' session JWTs; + // Annex-only, not shared with the identity service) + // OIDC_CLIENT_SECRET (the annex-admin client's secret from + // auth.cubityfir.st) + // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - same value as the api + // worker; used for admin-driven Stripe actions) // CF_API_TOKEN (same token as the api worker - zone-scoped, SSL // and Certificates: Edit; only used to release a // custom hostname on admin-driven site delete) diff --git a/packages/admin/frontend/src/App.test.tsx b/packages/admin/frontend/src/App.test.tsx index 91c2f180..ec203323 100644 --- a/packages/admin/frontend/src/App.test.tsx +++ b/packages/admin/frontend/src/App.test.tsx @@ -4,23 +4,21 @@ import { render, screen, waitFor } from "@testing-library/react"; vi.mock("@/lib/api", () => { class TransientVerifyError extends Error {} - class AdminHandoffError extends Error { + class AdminSignInError extends Error { constructor(public readonly code: string) { super(code); } } return { TransientVerifyError, - AdminHandoffError, + AdminSignInError, LIST_PAGE_SIZE: 25, verifyAdminSession: vi.fn(), - logoutAdminSession: vi.fn(async () => undefined), - exchangeAdminHandoff: vi.fn(), + logoutAdminSession: vi.fn(async () => null), + exchangeAdminCode: vi.fn(), searchUsers: vi.fn(async () => ({ users: [], nextCursor: null })), getUserDetails: vi.fn(), updateUserBadges: vi.fn(), - updateUserModeration: vi.fn(), - forceUserPasswordChange: vi.fn(), deleteUserAvatar: vi.fn(), exportUserData: vi.fn(), grantInk: vi.fn(), @@ -36,16 +34,11 @@ vi.mock("@/lib/api", () => { removeProjectDomain: vi.fn(), listAuditLog: vi.fn(async () => ({ entries: [], nextCursor: null })), listAuditActions: vi.fn(async () => []), - listOAuthClients: vi.fn(async () => []), - createOAuthClient: vi.fn(), - deleteOAuthClient: vi.fn(), - rotateOAuthClientSecret: vi.fn(), - setOAuthClientDisabled: vi.fn(), }; }); 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 = { @@ -71,7 +64,7 @@ beforeEach(() => { describe("App session gating", () => { it("shows the login page with no token", async () => { renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(verifyAdminSession).not.toHaveBeenCalled(); }); @@ -87,7 +80,7 @@ describe("App session gating", () => { setToken("tok"); vi.mocked(verifyAdminSession).mockRejectedValue(new Error("Unauthorized")); renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(getToken()).toBeNull(); }); @@ -97,7 +90,7 @@ describe("App session gating", () => { renderApp(); expect(await screen.findByText(/Couldn't reach the admin API/)).toBeInTheDocument(); expect(screen.getByText("Retry")).toBeInTheDocument(); - expect(screen.queryByText(/Continue to Annex sign-in/)).not.toBeInTheDocument(); + expect(screen.queryByText(/Continue to sign-in/)).not.toBeInTheDocument(); expect(getToken()).toBe("tok"); }); @@ -105,7 +98,18 @@ describe("App session gating", () => { setToken("tok"); vi.mocked(verifyAdminSession).mockResolvedValue({ ...SESSION, expiresAt: Date.now() - 1000 }); renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + 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 0a86c381..d5b78b6f 100644 --- a/packages/admin/frontend/src/App.tsx +++ b/packages/admin/frontend/src/App.tsx @@ -1,16 +1,15 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { Link, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom"; -import { Flag, KeyRound, ScrollText, Users, Boxes } from "lucide-react"; +import { Flag, KeyRound, ScrollText, Users, Boxes, ExternalLink } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ADMIN_AUTH_INVALIDATED_EVENT, clearToken, getToken } from "@/lib/auth"; -import { buildDocsAdminLoginUrl } from "@/lib/handoff"; 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"; -import { OAuthClientsPage } from "./pages/OAuthClientsPage"; import { ReportsPage } from "./pages/ReportsPage"; function AdminLayout({ @@ -71,15 +70,14 @@ function AdminLayout({ Audit - @@ -99,7 +97,6 @@ function AdminLayout({ } /> } /> } /> - } /> } /> @@ -114,7 +111,7 @@ export function App() { const [checking, setChecking] = useState(true); // Set when the session couldn't be VERIFIED (network down, API 5xx) as // opposed to being invalid - the token is kept and the operator gets a - // retry instead of being bounced through a full re-handoff. + // retry instead of being bounced through a full re-sign-in. const [verifyBlocked, setVerifyBlocked] = useState(null); // Latest session for the stable refreshSession callback (its deps are // empty so the closed-over `session` would always be the initial null). @@ -183,7 +180,7 @@ export function App() { setSession(null); setChecking(false); - if (location.pathname === "/login" || location.pathname === "/auth/callback") { + if (location.pathname === "/login" || location.pathname === "/auth/complete") { return; } @@ -203,14 +200,17 @@ export function App() { // Revoke the session server-side FIRST (while the token still works): // clearing local state alone would leave any copy of the token valid // until its TTL. Best-effort - local sign-out proceeds regardless. + let logoutUrl: string | null = null; try { - await logoutAdminSession(); + logoutUrl = await logoutAdminSession(); } catch { /* offline / already-revoked - still sign out locally */ } clearToken(); setSession(null); - window.location.assign(buildDocsAdminLoginUrl("/", { logout: true })); + // Continue to the identity service's end-session URL so the sign-out + // covers auth.cubityfir.st too; it comes back to the panel. + window.location.assign(logoutUrl ?? "/login"); } if (checking) { @@ -239,7 +239,7 @@ export function App() { return ( } /> - } /> + } /> ; + } + if (location.pathname === "/login") { return ; } diff --git a/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx b/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx new file mode 100644 index 00000000..ef61e7e4 --- /dev/null +++ b/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx @@ -0,0 +1,89 @@ +import { useEffect, useState } from "react"; +import { AlertTriangle } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { type OrphanedOwnership, listOrphanedOwnership } from "@/lib/api"; +import { formatDateTime } from "@/lib/format"; + +// Sites and orgs whose owner deleted their account on auth.cubityfir.st. The +// deletion sync keeps them (other members may still rely on them); an +// operator decides here whether to delete them. Renders nothing when there's +// nothing to review. +export function OrphanedOwnershipCard({ onFilterSite, refreshKey }: { onFilterSite: (name: string) => void; refreshKey: unknown }) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + const controller = new AbortController(); + listOrphanedOwnership(controller.signal) + .then(d => { setData(d); setError(null); }) + .catch(e => { if (!controller.signal.aborted) setError(e instanceof Error ? e.message : "Failed to load"); }); + return () => controller.abort(); + }, [refreshKey]); + + if (error) { + return

Couldn't load sites with deleted owners: {error}

; + } + if (!data || (data.sites.length === 0 && data.orgs.length === 0 && data.pending_deletions.length === 0)) return null; + + return ( + + + + + Owner account deleted + +

+ These owners deleted their account on auth.cubityfir.st. Their sites and organizations were kept for + review: delete them here, or leave them for the remaining members. +

+
+ + {data.sites.map(site => ( +
+
+

{site.name}

+

{site.id}

+

+ Owner deleted {formatDateTime(new Date(site.owner_deleted_at).toISOString())} ·{" "} + {site.other_members} other member{site.other_members === 1 ? "" : "s"} +

+
+
+ {site.published && Published} + +
+
+ ))} + {data.orgs.map(org => ( +
+

{org.name} (organization)

+

{org.id}

+

+ Owner deleted {formatDateTime(new Date(org.owner_deleted_at).toISOString())} · {org.sites} attached site + {org.sites === 1 ? "" : "s"} +

+
+ ))} + {data.pending_deletions.length > 0 && ( +
+

+ {data.pending_deletions.length} deleted account{data.pending_deletions.length === 1 ? "" : "s"} not cleaned up yet +

+
    + {data.pending_deletions.map(p => ( +
  • + {p.user_id} + {p.last_error ? ` - ${p.last_error}` : " - waiting for the next hourly run"} +
  • + ))} +
+
+ )} +
+
+ ); +} diff --git a/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.test.tsx b/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.test.tsx index 7a1eaafb..bc05b829 100644 --- a/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.test.tsx +++ b/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.test.tsx @@ -71,7 +71,7 @@ describe("BulkDeleteUsersDialog", () => { // The site is flagged with its details before anything happens. expect(await screen.findByText("Big Site")).toBeInTheDocument(); - expect(para(/^1 account will be disabled now and deleted in 7 days; 1 skipped.$/)).toBeInTheDocument(); + expect(para(/^1 account will be blocked now and their Annex data deleted in 7 days; 1 skipped.$/)).toBeInTheDocument(); expect(screen.queryByText(/will be permanently deleted with all docs/)).not.toBeInTheDocument(); // Delete stays disabled until the confirm word is typed. diff --git a/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.tsx b/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.tsx index e8a0e76a..7492a3f5 100644 --- a/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.tsx +++ b/packages/admin/frontend/src/components/users/BulkDeleteUsersDialog.tsx @@ -134,11 +134,13 @@ export function BulkDeleteUsersDialog({ open, onOpenChange, userIds, onScheduled { if (!running) onOpenChange(next); }}> - Schedule deletion of {title}? + Schedule deletion of Annex data for {title}? - Accounts are disabled immediately and permanently deleted in {DELETION_GRACE_DAYS} days. Until then any - admin can cancel from the Users page. When the deletion runs, each account's sessions, passkeys, billing - and memberships are removed, and any Stripe customer is deleted (which cancels their subscription). + They're blocked from Annex immediately and their Annex data is permanently deleted in{" "} + {DELETION_GRACE_DAYS} days. Until then any admin can cancel from the Users page. When the deletion runs, + each person's Annex sessions, billing, preferences and memberships are removed, and any Stripe customer + is deleted (which cancels their subscription). The cubityfir.st account itself is not deleted: do that on + auth.cubityfir.st afterwards. @@ -226,8 +228,8 @@ export function BulkDeleteUsersDialog({ open, onOpenChange, userIds, onScheduled

- {plural(plan.deletable.length, "account")} will be disabled now - and deleted in {DELETION_GRACE_DAYS} days{plan.skipped.length > 0 && <>; {plan.skipped.length} skipped}. + {plural(plan.deletable.length, "account")} will be blocked now + and their Annex data deleted in {DELETION_GRACE_DAYS} days{plan.skipped.length > 0 && <>; {plan.skipped.length} skipped}.

{plan.sites.length > 0 && (

diff --git a/packages/admin/frontend/src/components/users/BulkDisableUsersDialog.tsx b/packages/admin/frontend/src/components/users/BulkDisableUsersDialog.tsx deleted file mode 100644 index efc799cc..00000000 --- a/packages/admin/frontend/src/components/users/BulkDisableUsersDialog.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { useEffect, useState } from "react"; -import { toast } from "sonner"; -import { Button } from "@/components/ui/button"; -import { Label } from "@/components/ui/label"; -import { Textarea } from "@/components/ui/textarea"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { type AdminUser, updateUserModeration } from "@/lib/api"; -import { runBulk } from "@/lib/bulk"; - -export interface BulkDisableUsersDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - users: AdminUser[]; - onDone: () => void; -} - -// Disables every selected account indefinitely with one shared reason. -// Already-disabled accounts are left alone so their existing reason isn't -// overwritten; suspended accounts become indefinitely disabled. For a timed -// suspension, use the per-user "Disable account" dialog. -export function BulkDisableUsersDialog({ open, onOpenChange, users, onDone }: BulkDisableUsersDialogProps) { - const [reason, setReason] = useState(""); - const [running, setRunning] = useState(false); - // Snapshot at open time so a background list refresh can't change the - // target set after the operator has read the title. - const [snapshot, setSnapshot] = useState([]); - useEffect(() => { - if (open) setSnapshot(users); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [open]); - const targets = snapshot.filter(u => u.moderation !== -1); - const alreadyDisabled = snapshot.length - targets.length; - const nowSeconds = Math.floor(Date.now() / 1000); - const suspended = targets.filter(u => u.moderation > nowSeconds).length; - - function handleOpenChange(next: boolean) { - if (running) return; - if (!next) setReason(""); - onOpenChange(next); - } - - async function handleDisable() { - const trimmed = reason.trim(); - if (!trimmed) return; - setRunning(true); - try { - const result = await runBulk(targets.map(u => u.id), id => updateUserModeration(id, -1, trimmed)); - if (result.succeeded.length > 0) { - toast.success(`Disabled ${result.succeeded.length} account${result.succeeded.length === 1 ? "" : "s"}`); - } - for (const f of result.failed) { - const email = snapshot.find(u => u.id === f.id)?.email ?? f.id; - toast.error(`${email}: ${f.error}`); - } - onDone(); - } finally { - setRunning(false); - setReason(""); - onOpenChange(false); - } - } - - return ( -

- - - - Disable {targets.length} account{targets.length === 1 ? "" : "s"}? - - - These accounts won't be able to sign in until an administrator re-enables them. - {suspended > 0 && ` ${suspended} currently suspended account${suspended === 1 ? " becomes" : "s become"} disabled indefinitely.`} - {alreadyDisabled > 0 && ` ${alreadyDisabled} already-disabled account${alreadyDisabled === 1 ? " is" : "s are"} left unchanged.`} - - - -
- -