From 1b0d7f7071cf273655dc4df892caf75e62149a83 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:05:07 +0000 Subject: [PATCH 1/4] feat(api): add users mirror and Annex account tables to cubedocs-main Annex is becoming an OIDC client of auth.cubityfir.st. Migration 0065 adds the local users mirror, Annex's own sessions table, and the Annex-only tables that used to live in cubedocs-auth (user_billing, user_preferences, webhook_events, user_deletions, user_moderation_events, admin_audit_log), plus identity_deletions for the deletion sync. scripts/import-auth-data.mjs turns a cubedocs-auth export into INSERT OR IGNORE statements for cubedocs-main (one-time cutover copy). --- .gitignore | 3 + .../migrations/0065_add_identity_mirror.sql | 186 ++++++++++++++++++ packages/api/package.json | 1 + packages/api/src/test/authImport.test.ts | 113 +++++++++++ pnpm-lock.yaml | 8 + scripts/fixtures/cubedocs-auth-schema.sql | 182 +++++++++++++++++ scripts/import-auth-data.mjs | 58 ++++++ scripts/lib/auth-import.mjs | 134 +++++++++++++ 8 files changed, 685 insertions(+) create mode 100644 packages/api/migrations/0065_add_identity_mirror.sql create mode 100644 packages/api/src/test/authImport.test.ts create mode 100644 scripts/fixtures/cubedocs-auth-schema.sql create mode 100644 scripts/import-auth-data.mjs create mode 100644 scripts/lib/auth-import.mjs diff --git a/.gitignore b/.gitignore index c16a0bf..e27a5ff 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,6 @@ coverage/ .claude/worktrees/ /.worktree-ports.json /research/ + +# One-time identity-split data exports (personal data - never commit) +migration-data/ diff --git a/packages/api/migrations/0065_add_identity_mirror.sql b/packages/api/migrations/0065_add_identity_mirror.sql new file mode 100644 index 0000000..9c69b67 --- /dev/null +++ b/packages/api/migrations/0065_add_identity_mirror.sql @@ -0,0 +1,186 @@ +-- Annex becomes an OpenID Connect client of the identity service at +-- auth.cubityfir.st (worker `cubityfirst-auth`). Identity (passwords, 2FA, +-- passkeys, email changes, account moderation) lives there now; everything +-- Annex-specific moves into this database, keyed on the same user ids (the +-- OIDC `sub` is the existing Annex user id). +-- +-- One-time data copy from cubedocs-auth: scripts/import-auth-data.mjs. + +-- Local mirror of the identity account. Refreshed on every sign-in and from +-- IdentityService.getUser (see src/session.ts), so it can be a little stale. +-- email is deliberately NOT unique: the identity service owns uniqueness, and +-- a stale mirror (A changed address, B then took A's old one) must not make +-- B's first sign-in fail. +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL, + name TEXT NOT NULL, + email_verified INTEGER NOT NULL DEFAULT 0, + is_admin INTEGER NOT NULL DEFAULT 0, + -- Last known standing on the identity service: 'active' | 'disabled' | + -- 'suspended' (suspended_until = unix seconds). + status TEXT NOT NULL DEFAULT 'active', + suspended_until INTEGER, + -- Account creation time as reported by the identity service. + created_at TEXT NOT NULL, + first_seen_at INTEGER NOT NULL, + last_login_at INTEGER, + synced_at INTEGER NOT NULL +); + +CREATE INDEX users_created_at ON users(created_at DESC, id DESC); +CREATE INDEX idx_users_email_lower ON users(lower(email)); +CREATE INDEX idx_users_not_active ON users(created_at DESC, id DESC) WHERE status <> 'active'; + +-- Annex's own sessions, created from a verified id_token. The session JWT +-- carries the row id as `sid`. kind separates the docs app from the admin +-- panel so a token minted for one is refused by the other. +-- +-- id_token is kept for RP-initiated logout (id_token_hint). handoff_hash is +-- the SHA-256 of the single-use code /auth/callback hands the SPA; the SPA +-- exchanges it for the session JWT once, within handoff_expires_at. +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + kind TEXT NOT NULL DEFAULT 'app', + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_used_at INTEGER NOT NULL, + device_kind TEXT, + client_label TEXT, + ip TEXT, + revoked_at INTEGER, + id_token TEXT, + handoff_hash TEXT, + handoff_expires_at INTEGER +); + +CREATE INDEX idx_sessions_user_id ON sessions(user_id); +CREATE INDEX idx_sessions_expires_at ON sessions(expires_at); +CREATE UNIQUE INDEX idx_sessions_handoff ON sessions(handoff_hash) WHERE handoff_hash IS NOT NULL; + +-- Stripe + Ink plan state (was cubedocs-auth user_billing, same columns). +CREATE TABLE user_billing ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + stripe_customer_id TEXT, + stripe_subscription_id TEXT, + personal_period_end INTEGER, + personal_plan TEXT, + personal_plan_status TEXT, + personal_plan_started_at INTEGER, + personal_plan_cancel_at INTEGER, + granted_plan TEXT, + granted_plan_expires_at INTEGER, + granted_plan_started_at INTEGER, + granted_plan_reason TEXT +); + +CREATE INDEX idx_user_billing_subscription ON user_billing(stripe_subscription_id); + +-- Fonts, theme, Ink cosmetics, timezone, bio, badges and the /@ +-- profile link (was cubedocs-auth user_preferences, same columns). +CREATE TABLE user_preferences ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + reading_font TEXT, + editing_font TEXT, + ui_font TEXT, + personal_plan_style TEXT, + personal_presence_color TEXT, + personal_crit_sparkles INTEGER, + timezone TEXT, + bio TEXT, + badges INTEGER NOT NULL DEFAULT 0, + theme_mode TEXT, + theme_custom_color TEXT, + handle TEXT, + handle_locked INTEGER NOT NULL DEFAULT 0 +); + +CREATE UNIQUE INDEX idx_user_preferences_handle ON user_preferences(handle) WHERE handle IS NOT NULL; + +-- Stripe webhook idempotency markers. +CREATE TABLE webhook_events ( + event_id TEXT PRIMARY KEY, + type TEXT NOT NULL, + processed_at INTEGER NOT NULL +); + +CREATE INDEX idx_webhook_events_processed ON webhook_events(processed_at); + +-- Admin-scheduled deletion of a user's Annex data (admin lib/userDeletion.ts). +-- A row blocks the user from Annex for as long as it exists: scheduling +-- blocks at once, cancel deletes the row, and completion keeps it +-- (completed_at set) so the user stays locked out until the identity account +-- itself is deleted at auth.cubityfir.st - at which point the deletion sync +-- removes the users row and this one cascades with it. +-- +-- id identifies THIS schedule: the cron claims a row by (user_id, id), so a +-- cancel + reschedule can never be executed on the old schedule's consent. +CREATE TABLE user_deletions ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + id TEXT NOT NULL, + requested_by TEXT NOT NULL, + requested_by_email TEXT NOT NULL, + requested_at TEXT NOT NULL DEFAULT (datetime('now')), + execute_after INTEGER NOT NULL, + confirm_site_ids TEXT NOT NULL DEFAULT '[]', + confirm_org_ids TEXT NOT NULL DEFAULT '[]', + lease_until INTEGER, + started_at INTEGER, + completed_at INTEGER, + last_error TEXT, + last_attempt_at TEXT +); + +CREATE INDEX idx_user_deletions_execute_after ON user_deletions(execute_after); + +-- History of moderation actions taken from the Annex admin panel before the +-- split. Moderation itself happens on auth.cubityfir.st now; kept read-only. +CREATE TABLE user_moderation_events ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + action TEXT NOT NULL, + moderation_value INTEGER NOT NULL, + reason TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + actor_user_id TEXT, + actor_email TEXT +); + +CREATE INDEX user_moderation_events_user_id_created_at + ON user_moderation_events(user_id, created_at DESC); + +-- Actor-attributed log of admin-panel actions. No FKs on purpose: rows must +-- outlive the actor and the target. +CREATE TABLE admin_audit_log ( + id TEXT PRIMARY KEY, + actor_user_id TEXT NOT NULL, + actor_email TEXT NOT NULL, + action TEXT NOT NULL, + target_type TEXT NOT NULL, + target_id TEXT, + detail TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX admin_audit_log_created_at ON admin_audit_log(created_at DESC); +CREATE INDEX admin_audit_log_actor ON admin_audit_log(actor_user_id, created_at DESC); +CREATE INDEX admin_audit_log_target ON admin_audit_log(target_type, target_id, created_at DESC); +CREATE INDEX idx_admin_audit_log_action_created ON admin_audit_log(action, created_at DESC, id DESC); + +-- Accounts deleted on the identity service, fed by the hourly deletion sync +-- (IdentityService.listDeletedUsers; src/lib/identityDeletions.ts). MAX(deleted_at) +-- is the sync cursor. Owned sites/orgs are NOT deleted: their ids are recorded +-- here and the admin panel lists them for an operator to resolve. +CREATE TABLE identity_deletions ( + user_id TEXT PRIMARY KEY, + deleted_at INTEGER NOT NULL, + deleted_by TEXT NOT NULL, + processed_at INTEGER, + owned_site_ids TEXT NOT NULL DEFAULT '[]', + owned_org_ids TEXT NOT NULL DEFAULT '[]', + last_error TEXT +); + +CREATE INDEX idx_identity_deletions_deleted_at ON identity_deletions(deleted_at); +CREATE INDEX idx_identity_deletions_pending ON identity_deletions(deleted_at) WHERE processed_at IS NULL; diff --git a/packages/api/package.json b/packages/api/package.json index 132e9ab..6591951 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -16,6 +16,7 @@ "aws4fetch": "^1.0.20", "fflate": "^0.8.2", "lib0": "^0.2.0", + "oauth4webapi": "3.8.8", "y-protocols": "^1.0.6", "yjs": "^13.6.0" }, diff --git a/packages/api/src/test/authImport.test.ts b/packages/api/src/test/authImport.test.ts new file mode 100644 index 0000000..12aaa9f --- /dev/null +++ b/packages/api/src/test/authImport.test.ts @@ -0,0 +1,113 @@ +// scripts/lib/auth-import.mjs: the one-time cubedocs-auth -> cubedocs-main +// copy. Builds a source DB from the frozen cubedocs-auth schema, runs the +// generated statements against the real, fully migrated main schema, and +// checks what lands. +import { describe, it, expect } from "vitest"; +import { DatabaseSync } from "node:sqlite"; +import { readdirSync, readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +// @ts-expect-error - plain .mjs script module, no type declarations +import { buildImportStatements, sqlValue, standingFromModeration } from "../../../../scripts/lib/auth-import.mjs"; + +const AUTH_SCHEMA = fileURLToPath(new URL("../../../../scripts/fixtures/cubedocs-auth-schema.sql", import.meta.url)); +const MAIN_MIGRATIONS = fileURLToPath(new URL("../../migrations", import.meta.url)); + +const NOW = Date.UTC(2026, 10, 18, 12, 0, 0); +const NOW_S = Math.floor(NOW / 1000); + +function authDb(): DatabaseSync { + const db = new DatabaseSync(":memory:"); + db.exec(readFileSync(AUTH_SCHEMA, "utf8")); + const user = db.prepare( + "INSERT INTO users (id, email, name, password_hash, created_at, moderation, is_admin, email_verified) VALUES (?, ?, ?, 'x', ?, ?, ?, ?)", + ); + user.run("u-active", "a@example.com", "Ann O'Neil", "2025-01-02T03:04:05.000Z", 0, 1, 1); + user.run("u-disabled", "d@example.com", "Dee", "2025-02-01T00:00:00.000Z", -1, 0, 0); + user.run("u-suspended", "s@example.com", "Sue", "2025-03-01T00:00:00.000Z", NOW_S + 3600, 0, 1); + user.run("u-expired", "e@example.com", "Ed", "2025-04-01T00:00:00.000Z", NOW_S - 3600, 0, 1); + db.prepare( + "INSERT INTO user_billing (user_id, stripe_customer_id, stripe_subscription_id, personal_plan, personal_plan_status, personal_plan_started_at) VALUES (?, ?, ?, 'ink', 'active', ?)", + ).run("u-active", "cus_1", "sub_1", NOW - 1000); + db.prepare( + "INSERT INTO user_preferences (user_id, reading_font, badges, bio, handle, handle_locked, theme_mode) VALUES (?, 'serif', 5, ?, 'ann', 1, 'light')", + ).run("u-active", "it's me"); + db.prepare( + "INSERT INTO user_deletions (user_id, id, requested_by, requested_by_email, execute_after, confirm_site_ids, previous_moderation) VALUES ('u-disabled', 'del-1', 'u-active', 'a@example.com', ?, '[\"p1\"]', 0)", + ).run(NOW_S + 86400); + db.prepare( + "INSERT INTO user_moderation_events (id, user_id, action, moderation_value) VALUES ('m1', 'u-disabled', 'disable', -1)", + ).run(); + db.prepare( + "INSERT INTO admin_audit_log (id, actor_user_id, actor_email, action, target_type, target_id) VALUES ('a1', 'u-gone', 'gone@example.com', 'grant_ink', 'user', 'u-active')", + ).run(); + db.prepare("INSERT INTO webhook_events (event_id, type, processed_at) VALUES ('evt_1', 'invoice.paid', ?)").run(NOW); + return db; +} + +function mainDb(): DatabaseSync { + const db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON;"); + for (const f of readdirSync(MAIN_MIGRATIONS).filter(f => f.endsWith(".sql")).sort()) { + db.exec(readFileSync(`${MAIN_MIGRATIONS}/${f}`, "utf8")); + } + return db; +} + +describe("auth-import", () => { + it("copies the users mirror with standing derived from moderation", () => { + const { statements, counts } = buildImportStatements(authDb(), NOW); + const main = mainDb(); + for (const s of statements) main.exec(s); + + expect(counts.users).toBe(4); + const rows = main.prepare("SELECT id, email, name, is_admin, email_verified, status, suspended_until, first_seen_at, synced_at FROM users ORDER BY id").all(); + expect(rows).toEqual([ + { id: "u-active", email: "a@example.com", name: "Ann O'Neil", is_admin: 1, email_verified: 1, status: "active", suspended_until: null, first_seen_at: Date.parse("2025-01-02T03:04:05.000Z"), synced_at: NOW }, + { id: "u-disabled", email: "d@example.com", name: "Dee", is_admin: 0, email_verified: 0, status: "disabled", suspended_until: null, first_seen_at: Date.parse("2025-02-01T00:00:00.000Z"), synced_at: NOW }, + { id: "u-expired", email: "e@example.com", name: "Ed", is_admin: 0, email_verified: 1, status: "active", suspended_until: null, first_seen_at: Date.parse("2025-04-01T00:00:00.000Z"), synced_at: NOW }, + { id: "u-suspended", email: "s@example.com", name: "Sue", is_admin: 0, email_verified: 1, status: "suspended", suspended_until: NOW_S + 3600, first_seen_at: Date.parse("2025-03-01T00:00:00.000Z"), synced_at: NOW }, + ]); + }); + + it("copies billing, preferences, deletions, history, audit and webhook markers", () => { + const { statements, counts } = buildImportStatements(authDb(), NOW); + const main = mainDb(); + for (const s of statements) main.exec(s); + + expect(counts).toMatchObject({ user_billing: 1, user_preferences: 1, user_deletions: 1, user_moderation_events: 1, admin_audit_log: 1, webhook_events: 1 }); + expect(main.prepare("SELECT stripe_customer_id, personal_plan FROM user_billing WHERE user_id = 'u-active'").get()) + .toEqual({ stripe_customer_id: "cus_1", personal_plan: "ink" }); + expect(main.prepare("SELECT reading_font, badges, bio, handle, handle_locked, theme_mode FROM user_preferences WHERE user_id = 'u-active'").get()) + .toEqual({ reading_font: "serif", badges: 5, bio: "it's me", handle: "ann", handle_locked: 1, theme_mode: "light" }); + expect(main.prepare("SELECT id, confirm_site_ids, completed_at FROM user_deletions WHERE user_id = 'u-disabled'").get()) + .toEqual({ id: "del-1", confirm_site_ids: "[\"p1\"]", completed_at: null }); + // Audit rows keep actors that no longer exist (no FK). + expect(main.prepare("SELECT actor_email FROM admin_audit_log WHERE id = 'a1'").get()).toEqual({ actor_email: "gone@example.com" }); + expect(main.prepare("SELECT type FROM webhook_events WHERE event_id = 'evt_1'").get()).toEqual({ type: "invoice.paid" }); + }); + + it("is safe to re-run and never overwrites rows Annex wrote since", () => { + const { statements } = buildImportStatements(authDb(), NOW); + const main = mainDb(); + for (const s of statements) main.exec(s); + main.prepare("UPDATE user_preferences SET reading_font = 'mono' WHERE user_id = 'u-active'").run(); + for (const s of statements) main.exec(s); + expect(main.prepare("SELECT reading_font FROM user_preferences WHERE user_id = 'u-active'").get()).toEqual({ reading_font: "mono" }); + expect(main.prepare("SELECT COUNT(*) AS n FROM users").get()).toEqual({ n: 4 }); + }); + + it("quotes values safely", () => { + expect(sqlValue(null)).toBe("NULL"); + expect(sqlValue(42)).toBe("42"); + expect(sqlValue("a'b")).toBe("'a''b'"); + expect(() => sqlValue(Number.NaN)).toThrow(); + expect(() => sqlValue({})).toThrow(); + }); + + it("maps moderation values to standing", () => { + expect(standingFromModeration(0, NOW)).toEqual({ status: "active", suspendedUntil: null }); + expect(standingFromModeration(-1, NOW)).toEqual({ status: "disabled", suspendedUntil: null }); + expect(standingFromModeration(NOW_S + 1, NOW)).toEqual({ status: "suspended", suspendedUntil: NOW_S + 1 }); + expect(standingFromModeration(NOW_S - 1, NOW)).toEqual({ status: "active", suspendedUntil: null }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59a9d5b..2b64016 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -159,6 +159,9 @@ importers: lib0: specifier: ^0.2.0 version: 0.2.117 + oauth4webapi: + specifier: 3.8.8 + version: 3.8.8 y-protocols: specifier: ^1.0.6 version: 1.0.7(yjs@13.6.30) @@ -5152,6 +5155,9 @@ packages: nwsapi@2.2.23: resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==} + oauth4webapi@3.8.8: + resolution: {integrity: sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==} + object-assign@4.1.1: resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} engines: {node: '>=0.10.0'} @@ -11561,6 +11567,8 @@ snapshots: nwsapi@2.2.23: {} + oauth4webapi@3.8.8: {} + object-assign@4.1.1: {} object-inspect@1.13.4: {} diff --git a/scripts/fixtures/cubedocs-auth-schema.sql b/scripts/fixtures/cubedocs-auth-schema.sql new file mode 100644 index 0000000..5d7f0ea --- /dev/null +++ b/scripts/fixtures/cubedocs-auth-schema.sql @@ -0,0 +1,182 @@ +-- Final schema of the retired cubedocs-auth database (packages/auth/migrations +-- 0001-0036, the last before the identity split). Fixture for +-- scripts/lib/auth-import.test.ts; regenerate only if that history changes. +CREATE TABLE admin_audit_log ( + id TEXT PRIMARY KEY, + actor_user_id TEXT NOT NULL, + actor_email TEXT NOT NULL, + action TEXT NOT NULL, + target_type TEXT NOT NULL, + target_id TEXT, + detail TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX admin_audit_log_created_at ON admin_audit_log(created_at DESC); +CREATE INDEX admin_audit_log_actor ON admin_audit_log(actor_user_id, created_at DESC); +CREATE INDEX admin_audit_log_target ON admin_audit_log(target_type, target_id, created_at DESC); +CREATE INDEX idx_admin_audit_log_action_created + ON admin_audit_log(action, created_at DESC, id DESC); +CREATE TABLE admin_handoffs ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + return_to TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER +); +CREATE INDEX idx_admin_handoffs_user_id ON admin_handoffs(user_id); +CREATE INDEX idx_admin_handoffs_expires_at ON admin_handoffs(expires_at); +CREATE TABLE backup_codes ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + code_hash TEXT NOT NULL, + used_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX backup_codes_user_id ON backup_codes(user_id); +CREATE TABLE email_verification_tokens ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER +, email TEXT); +CREATE INDEX idx_email_verification_tokens_user_id ON email_verification_tokens (user_id); +CREATE INDEX idx_email_verification_tokens_expires ON email_verification_tokens(expires_at); +CREATE TABLE oauth_clients ( + client_id TEXT PRIMARY KEY, + client_name TEXT NOT NULL, + -- SHA-256 (base64url) of the client secret. NULL => public client (PKCE only). + client_secret_hash TEXT, + -- JSON array of exact allowed redirect URIs. + redirect_uris TEXT NOT NULL, + -- Space-separated scopes this client may request (subset of: openid profile email). + allowed_scopes TEXT NOT NULL DEFAULT 'openid profile email', + -- 1 => first-party: auto-approve and skip the consent screen. 0 => show consent. + trusted INTEGER NOT NULL DEFAULT 0, + -- 1 => disabled (refuses new authorizations) without deleting the row/history. + disabled INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); +CREATE TABLE oauth_codes ( + code TEXT PRIMARY KEY, + client_id TEXT NOT NULL, + user_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + scope TEXT NOT NULL, + -- PKCE S256 challenge: base64url(SHA-256(code_verifier)). Always required. + code_challenge TEXT NOT NULL, + -- OIDC nonce, echoed into the id_token when the client supplied one. + nonce TEXT, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER, + FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE +); +CREATE INDEX idx_oauth_codes_expires_at ON oauth_codes(expires_at); +CREATE INDEX idx_oauth_codes_client_id ON oauth_codes(client_id); +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_used_at INTEGER NOT NULL, + device_kind TEXT, + client_label TEXT, + ip TEXT, + revoked_at INTEGER +); +CREATE INDEX idx_sessions_user_id ON sessions(user_id); +CREATE INDEX idx_sessions_expires_at ON sessions(expires_at); +CREATE TABLE user_billing ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + stripe_customer_id TEXT, + stripe_subscription_id TEXT, + personal_period_end INTEGER, + personal_plan TEXT, + personal_plan_status TEXT, + personal_plan_started_at INTEGER, + personal_plan_cancel_at INTEGER, + granted_plan TEXT, + granted_plan_expires_at INTEGER, + granted_plan_started_at INTEGER, + granted_plan_reason TEXT +); +CREATE INDEX idx_user_billing_subscription ON user_billing(stripe_subscription_id); +CREATE TABLE user_deletions ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + id TEXT NOT NULL, + requested_by TEXT NOT NULL, + requested_by_email TEXT NOT NULL, + requested_at TEXT NOT NULL DEFAULT (datetime('now')), + execute_after INTEGER NOT NULL, + confirm_site_ids TEXT NOT NULL DEFAULT '[]', + confirm_org_ids TEXT NOT NULL DEFAULT '[]', + previous_moderation INTEGER NOT NULL DEFAULT 0, + lease_until INTEGER, + started_at INTEGER, + last_error TEXT, + last_attempt_at TEXT +); +CREATE INDEX idx_user_deletions_execute_after ON user_deletions(execute_after); +CREATE TABLE user_moderation_events ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + action TEXT NOT NULL, + moderation_value INTEGER NOT NULL, + reason TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + actor_user_id TEXT, + actor_email TEXT +); +CREATE INDEX user_moderation_events_user_id_created_at + ON user_moderation_events(user_id, created_at DESC); +CREATE TABLE user_preferences ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + reading_font TEXT, + editing_font TEXT, + ui_font TEXT, + personal_plan_style TEXT, + personal_presence_color TEXT, + personal_crit_sparkles INTEGER, + timezone TEXT, + bio TEXT, + badges INTEGER NOT NULL DEFAULT 0 +, theme_mode TEXT, theme_custom_color TEXT, handle TEXT, handle_locked INTEGER NOT NULL DEFAULT 0); +CREATE UNIQUE INDEX idx_user_preferences_handle ON user_preferences(handle) WHERE handle IS NOT NULL; +CREATE TABLE users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TEXT NOT NULL +, moderation INTEGER NOT NULL DEFAULT 0, totp_secret TEXT, force_password_change INTEGER NOT NULL DEFAULT 0, is_admin INTEGER NOT NULL DEFAULT 0, email_verified INTEGER NOT NULL DEFAULT 0, email_verified_at TEXT, change_token_id TEXT, totp_last_used_step INTEGER); +CREATE INDEX users_created_at ON users(created_at DESC); +CREATE INDEX idx_users_disabled_created + ON users(created_at DESC, id DESC) WHERE moderation = -1; +CREATE INDEX idx_users_email_lower ON users(lower(email)); +CREATE TABLE webauthn_challenges ( + id TEXT PRIMARY KEY, -- random UUID, used as lookup key + user_id TEXT NOT NULL, + challenge TEXT NOT NULL, -- base64url random bytes + type TEXT NOT NULL, -- 'registration' | 'authentication' + created_at INTEGER NOT NULL -- Unix ms, enforce 5-min TTL at verification +); +CREATE INDEX idx_webauthn_challenges_created_at + ON webauthn_challenges(created_at); +CREATE TABLE webauthn_credentials ( + id TEXT PRIMARY KEY, -- base64url credential ID + user_id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT 'Security Key', + public_key TEXT NOT NULL, -- base64url COSE public key + counter INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, transports TEXT, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); +CREATE INDEX idx_webauthn_credentials_user ON webauthn_credentials(user_id); +CREATE TABLE webhook_events ( + event_id TEXT PRIMARY KEY, + type TEXT NOT NULL, + processed_at INTEGER NOT NULL +); +CREATE INDEX idx_webhook_events_processed ON webhook_events(processed_at); diff --git a/scripts/import-auth-data.mjs b/scripts/import-auth-data.mjs new file mode 100644 index 0000000..a48973c --- /dev/null +++ b/scripts/import-auth-data.mjs @@ -0,0 +1,58 @@ +#!/usr/bin/env node +// One-time copy of Annex-owned data from cubedocs-auth into cubedocs-main. +// See scripts/lib/auth-import.mjs for what is copied and why. +// +// Usage: +// node scripts/import-auth-data.mjs [--out ] +// +// Remote cutover (the user runs these; nothing here touches a database): +// npx wrangler d1 export cubedocs-auth --remote --output migration-data/cubedocs-auth.sql +// node scripts/import-auth-data.mjs migration-data/cubedocs-auth.sql --out migration-data/annex-import.sql +// npx wrangler d1 execute cubedocs-main --remote --file migration-data/annex-import.sql +// +// Local dev: point it at the auth DB's sqlite file under +// .wrangler/state/v3/d1/miniflare-D1DatabaseObject/ (or a local export), then +// apply the output with `node scripts/d1-local.mjs main --file `. +// +// The output only INSERTs (OR IGNORE), so it is safe to re-run, but a re-run +// never refreshes rows that already exist. migration-data/ holds personal +// data: delete it after the cutover. + +import { DatabaseSync } from "node:sqlite"; +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { buildImportStatements } from "./lib/auth-import.mjs"; + +const args = process.argv.slice(2); +const outIdx = args.indexOf("--out"); +const outFile = outIdx >= 0 ? args[outIdx + 1] : "migration-data/annex-import.sql"; +const input = args.find((a, i) => !a.startsWith("--") && i !== outIdx + 1); +if (!input) { + console.error("Usage: node scripts/import-auth-data.mjs [--out ]"); + process.exit(1); +} + +let db; +if (/\.sql$/i.test(input)) { + db = new DatabaseSync(":memory:"); + db.exec(readFileSync(input, "utf8")); +} else { + db = new DatabaseSync(resolve(input), { readOnly: true }); +} + +const { statements, counts } = buildImportStatements(db); +db.close(); + +mkdirSync(dirname(resolve(outFile)), { recursive: true }); +writeFileSync( + outFile, + [ + "-- Generated by scripts/import-auth-data.mjs. Apply to cubedocs-main AFTER", + "-- migration 0065_add_identity_mirror.sql. Contains personal data.", + ...statements, + "", + ].join("\n"), +); + +console.log(`Wrote ${statements.length} statements to ${outFile}`); +for (const [table, n] of Object.entries(counts)) console.log(` ${table.padEnd(24)} ${n}`); diff --git a/scripts/lib/auth-import.mjs b/scripts/lib/auth-import.mjs new file mode 100644 index 0000000..822eac5 --- /dev/null +++ b/scripts/lib/auth-import.mjs @@ -0,0 +1,134 @@ +// One-time copy of Annex-owned data from the retired cubedocs-auth database +// into cubedocs-main (api migration 0065_add_identity_mirror.sql). +// +// Identity itself (password hashes, TOTP, passkeys, OAuth clients) is NOT +// copied here: that went to the identity service's own database. What comes +// across is what Annex keeps: the users mirror (id/email/name/admin/standing), +// billing, preferences, Stripe webhook markers, scheduled deletions, +// moderation history and the admin audit log. +// +// Every statement is INSERT OR IGNORE, so a second run never overwrites rows +// Annex has written since. Run it once, at cutover, before Annex serves +// traffic from the new code (see memories/Identity-Client.md). + +/** @param {unknown} v */ +export function sqlValue(v) { + if (v === null || v === undefined) return "NULL"; + if (typeof v === "number" || typeof v === "bigint") { + if (typeof v === "number" && !Number.isFinite(v)) throw new Error(`non-finite number: ${v}`); + return String(v); + } + if (typeof v === "boolean") return v ? "1" : "0"; + if (typeof v === "string") return `'${v.replace(/'/g, "''")}'`; + throw new Error(`unsupported SQL value: ${typeof v}`); +} + +/** + * @param {string} table + * @param {string[]} cols + * @param {Array>} rows + */ +function inserts(table, cols, rows) { + return rows.map( + (r) => `INSERT OR IGNORE INTO ${table} (${cols.join(", ")}) VALUES (${cols.map((c) => sqlValue(r[c])).join(", ")});`, + ); +} + +// users.moderation on cubedocs-auth: 0 = active, -1 = disabled, >0 = suspended +// until that unix-seconds instant (an expired suspension reads as active). +export function standingFromModeration(moderation, nowMs) { + if (moderation === -1) return { status: "disabled", suspendedUntil: null }; + if (moderation > 0 && Math.floor(nowMs / 1000) < moderation) return { status: "suspended", suspendedUntil: moderation }; + return { status: "active", suspendedUntil: null }; +} + +function tableExists(db, name) { + return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name); +} + +/** + * Builds the import statements from an opened copy of cubedocs-auth. + * + * @param {{ prepare(sql: string): { all(...a: unknown[]): any[]; get(...a: unknown[]): any } }} db + * node:sqlite DatabaseSync (or anything with the same prepare/all/get shape) + * @param {number} nowMs + * @returns {{ statements: string[]; counts: Record }} + */ +export function buildImportStatements(db, nowMs = Date.now()) { + const statements = []; + const counts = {}; + + const users = db + .prepare("SELECT id, email, name, email_verified, is_admin, moderation, created_at FROM users ORDER BY created_at, id") + .all() + .map((u) => { + const standing = standingFromModeration(Number(u.moderation ?? 0), nowMs); + const createdMs = Date.parse(u.created_at); + return { + id: u.id, + email: u.email, + name: u.name, + email_verified: u.email_verified ? 1 : 0, + is_admin: u.is_admin ? 1 : 0, + status: standing.status, + suspended_until: standing.suspendedUntil, + created_at: u.created_at, + first_seen_at: Number.isFinite(createdMs) ? createdMs : nowMs, + last_login_at: null, + synced_at: nowMs, + }; + }); + statements.push( + ...inserts( + "users", + ["id", "email", "name", "email_verified", "is_admin", "status", "suspended_until", "created_at", "first_seen_at", "last_login_at", "synced_at"], + users, + ), + ); + counts.users = users.length; + + // Satellites, copied column-for-column. Parents first (FKs are enforced). + const copies = [ + ["user_billing", [ + "user_id", "stripe_customer_id", "stripe_subscription_id", "personal_period_end", + "personal_plan", "personal_plan_status", "personal_plan_started_at", "personal_plan_cancel_at", + "granted_plan", "granted_plan_expires_at", "granted_plan_started_at", "granted_plan_reason", + ]], + ["user_preferences", [ + "user_id", "reading_font", "editing_font", "ui_font", + "personal_plan_style", "personal_presence_color", "personal_crit_sparkles", + "timezone", "bio", "badges", "theme_mode", "theme_custom_color", "handle", "handle_locked", + ]], + // previous_moderation is dropped: cancelling a deletion no longer touches + // account standing (that lives on the identity service now). + ["user_deletions", [ + "user_id", "id", "requested_by", "requested_by_email", "requested_at", "execute_after", + "confirm_site_ids", "confirm_org_ids", "lease_until", "started_at", "last_error", "last_attempt_at", + ]], + ["user_moderation_events", [ + "id", "user_id", "action", "moderation_value", "reason", "created_at", "actor_user_id", "actor_email", + ]], + ["admin_audit_log", [ + "id", "actor_user_id", "actor_email", "action", "target_type", "target_id", "detail", "created_at", + ]], + ["webhook_events", ["event_id", "type", "processed_at"]], + ]; + + const userIds = new Set(users.map((u) => u.id)); + for (const [table, cols] of copies) { + if (!tableExists(db, table)) { + counts[table] = 0; + continue; + } + let rows = db.prepare(`SELECT ${cols.join(", ")} FROM ${table}`).all(); + // Belt and braces: a satellite row for a user that isn't being copied + // would fail the FK and abort the whole import. + if (cols[0] === "user_id" || table === "user_moderation_events") { + rows = rows.filter((r) => userIds.has(r.user_id)); + } + statements.push(...inserts(table, cols, rows)); + counts[table] = rows.length; + } + + return { statements, counts }; +} From 50847596870d9b3209cb96c97f533ca83f435552 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:13:16 +0000 Subject: [PATCH 2/4] feat(api): sign in with auth.cubityfir.st as an OIDC client Annex verifies its own sessions against cubedocs-main instead of the auth DB. New account/ module (shared with the admin worker later): HS256 session JWTs, sessions with a kind (app/admin) and a single-use handoff code, account standing from the IdentityService RPC cached ~60s with the users mirror as fallback, and an oauth4webapi-based OIDC client (PKCE S256, state, nonce, id_token claims and JWKS signature checks). Routes: GET /auth/login, GET /auth/callback, POST /auth/exchange, POST /auth/logout, and a localhost-only POST /dev/quick-login that mints mirror-only dev users. Issuer, client id/secret and redirect URIs come from OIDC_* vars and APP_ORIGIN. --- packages/api/cloudflare.config.ts | 20 +- packages/api/src/account/identity.ts | 233 +++++++++++++++++ packages/api/src/account/jwt.test.ts | 105 ++++++++ packages/api/src/account/jwt.ts | 108 ++++++++ packages/api/src/account/oidc.ts | 263 +++++++++++++++++++ packages/api/src/account/plan.test.ts | 205 +++++++++++++++ packages/api/src/account/plan.ts | 115 +++++++++ packages/api/src/account/session.ts | 309 ++++++++++++++++++++++ packages/api/src/auth.ts | 61 +++-- packages/api/src/index.ts | 38 ++- packages/api/src/lib.ts | 3 + packages/api/src/me.test.ts | 6 +- packages/api/src/routes/auth.test.ts | 354 ++++++++++++++++++++++++++ packages/api/src/routes/auth.ts | 246 ++++++++++++++++++ packages/api/src/routes/members.ts | 2 +- packages/api/src/test/fakeIdp.ts | 157 ++++++++++++ packages/api/src/test/session.ts | 23 ++ 17 files changed, 2211 insertions(+), 37 deletions(-) create mode 100644 packages/api/src/account/identity.ts create mode 100644 packages/api/src/account/jwt.test.ts create mode 100644 packages/api/src/account/jwt.ts create mode 100644 packages/api/src/account/oidc.ts create mode 100644 packages/api/src/account/plan.test.ts create mode 100644 packages/api/src/account/plan.ts create mode 100644 packages/api/src/account/session.ts create mode 100644 packages/api/src/routes/auth.test.ts create mode 100644 packages/api/src/routes/auth.ts create mode 100644 packages/api/src/test/fakeIdp.ts create mode 100644 packages/api/src/test/session.ts diff --git a/packages/api/cloudflare.config.ts b/packages/api/cloudflare.config.ts index b188b08..eba6f56 100644 --- a/packages/api/cloudflare.config.ts +++ b/packages/api/cloudflare.config.ts @@ -50,6 +50,23 @@ export default defineConfig({ // route. R2_BUCKET_NAME: bindings.text("cubedocs-assets"), R2_ACCOUNT_ID: bindings.text("d843ae90cab33e54f4d284bc65d2fd6a"), + // Sign in with auth.cubityfir.st (src/routes/auth.ts). Annex is a + // first-party OIDC client with scopes `openid profile email roles`, + // redirect URI APP_ORIGIN/api/auth/callback and post-logout redirect + // URI APP_ORIGIN/ (override with OIDC_REDIRECT_URI / + // OIDC_POST_LOGOUT_REDIRECT_URI). OIDC_CLIENT_ID must be the id the + // client was registered with at auth.cubityfir.st/admin/clients; + // OIDC_CLIENT_SECRET is a secret. Local dev overrides all of these in + // .dev.vars (see .dev.vars.example). + OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), + OIDC_CLIENT_ID: bindings.text("annex-docs"), + APP_ORIGIN: bindings.text("https://docs.cubityfir.st"), + // Identity service RPC (cubityfirst-auth's IdentityService entrypoint): + // account standing, invite-by-email lookups and the deletion sync. + IDENTITY: bindings.worker({ + worker: "cubityfirst-auth", + exportName: "IdentityService", + }), DB: bindings.d1({ name: "cubedocs-main", id: "267490be-7141-4d00-ab23-152742f2f6ef", @@ -119,7 +136,8 @@ export default defineConfig({ }), // Secrets (set via `npx wrangler secret put --name annex-api`; // existing secrets are kept across `cf deploy`): - // JWT_SECRET (same value as auth worker - used for local JWT verification) + // JWT_SECRET (signs Annex's own session JWTs; Annex-only) + // OIDC_CLIENT_SECRET (the annex-docs client's secret from auth.cubityfir.st) // OPENAI_API_KEY (OpenAI API key for AI summarisation feature) // CF_API_TOKEN (Cloudflare token scoped to the zone with "SSL and // Certificates: Edit" - used to create/poll custom hostnames) diff --git a/packages/api/src/account/identity.ts b/packages/api/src/account/identity.ts new file mode 100644 index 0000000..6bbb4a8 --- /dev/null +++ b/packages/api/src/account/identity.ts @@ -0,0 +1,233 @@ +// The identity service (auth.cubityfir.st, worker `cubityfirst-auth`) as seen +// from Annex: the IdentityService RPC binding, the local `users` mirror, and +// account standing. +// +// Bound as { binding: IDENTITY, service: cubityfirst-auth, entrypoint: +// IdentityService } (see cloudflare.config.ts). RPC entrypoints aren't +// reachable over HTTP, so the binding is the access control. + +export interface IdentityUser { + id: string; + email: string; + name: string; + emailVerified: boolean; + isAdmin: boolean; + status: "active" | "disabled" | "suspended"; + // Unix seconds, set when status is "suspended". + suspendedUntil: number | null; + createdAt: string; +} + +export interface IdentityService { + getUser(id: string): Promise; + getUsers(ids: string[]): Promise; + findUserByEmail(email: string): Promise; + listDeletedUsers(sinceMs: number, limit?: number): Promise>; +} + +// What every consumer of this module needs from its worker's Env. +export interface IdentityEnv { + DB: D1Database; + IDENTITY?: IdentityService; + // Local-dev quick login: dev-* users exist only in the mirror (see + // routes/auth.ts handleDevQuickLogin), so standing checks skip the RPC. + DEV_QUICK_LOGIN?: string; + APP_ORIGIN?: string; +} + +export interface MirrorUser { + id: string; + email: string; + name: string; + email_verified: number; + is_admin: number; + status: string; + suspended_until: number | null; + created_at: string; +} + +export type Standing = + | { ok: true; isAdmin: boolean } + | { ok: false; reason: "disabled" } + | { ok: false; reason: "suspended"; until: number } + | { ok: false; reason: "deleted" }; + +export const DEV_USER_PREFIX = "dev-"; + +export function isLocalDeploy(env: { APP_ORIGIN?: string }): boolean { + return /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(env.APP_ORIGIN ?? ""); +} + +export function isLocalDevUser(env: IdentityEnv, userId: string): boolean { + return env.DEV_QUICK_LOGIN === "true" && isLocalDeploy(env) && userId.startsWith(DEV_USER_PREFIX); +} + +// --------------------------------------------------------------------------- +// Standing cache +// --------------------------------------------------------------------------- +// +// Account standing is owned by the identity service. Asking it on every +// request would add an RPC per API call, so each isolate remembers the answer +// for STANDING_TTL_MS. A user disabled on auth.cubityfir.st is therefore +// locked out of Annex within about a minute, not when their Annex session +// expires. + +export const STANDING_TTL_MS = 60_000; +const CACHE_MAX = 5_000; + +interface CacheEntry { user: IdentityUser | null; at: number } +const cache = new Map(); + +export function clearIdentityCache(): void { + cache.clear(); +} + +function remember(id: string, user: IdentityUser | null, now: number): void { + if (cache.size >= CACHE_MAX) { + // Map iterates in insertion order: drop the oldest tenth. + let n = Math.ceil(CACHE_MAX / 10); + for (const k of cache.keys()) { + cache.delete(k); + if (--n <= 0) break; + } + } + cache.delete(id); + cache.set(id, { user, at: now }); +} + +export function standingFromIdentity(user: IdentityUser | null, nowMs: number): Standing { + if (!user) return { ok: false, reason: "deleted" }; + if (user.status === "disabled") return { ok: false, reason: "disabled" }; + if (user.status === "suspended" && user.suspendedUntil && Math.floor(nowMs / 1000) < user.suspendedUntil) { + return { ok: false, reason: "suspended", until: user.suspendedUntil }; + } + return { ok: true, isAdmin: user.isAdmin }; +} + +export function standingFromMirror(row: Pick, nowMs: number): Standing { + if (row.status === "disabled") return { ok: false, reason: "disabled" }; + if (row.status === "suspended" && row.suspended_until && Math.floor(nowMs / 1000) < row.suspended_until) { + return { ok: false, reason: "suspended", until: row.suspended_until }; + } + return { ok: true, isAdmin: Boolean(row.is_admin) }; +} + +// Live standing for a user Annex already has a mirror row for. Uses the +// isolate cache, then the IDENTITY RPC; when the identity service can't be +// reached it falls back to the mirror's last known standing rather than +// locking everyone out of Annex. A changed answer is written back to the +// mirror (and to the member-row name/email snapshots). +export async function accountStanding( + env: IdentityEnv, + mirror: MirrorUser, + nowMs: number = Date.now(), + ctx?: { waitUntil(p: Promise): void }, +): Promise { + if (isLocalDevUser(env, mirror.id)) return standingFromMirror(mirror, nowMs); + + const hit = cache.get(mirror.id); + if (hit && nowMs - hit.at < STANDING_TTL_MS) return standingFromIdentity(hit.user, nowMs); + + if (!env.IDENTITY) return standingFromMirror(mirror, nowMs); + + let user: IdentityUser | null; + try { + user = await env.IDENTITY.getUser(mirror.id); + } catch (err) { + console.error("[identity] getUser failed; using mirror standing", { userId: mirror.id, err: String(err) }); + return standingFromMirror(mirror, nowMs); + } + remember(mirror.id, user, nowMs); + if (user && mirrorDiffers(mirror, user)) { + const write = refreshMirror(env.DB, user, nowMs).catch(err => + console.error("[identity] mirror refresh failed", { userId: user.id, err: String(err) }), + ); + if (ctx) ctx.waitUntil(write); + else await write; + } + return standingFromIdentity(user, nowMs); +} + +function mirrorDiffers(m: MirrorUser, u: IdentityUser): boolean { + return ( + m.email !== u.email || + m.name !== u.name || + Boolean(m.email_verified) !== u.emailVerified || + Boolean(m.is_admin) !== u.isAdmin || + m.status !== u.status || + (m.suspended_until ?? null) !== (u.suspendedUntil ?? null) + ); +} + +// Writes the identity service's view of a user into the mirror. Name and +// email are also denormalized onto site/org member rows; keep those in step +// (the <> guards make the statements no-ops when nothing changed). +export function mirrorUpsertStatements(db: D1Database, user: IdentityUser, nowMs: number, opts: { login?: boolean } = {}): D1PreparedStatement[] { + return [ + db.prepare( + `INSERT INTO users (id, email, name, email_verified, is_admin, status, suspended_until, created_at, first_seen_at, last_login_at, synced_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + email = excluded.email, + name = excluded.name, + email_verified = excluded.email_verified, + is_admin = excluded.is_admin, + status = excluded.status, + suspended_until = excluded.suspended_until, + created_at = excluded.created_at, + last_login_at = COALESCE(excluded.last_login_at, users.last_login_at), + synced_at = excluded.synced_at`, + ).bind( + user.id, + user.email, + user.name, + user.emailVerified ? 1 : 0, + user.isAdmin ? 1 : 0, + user.status, + user.suspendedUntil ?? null, + user.createdAt, + nowMs, + opts.login ? nowMs : null, + nowMs, + ), + db.prepare("UPDATE project_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?)") + .bind(user.name, user.email, user.id, user.name, user.email), + db.prepare("UPDATE organization_members SET name = ?, email = ? WHERE user_id = ? AND (name <> ? OR email <> ?)") + .bind(user.name, user.email, user.id, user.name, user.email), + ]; +} + +export async function refreshMirror(db: D1Database, user: IdentityUser, nowMs: number, opts: { login?: boolean } = {}): Promise { + await db.batch(mirrorUpsertStatements(db, user, nowMs, opts)); +} + +// Finds a person by email for "invite by email". Annex's mirror only knows +// people who have used Annex, so ask the identity service first and mirror +// whoever it returns (so member rows and joins have a users row to point at). +// Without the binding (unit tests, or the identity service unreachable) the +// mirror is the fallback. +export async function findUserByEmail(env: IdentityEnv, email: string, nowMs: number = Date.now()): Promise<{ id: string; email: string; name: string } | null> { + const normalized = email.trim().toLowerCase(); + if (!normalized) return null; + if (env.IDENTITY) { + let user: IdentityUser | null = null; + let reached = true; + try { + user = await env.IDENTITY.findUserByEmail(normalized); + } catch (err) { + reached = false; + console.error("[identity] findUserByEmail failed; using mirror", { err: String(err) }); + } + if (reached) { + if (!user) return null; + // Never resurrect an account Annex has already processed as deleted. + const gone = await env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(user.id).first(); + if (gone) return null; + await refreshMirror(env.DB, user, nowMs); + return { id: user.id, email: user.email, name: user.name }; + } + } + const row = await env.DB.prepare("SELECT id, email, name FROM users WHERE lower(email) = ? LIMIT 1") + .bind(normalized).first<{ id: string; email: string; name: string }>(); + return row ?? null; +} diff --git a/packages/api/src/account/jwt.test.ts b/packages/api/src/account/jwt.test.ts new file mode 100644 index 0000000..dd2237a --- /dev/null +++ b/packages/api/src/account/jwt.test.ts @@ -0,0 +1,105 @@ +import { describe, it, expect } from "vitest"; +import { signJwt, verifyJwt } from "./jwt"; +import type { SessionToken as Session } from "./jwt"; + +const SECRET = "test-jwt-secret"; +const PAYLOAD: Session = { + userId: "user-abc", + email: "test@example.com", + expiresAt: Date.now() + 60_000, +}; + +describe("signJwt / verifyJwt", () => { + it("round-trips: verify returns the original payload", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const session = await verifyJwt(token, SECRET); + expect(session).not.toBeNull(); + expect(session!.userId).toBe(PAYLOAD.userId); + expect(session!.email).toBe(PAYLOAD.email); + expect(session!.expiresAt).toBe(PAYLOAD.expiresAt); + }); + + it("returns null when verified with the wrong secret", async () => { + const token = await signJwt(PAYLOAD, SECRET); + expect(await verifyJwt(token, "wrong-secret")).toBeNull(); + }); + + it("returns null for a token with only two parts", async () => { + expect(await verifyJwt("header.payload", SECRET)).toBeNull(); + }); + + it("returns null for an empty string", async () => { + expect(await verifyJwt("", SECRET)).toBeNull(); + }); + + it("returns null for a token with a tampered payload", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const [h, , s] = token.split("."); + const tampered = btoa(JSON.stringify({ ...PAYLOAD, isAdmin: true })) + .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + expect(await verifyJwt(`${h}.${tampered}.${s}`, SECRET)).toBeNull(); + }); + + it("returns null for an expired token", async () => { + const expired: Session = { ...PAYLOAD, expiresAt: Date.now() - 1000 }; + const token = await signJwt(expired, SECRET); + expect(await verifyJwt(token, SECRET)).toBeNull(); + }); + + it("preserves optional isAdmin field", async () => { + const admin: Session = { ...PAYLOAD, isAdmin: true }; + const token = await signJwt(admin, SECRET); + const session = await verifyJwt(token, SECRET); + expect(session!.isAdmin).toBe(true); + }); + + it("preserves optional sid field", async () => { + const withSid: Session = { ...PAYLOAD, sid: "session-uuid" }; + const token = await signJwt(withSid, SECRET); + const session = await verifyJwt(token, SECRET); + expect(session!.sid).toBe("session-uuid"); + }); + + it("rejects a token whose header alg is not HS256", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const [, body, sig] = token.split("."); + // Replace the header with one that claims `alg: none` while keeping the + // body and (now-invalid) signature - the alg check must reject before + // the signature is consulted. + const noneHeader = btoa(JSON.stringify({ alg: "none", typ: "JWT" })) + .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + expect(await verifyJwt(`${noneHeader}.${body}.${sig}`, SECRET)).toBeNull(); + }); + + it("rejects a token whose header typ is not JWT", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const [, body, sig] = token.split("."); + const wrongTyp = btoa(JSON.stringify({ alg: "HS256", typ: "JWE" })) + .replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + expect(await verifyJwt(`${wrongTyp}.${body}.${sig}`, SECRET)).toBeNull(); + }); + + it("rejects a token with an unparseable header", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const [, body, sig] = token.split("."); + expect(await verifyJwt(`!!!.${body}.${sig}`, SECRET)).toBeNull(); + }); + + it("returns null (not a throw) for a signature that is not valid base64", async () => { + const token = await signJwt(PAYLOAD, SECRET); + const [h, body] = token.split("."); + await expect(verifyJwt(`${h}.${body}.!!!not-base64!!!`, SECRET)).resolves.toBeNull(); + }); + + it("rejects a correctly-signed token that lacks expiresAt", async () => { + const noExpiry = { userId: "user-abc", email: "test@example.com" } as unknown as Session; + const token = await signJwt(noExpiry, SECRET); + expect(await verifyJwt(token, SECRET)).toBeNull(); + }); + + it("rejects a correctly-signed token whose expiresAt is not a number", async () => { + const badExpiry = { ...PAYLOAD, expiresAt: "9999999999999" } as unknown as Session; + const token = await signJwt(badExpiry, SECRET); + expect(await verifyJwt(token, SECRET)).toBeNull(); + }); +}); diff --git a/packages/api/src/account/jwt.ts b/packages/api/src/account/jwt.ts new file mode 100644 index 0000000..df36640 --- /dev/null +++ b/packages/api/src/account/jwt.ts @@ -0,0 +1,108 @@ +// HS256 session tokens for Annex's own sessions (docs app and admin panel). +// +// Since the identity split this secret is Annex-only: the identity service +// signs its id_tokens with its own RS256 key and never sees JWT_SECRET. The +// token is proof that Annex minted a session; every claim that can change is +// re-read from the database on each request (see account/session.ts). + +export interface SessionToken { + userId: string; + email: string; + expiresAt: number; + isAdmin?: boolean; + // Server-side session row id (sessions.id). Required: a token without one + // is refused by loadCurrentSession. + sid?: string; +} + +const ALG = { name: "HMAC", hash: "SHA-256" }; +const enc = new TextEncoder(); + +function toArrayBuffer(bytes: Uint8Array): ArrayBuffer { + const { buffer, byteOffset, byteLength } = bytes; + if (buffer instanceof ArrayBuffer) return buffer.slice(byteOffset, byteOffset + byteLength); + const copy = new Uint8Array(byteLength); + copy.set(bytes); + return copy.buffer; +} + +function importKey(secret: string): Promise { + return crypto.subtle.importKey("raw", toArrayBuffer(enc.encode(secret)), ALG, false, ["sign", "verify"]); +} + +export function b64url(bytes: ArrayBuffer | Uint8Array): string { + const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); + let s = ""; + for (const b of arr) s += String.fromCharCode(b); + return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} + +export function b64urlDecodeBytes(str: string): Uint8Array { + return Uint8Array.from(atob(str.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0)); +} + +function b64urlDecode(str: string): string { + return new TextDecoder().decode(b64urlDecodeBytes(str)); +} + +function encodeJSON(obj: unknown): string { + return b64url(enc.encode(JSON.stringify(obj))); +} + +export async function hmacSign(data: string, secret: string): Promise { + const key = await importKey(secret); + return b64url(await crypto.subtle.sign(ALG, key, enc.encode(data))); +} + +export async function hmacVerify(data: string, sig: string, secret: string): Promise { + let sigBytes: Uint8Array; + try { + sigBytes = b64urlDecodeBytes(sig); + } catch { + return false; + } + const key = await importKey(secret); + return crypto.subtle.verify(ALG, key, toArrayBuffer(sigBytes), enc.encode(data)); +} + +export async function signJwt(payload: SessionToken, secret: string): Promise { + const header = encodeJSON({ alg: "HS256", typ: "JWT" }); + const body = encodeJSON(payload); + return `${header}.${body}.${await hmacSign(`${header}.${body}`, secret)}`; +} + +export async function verifyJwt(token: string, secret: string): Promise { + const parts = token.split("."); + if (parts.length !== 3) return null; + + // Pin the algorithm: a verifier that accepted several algs would be one + // bug away from `alg: none` / RS-HS confusion. + let header: { alg?: unknown; typ?: unknown }; + try { + header = JSON.parse(b64urlDecode(parts[0])); + } catch { + return null; + } + if (header.alg !== "HS256" || header.typ !== "JWT") return null; + + if (!(await hmacVerify(`${parts[0]}.${parts[1]}`, parts[2], secret))) return null; + + let payload: SessionToken; + try { + payload = JSON.parse(b64urlDecode(parts[1])); + } catch { + return null; + } + if (!payload || typeof payload !== "object" || typeof payload.userId !== "string") return null; + // Fail closed on a missing/malformed expiry: `undefined < n` is false. + if (typeof payload.expiresAt !== "number" || payload.expiresAt < Date.now()) return null; + return payload; +} + +export async function sha256b64url(input: string): Promise { + return b64url(await crypto.subtle.digest("SHA-256", enc.encode(input))); +} + +export function randomToken(bytes = 32): string { + return b64url(crypto.getRandomValues(new Uint8Array(bytes))); +} diff --git a/packages/api/src/account/oidc.ts b/packages/api/src/account/oidc.ts new file mode 100644 index 0000000..596894c --- /dev/null +++ b/packages/api/src/account/oidc.ts @@ -0,0 +1,263 @@ +// Annex as an OpenID Connect relying party of the identity service +// (https://auth.cubityfir.st). Authorization Code + PKCE (S256), state and +// nonce, id_token checked by oauth4webapi (iss, aud, exp, iat, nonce, azp, +// alg pinned to RS256) and its signature verified against the issuer's JWKS. +// +// Shared by the API worker (the docs app) and the admin worker (its own +// client); each passes its own OidcClientConfig. + +import * as oauth from "oauth4webapi"; +import { hmacSign, hmacVerify, b64url, b64urlDecodeBytes } from "./jwt"; + +export interface OidcClientConfig { + issuer: string; + clientId: string; + // Absent for a public client (PKCE only). + clientSecret?: string; + redirectUri: string; + postLogoutRedirectUri: string; + scope: string; + // Test hook: replaces fetch for discovery, token and JWKS requests. + fetchImpl?: typeof fetch; +} + +export interface VerifiedIdentity { + sub: string; + email: string; + emailVerified: boolean; + name: string; + roles: string[]; + idToken: string; +} + +export class OidcError extends Error { + constructor(readonly code: string, message?: string) { + super(message ?? code); + } +} + +// --------------------------------------------------------------------------- +// Discovery + JWKS cache (per isolate) +// --------------------------------------------------------------------------- + +const DISCOVERY_TTL_MS = 60 * 60 * 1000; +const discoveryCache = new Map(); +const jwksCaches = new Map(); + +export function clearOidcCaches(): void { + discoveryCache.clear(); + jwksCaches.clear(); +} + +function httpOptions(cfg: OidcClientConfig): oauth.HttpRequestOptions<"GET" | "POST", unknown> { + const opts: oauth.HttpRequestOptions<"GET" | "POST", unknown> = { signal: () => AbortSignal.timeout(10_000) }; + // Local dev points at `wrangler dev` of the identity worker over http. + if (new URL(cfg.issuer).protocol === "http:") opts[oauth.allowInsecureRequests] = true; + if (cfg.fetchImpl) { + const f = cfg.fetchImpl; + opts[oauth.customFetch] = (url, init) => f(url, init as RequestInit); + } + return opts; +} + +export async function discover(cfg: OidcClientConfig, nowMs: number = Date.now()): Promise { + const hit = discoveryCache.get(cfg.issuer); + if (hit && nowMs - hit.at < DISCOVERY_TTL_MS) return hit.as; + const issuer = new URL(cfg.issuer); + const res = await oauth.discoveryRequest(issuer, { ...httpOptions(cfg), algorithm: "oidc" }); + // Validates that the document's `issuer` is exactly the configured issuer. + const as = await oauth.processDiscoveryResponse(issuer, res); + discoveryCache.set(cfg.issuer, { as, at: nowMs }); + return as; +} + +function client(cfg: OidcClientConfig): oauth.Client { + return { client_id: cfg.clientId, id_token_signed_response_alg: "RS256" }; +} + +function clientAuth(cfg: OidcClientConfig): oauth.ClientAuth { + return cfg.clientSecret ? oauth.ClientSecretBasic(cfg.clientSecret) : oauth.None(); +} + +// --------------------------------------------------------------------------- +// Login state cookie +// --------------------------------------------------------------------------- +// +// state, nonce and the PKCE verifier live in a short-lived HttpOnly cookie, +// HMAC-signed with the worker's JWT_SECRET so it can't be forged or edited. +// SameSite=Lax: the callback is a top-level GET navigation from the identity +// host, which Lax cookies ride along on. + +export const LOGIN_STATE_TTL_MS = 10 * 60 * 1000; + +export interface LoginState { + state: string; + nonce: string; + verifier: string; + returnTo: string; + exp: number; +} + +export async function sealLoginState(s: LoginState, secret: string): Promise { + const body = b64url(new TextEncoder().encode(JSON.stringify(s))); + return `${body}.${await hmacSign(`oidc-state.${body}`, secret)}`; +} + +export async function openLoginState(sealed: string | null, secret: string, nowMs: number = Date.now()): Promise { + if (!sealed) return null; + const dot = sealed.indexOf("."); + if (dot < 1) return null; + const body = sealed.slice(0, dot); + if (!(await hmacVerify(`oidc-state.${body}`, sealed.slice(dot + 1), secret))) return null; + try { + const s = JSON.parse(new TextDecoder().decode(b64urlDecodeBytes(body))) as LoginState; + if (typeof s.exp !== "number" || s.exp <= nowMs) return null; + if (![s.state, s.nonce, s.verifier, s.returnTo].every(v => typeof v === "string" && v.length > 0)) return null; + return s; + } catch { + return null; + } +} + +export function readCookie(request: Request, name: string): string | null { + const header = request.headers.get("Cookie"); + if (!header) return null; + for (const part of header.split(";")) { + const eq = part.indexOf("="); + if (eq < 0) continue; + if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim(); + } + return null; +} + +export function stateCookie(name: string, value: string, opts: { path: string; secure: boolean; maxAgeSec: number }): string { + return [ + `${name}=${value}`, + `Path=${opts.path}`, + `Max-Age=${opts.maxAgeSec}`, + "HttpOnly", + "SameSite=Lax", + ...(opts.secure ? ["Secure"] : []), + ].join("; "); +} + +// Only same-origin app paths: "/x", never "//host", "/\\host" or a scheme. +export function safeReturnTo(raw: string | null | undefined, fallback = "/"): string { + if (typeof raw !== "string" || raw.length === 0 || raw.length > 2048) return fallback; + if (!raw.startsWith("/") || raw.startsWith("//") || raw.includes("\\")) return fallback; + // Reject control characters (CR/LF in particular). + for (let i = 0; i < raw.length; i++) { + const c = raw.charCodeAt(i); + if (c < 0x20 || c === 0x7f) return fallback; + } + return raw; +} + +// --------------------------------------------------------------------------- +// Flow +// --------------------------------------------------------------------------- + +export interface LoginRedirect { + url: string; + state: LoginState; +} + +export async function buildLoginRedirect( + cfg: OidcClientConfig, + opts: { returnTo: string; prompt?: string; nowMs?: number }, +): Promise { + const as = await discover(cfg, opts.nowMs); + if (!as.authorization_endpoint) throw new OidcError("misconfigured", "issuer has no authorization_endpoint"); + const verifier = oauth.generateRandomCodeVerifier(); + const state: LoginState = { + state: oauth.generateRandomState(), + nonce: oauth.generateRandomNonce(), + verifier, + returnTo: opts.returnTo, + exp: (opts.nowMs ?? Date.now()) + LOGIN_STATE_TTL_MS, + }; + const url = new URL(as.authorization_endpoint); + url.searchParams.set("client_id", cfg.clientId); + url.searchParams.set("redirect_uri", cfg.redirectUri); + url.searchParams.set("response_type", "code"); + url.searchParams.set("scope", cfg.scope); + url.searchParams.set("state", state.state); + url.searchParams.set("nonce", state.nonce); + url.searchParams.set("code_challenge", await oauth.calculatePKCECodeChallenge(verifier)); + url.searchParams.set("code_challenge_method", "S256"); + if (opts.prompt) url.searchParams.set("prompt", opts.prompt); + return { url: url.toString(), state }; +} + +function asString(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +// Completes the callback: checks state (and `iss` when the server sends it), +// redeems the code with the PKCE verifier, validates the id_token claims +// including nonce, and verifies its signature against the JWKS. +export async function completeLogin(cfg: OidcClientConfig, callbackUrl: URL, login: LoginState): Promise { + const as = await discover(cfg); + const c = client(cfg); + + let params: URLSearchParams; + try { + params = oauth.validateAuthResponse(as, c, callbackUrl, login.state); + } catch (err) { + if (err instanceof oauth.AuthorizationResponseError) throw new OidcError(err.error, err.error_description ?? undefined); + throw new OidcError("invalid_callback", String(err)); + } + + const opts = httpOptions(cfg); + const res = await oauth.authorizationCodeGrantRequest(as, c, clientAuth(cfg), params, cfg.redirectUri, login.verifier, opts); + let tokens: oauth.TokenEndpointResponse; + try { + tokens = await oauth.processAuthorizationCodeResponse(as, c, res, { expectedNonce: login.nonce, requireIdToken: true }); + } catch (err) { + if (err instanceof oauth.ResponseBodyError) throw new OidcError(err.error, err.error_description ?? undefined); + throw new OidcError("invalid_token_response", String(err)); + } + + let jwks = jwksCaches.get(cfg.issuer); + if (!jwks) { + jwks = {}; + jwksCaches.set(cfg.issuer, jwks); + } + try { + await oauth.validateApplicationLevelSignature(as, res, { ...opts, [oauth.jwksCache]: jwks }); + } catch (err) { + throw new OidcError("invalid_signature", String(err)); + } + + const claims = oauth.getValidatedIdTokenClaims(tokens); + if (!claims || typeof claims.sub !== "string" || !claims.sub) throw new OidcError("invalid_id_token", "missing sub"); + const email = asString(claims.email); + if (!email) throw new OidcError("invalid_id_token", "missing email (request the email scope)"); + const roles = Array.isArray(claims.roles) ? (claims.roles as unknown[]).filter((r): r is string => typeof r === "string") : []; + return { + sub: claims.sub, + email, + emailVerified: claims.email_verified === true, + name: asString(claims.name) || email, + roles, + idToken: tokens.id_token as string, + }; +} + +// RP-initiated logout URL. Falls back to the configured post-logout URI when +// discovery is unavailable, so signing out of Annex never depends on the +// identity service being up. +export async function buildLogoutUrl(cfg: OidcClientConfig, idToken: string | null): Promise { + let endSession: string | undefined; + try { + endSession = (await discover(cfg)).end_session_endpoint; + } catch (err) { + console.error("[oidc] discovery failed during logout", String(err)); + } + if (!endSession) return cfg.postLogoutRedirectUri; + const url = new URL(endSession); + if (idToken) url.searchParams.set("id_token_hint", idToken); + else url.searchParams.set("client_id", cfg.clientId); + url.searchParams.set("post_logout_redirect_uri", cfg.postLogoutRedirectUri); + return url.toString(); +} diff --git a/packages/api/src/account/plan.test.ts b/packages/api/src/account/plan.test.ts new file mode 100644 index 0000000..e1f1584 --- /dev/null +++ b/packages/api/src/account/plan.test.ts @@ -0,0 +1,205 @@ +import { describe, it, expect } from "vitest"; +import { resolvePersonalPlan, type PlanRow } from "./plan"; + +const FREE: PlanRow = { + granted_plan: null, + granted_plan_expires_at: null, + granted_plan_started_at: null, + personal_plan: null, + personal_plan_status: null, + personal_plan_started_at: null, + personal_plan_cancel_at: null, + personal_plan_style: null, + personal_presence_color: null, + personal_crit_sparkles: null, +}; + +const NOW = 1_000_000; + +describe("resolvePersonalPlan", () => { + it("returns free when no plan info is set", () => { + const r = resolvePersonalPlan(FREE, NOW); + expect(r.plan).toBe("free"); + expect(r.via).toBe("free"); + expect(r.since).toBeNull(); + }); + + it("returns ink when paid plan is active", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "active", + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.via).toBe("paid"); + expect(r.since).toBe(500); + expect(r.status).toBe("active"); + }); + + it("keeps perks active during past_due grace period", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "past_due", + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.status).toBe("past_due"); + }); + + it("trialing counts as active", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "trialing", + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("ink"); + }); + + it("returns free when paid plan is canceled", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "canceled", + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("free"); + expect(r.via).toBe("free"); + }); + + it("returns free when paid plan is unpaid or incomplete_expired", () => { + for (const status of ["unpaid", "incomplete_expired", "incomplete"]) { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: status, + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("free"); + } + }); + + it("granted plan with NULL expiry beats no paid plan", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: null, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.via).toBe("granted"); + expect(r.status).toBe("granted"); + }); + + it("granted plan with future expiry beats no paid plan", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: NOW + 1000, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.via).toBe("granted"); + }); + + it("granted plan with past expiry falls back to paid", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: NOW - 1, + personal_plan: "ink", + personal_plan_status: "active", + personal_plan_started_at: 500, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.via).toBe("paid"); + }); + + it("granted plan with past expiry and no paid plan falls back to free", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: NOW - 1, + }, NOW); + expect(r.plan).toBe("free"); + }); + + it("granted plan beats paid plan even when both are active", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: null, + personal_plan: "ink", + personal_plan_status: "active", + personal_plan_started_at: 500, + }, NOW); + expect(r.via).toBe("granted"); + }); + + it("unknown plan strings normalize to free", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "mystery_tier", + personal_plan_status: "active", + }, NOW); + expect(r.plan).toBe("free"); + }); + + it("surfaces cancelAt for paid plans pending cancellation", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "active", + personal_plan_started_at: 100, + personal_plan_cancel_at: NOW + 86400_000, + }, NOW); + expect(r.plan).toBe("ink"); + expect(r.cancelAt).toBe(NOW + 86400_000); + }); + + it("granted plans never carry a cancelAt", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: null, + personal_plan_cancel_at: NOW + 86400_000, + }, NOW); + expect(r.cancelAt).toBeNull(); + }); + + it("granted plans surface granted_plan_started_at as since", () => { + const r = resolvePersonalPlan({ + ...FREE, + granted_plan: "ink", + granted_plan_expires_at: null, + granted_plan_started_at: 12345, + }, NOW); + expect(r.via).toBe("granted"); + expect(r.since).toBe(12345); + }); + + it("crit sparkles default to true for paid Ink users (NULL column)", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "active", + }, NOW); + expect(r.critSparkles).toBe(true); + }); + + it("crit sparkles respect explicit 0 (off) for Ink users", () => { + const r = resolvePersonalPlan({ + ...FREE, + personal_plan: "ink", + personal_plan_status: "active", + personal_crit_sparkles: 0, + }, NOW); + expect(r.critSparkles).toBe(false); + }); + + it("crit sparkles are always false for free users", () => { + const r = resolvePersonalPlan({ ...FREE, personal_crit_sparkles: 1 }, NOW); + expect(r.plan).toBe("free"); + expect(r.critSparkles).toBe(false); + }); +}); diff --git a/packages/api/src/account/plan.ts b/packages/api/src/account/plan.ts new file mode 100644 index 0000000..3d81f2d --- /dev/null +++ b/packages/api/src/account/plan.ts @@ -0,0 +1,115 @@ +// Per-user plan resolution. Three sources of truth, in priority order: +// +// 1. granted_plan (set via wrangler one-liner for comps) - wins if it +// either has no expiry or hasn't expired yet +// 2. personal_plan (Stripe-managed) - active when status is one of +// active|trialing|past_due (past_due gets a grace period; the UI +// shows a banner but the perks stay on) +// 3. free +// +// Keep this a pure function so the api worker can import it via the +// same cross-package path it already uses for loadCurrentSession. + +export type PersonalPlan = "free" | "ink"; + +// Allowed ring style ids. Default ('shimmer') is what every supporter gets +// before customising; null on the row means "use the default". 'none' +// opts out of the animated ring entirely. Adding a new style: append the +// id here, add a CSS variant in ink-border.css, and add it to +// INK_PRESENCE_RING_STYLES below. +export const INK_RING_STYLES = ["shimmer", "aurora", "ember", "mono", "none"] as const; +export type InkRingStyle = typeof INK_RING_STYLES[number]; + +export function isInkRingStyle(value: unknown): value is InkRingStyle { + return typeof value === "string" && (INK_RING_STYLES as readonly string[]).includes(value); +} + +// Strict #rrggbb. We render the colour straight into a CSS box-shadow / +// caret-color, so we lock the input down to a known-safe shape. +const HEX_COLOR = /^#[0-9a-fA-F]{6}$/; +export function isInkPresenceColor(value: unknown): value is string { + return typeof value === "string" && HEX_COLOR.test(value); +} + +export type PlanRow = { + granted_plan: string | null; + granted_plan_expires_at: number | null; + granted_plan_started_at: number | null; + personal_plan: string | null; + personal_plan_status: string | null; + personal_plan_started_at: number | null; + personal_plan_cancel_at: number | null; + personal_plan_style: string | null; + personal_presence_color: string | null; + personal_crit_sparkles: number | null; +}; + +export type ResolvedPlan = { + plan: PersonalPlan; + via: "granted" | "paid" | "free"; + since: number | null; + status: string | null; + // When non-null, the active sub has been set to cancel and access + // ends at this Unix-ms timestamp. Stays in 'active' status until + // then; UI uses this to show "expires on X". + cancelAt: null | number; + // Cosmetic prefs. null on a free user (no Ink → no perks); for an Ink + // user, null means "use the default" (style: 'shimmer', presence colour: + // deterministic from userColor()). Persisted values that fail validation + // are normalised to null here so callers don't have to re-validate. + style: InkRingStyle | null; + presenceColor: string | null; + // Whether to render the dice crit sparkle burst for this user. Ink-only + // perk: false for free users. For Ink users, NULL on the row means "use + // the default" which is true; an explicit 0 turns it off. + critSparkles: boolean; +}; + +const ACTIVE_STATUSES = new Set(["active", "trialing", "past_due"]); + +function asPlan(value: string | null): PersonalPlan { + return value === "ink" ? "ink" : "free"; +} + +function readStyle(row: PlanRow): InkRingStyle | null { + return isInkRingStyle(row.personal_plan_style) ? row.personal_plan_style : null; +} + +function readPresenceColor(row: PlanRow): string | null { + return isInkPresenceColor(row.personal_presence_color) ? row.personal_presence_color : null; +} + +// NULL → default (on); explicit 0 → off; anything else → on. +function readCritSparkles(row: PlanRow): boolean { + return row.personal_crit_sparkles !== 0; +} + +export function resolvePersonalPlan(row: PlanRow, now: number = Date.now()): ResolvedPlan { + if (row.granted_plan && (row.granted_plan_expires_at === null || row.granted_plan_expires_at > now)) { + return { + plan: asPlan(row.granted_plan), + via: "granted", + since: row.granted_plan_started_at, + status: "granted", + cancelAt: null, + style: readStyle(row), + presenceColor: readPresenceColor(row), + critSparkles: readCritSparkles(row), + }; + } + + if (row.personal_plan && row.personal_plan_status && ACTIVE_STATUSES.has(row.personal_plan_status)) { + return { + plan: asPlan(row.personal_plan), + via: "paid", + since: row.personal_plan_started_at, + status: row.personal_plan_status, + cancelAt: row.personal_plan_cancel_at, + style: readStyle(row), + presenceColor: readPresenceColor(row), + critSparkles: readCritSparkles(row), + }; + } + + return { plan: "free", via: "free", since: null, status: null, cancelAt: null, style: null, presenceColor: null, critSparkles: false }; +} diff --git a/packages/api/src/account/session.ts b/packages/api/src/account/session.ts new file mode 100644 index 0000000..e7402a6 --- /dev/null +++ b/packages/api/src/account/session.ts @@ -0,0 +1,309 @@ +// Annex's own sessions, stored in cubedocs-main `sessions` and created from a +// verified OIDC id_token (routes/auth.ts). The JWT in the Authorization +// header is only proof that Annex minted the session; everything that can +// change (revocation, expiry, account standing, admin flag, plan, prefs) is +// re-read here on every request. +// +// Shared with the admin worker, which imports this file cross-package for its +// own 'admin' sessions. + +import { verifyJwt, signJwt, sha256b64url, randomToken } from "./jwt"; +import { resolvePersonalPlan } from "./plan"; +import { accountStanding, type IdentityEnv, type MirrorUser } from "./identity"; + +export type SessionKind = "app" | "admin"; + +export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; +// Admin-panel sessions are the highest-privilege token in the product - keep +// them to a working day. +export const ADMIN_SESSION_TTL_MS = 12 * 60 * 60 * 1000; +// How long the SPA has to redeem the single-use code from /auth/callback. +export const HANDOFF_TTL_MS = 60 * 1000; +// How stale last_used_at may get before a refresh write. +const LAST_USED_REFRESH_MS = 10 * 60 * 1000; + +export interface SessionEnv extends IdentityEnv { + JWT_SECRET: string; +} + +export interface LoadedSession { + userId: string; + email: string; + name: string; + expiresAt: number; + isAdmin: boolean; + sid: string; + personalPlan: "free" | "ink"; + personalPlanSince: number | null; + personalPlanStatus: string | null; + personalPlanCancelAt: number | null; + personalPlanStyle: string | null; + personalPresenceColor: string | null; + personalCritSparkles: boolean; + readingFont: string | null; + editingFont: string | null; + uiFont: string | null; + themeMode: string | null; + themeCustomColor: string | null; +} + +export type SessionLoadResult = + | { kind: "ok"; session: LoadedSession } + | { kind: "disabled" } + | { kind: "suspended"; until: number } + | { kind: "invalid" }; + +interface SessionUserRow extends MirrorUser { + pending_deletion: string | null; + personal_plan: string | null; + personal_plan_status: string | null; + personal_plan_started_at: number | null; + personal_plan_cancel_at: number | null; + personal_plan_style: string | null; + personal_presence_color: string | null; + personal_crit_sparkles: number | null; + granted_plan: string | null; + granted_plan_expires_at: number | null; + granted_plan_started_at: number | null; + reading_font: string | null; + editing_font: string | null; + ui_font: string | null; + theme_mode: string | null; + theme_custom_color: string | null; +} + +interface SessionStateRow { + id: string; + kind: string; + expires_at: number; + revoked_at: number | null; + last_used_at: number; + handoff_hash: string | null; +} + +// Loads, validates and re-derives a session: one D1 batch for the mirror row +// (+ billing, prefs, pending admin deletion) and the session row, then the +// identity service for live standing (cached, see account/identity.ts). +export async function loadCurrentSession( + token: string, + env: SessionEnv, + kind: SessionKind, + ctx?: { waitUntil(p: Promise): void }, +): Promise { + const claims = await verifyJwt(token, env.JWT_SECRET); + if (!claims?.sid) return { kind: "invalid" }; + + const db = env.DB; + const [userResult, sessionResult] = await db.batch([ + db.prepare( + `SELECT u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at, + d.id AS pending_deletion, + p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, + p.reading_font, p.editing_font, p.ui_font, + p.theme_mode, p.theme_custom_color, + b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, + b.personal_plan_cancel_at, + b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at + FROM users u + LEFT JOIN user_billing b ON b.user_id = u.id + LEFT JOIN user_preferences p ON p.user_id = u.id + LEFT JOIN user_deletions d ON d.user_id = u.id + WHERE u.id = ?`, + ).bind(claims.userId), + db.prepare( + "SELECT id, kind, expires_at, revoked_at, last_used_at, handoff_hash FROM sessions WHERE id = ? AND user_id = ?", + ).bind(claims.sid, claims.userId), + ]); + + const user = (userResult.results as SessionUserRow[])[0]; + const row = (sessionResult.results as SessionStateRow[])[0]; + const now = Date.now(); + + if (!user || !row) return { kind: "invalid" }; + if (row.kind !== kind) return { kind: "invalid" }; + if (row.revoked_at !== null || row.expires_at <= now) return { kind: "invalid" }; + // A session whose handoff code was never redeemed has no legitimate token. + if (row.handoff_hash !== null) return { kind: "invalid" }; + + // An admin-scheduled deletion of the user's Annex data blocks Annex at once + // and for as long as the schedule exists (pending or completed). + if (user.pending_deletion) return { kind: "disabled" }; + + const standing = await accountStanding(env, user, now, ctx); + if (!standing.ok) { + if (standing.reason === "disabled") return { kind: "disabled" }; + if (standing.reason === "suspended") return { kind: "suspended", until: standing.until }; + return { kind: "invalid" }; + } + + if (now - row.last_used_at > LAST_USED_REFRESH_MS) { + const touch = db.prepare("UPDATE sessions SET last_used_at = ? WHERE id = ?").bind(now, row.id).run() + .catch(err => console.error("[session] last_used_at refresh failed", String(err))); + // Bounded to one write per session per ~10 min, so awaiting it when + // there's no ExecutionContext costs little. + if (ctx) ctx.waitUntil(touch); + else await touch; + } + + const resolved = resolvePersonalPlan({ + granted_plan: user.granted_plan, + granted_plan_expires_at: user.granted_plan_expires_at, + granted_plan_started_at: user.granted_plan_started_at, + personal_plan: user.personal_plan, + personal_plan_status: user.personal_plan_status, + personal_plan_started_at: user.personal_plan_started_at, + personal_plan_cancel_at: user.personal_plan_cancel_at, + personal_plan_style: user.personal_plan_style, + personal_presence_color: user.personal_presence_color, + personal_crit_sparkles: user.personal_crit_sparkles, + }, now); + + return { + kind: "ok", + session: { + userId: user.id, + email: user.email, + name: user.name, + expiresAt: row.expires_at, + isAdmin: standing.isAdmin, + sid: row.id, + personalPlan: resolved.plan, + personalPlanSince: resolved.since, + personalPlanStatus: resolved.status, + personalPlanCancelAt: resolved.cancelAt, + personalPlanStyle: resolved.style, + personalPresenceColor: resolved.presenceColor, + personalCritSparkles: resolved.critSparkles, + readingFont: user.reading_font, + editingFont: user.editing_font, + uiFont: user.ui_font, + themeMode: user.theme_mode, + themeCustomColor: user.theme_custom_color, + }, + }; +} + +export function sessionResultToResponse(result: Exclude): Response { + if (result.kind === "disabled") { + return Response.json({ ok: false, error: "account_disabled" }, { status: 403 }); + } + if (result.kind === "suspended") { + return Response.json({ ok: false, error: "account_suspended", until: result.until }, { status: 403 }); + } + return Response.json({ ok: false, error: "Unauthorized", status: 401 }, { status: 401 }); +} + +export type DeviceKind = "phone" | "tablet" | "laptop" | "desktop"; + +// Coarse device kind + friendly client label from the User-Agent at session +// creation. Only the derived values are stored, never the raw UA. +export function parseUserAgent(ua: string | null): { deviceKind: DeviceKind | null; clientLabel: string | null } { + if (!ua) return { deviceKind: null, clientLabel: null }; + const deviceKind: DeviceKind = + /iPad/.test(ua) || (/Android/.test(ua) && !/Mobile/.test(ua)) ? "tablet" : + /iPhone|Android.*Mobile|Mobile.*Firefox|Windows Phone/.test(ua) ? "phone" : + /Macintosh|Mac OS X/.test(ua) ? "laptop" : + "desktop"; + const browser = + /Edg\//.test(ua) ? "Edge" : + /Firefox\//.test(ua) ? "Firefox" : + /Chrome\//.test(ua) ? "Chrome" : + /Safari\//.test(ua) ? "Safari" : + "Browser"; + const os = + /Windows/.test(ua) ? "Windows" : + /Mac OS X/.test(ua) ? "macOS" : + /Android/.test(ua) ? "Android" : + /iPhone|iPad|iOS/.test(ua) ? "iOS" : + /Linux/.test(ua) ? "Linux" : + ""; + return { deviceKind, clientLabel: os ? `${browser} on ${os}` : browser }; +} + +export function clientIp(request: Request): string | null { + return request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"); +} + +// Creates a session that can't be used until its handoff code is redeemed +// (redeemHandoff). Returns the code to hand the browser. +export async function createPendingSession( + db: D1Database, + opts: { userId: string; kind: SessionKind; request: Request; idToken: string | null; nowMs?: number }, +): Promise<{ sessionId: string; handoffCode: string }> { + const now = opts.nowMs ?? Date.now(); + const id = crypto.randomUUID(); + const code = randomToken(32); + const ttl = opts.kind === "admin" ? ADMIN_SESSION_TTL_MS : SESSION_TTL_MS; + const { deviceKind, clientLabel } = parseUserAgent(opts.request.headers.get("User-Agent")); + await db.batch([ + // Opportunistic GC of this user's dead rows (expired, revoked, or + // abandoned before their handoff was redeemed). + db.prepare( + `DELETE FROM sessions WHERE user_id = ? AND (expires_at <= ? OR revoked_at IS NOT NULL + OR (handoff_hash IS NOT NULL AND handoff_expires_at <= ?))`, + ).bind(opts.userId, now, now), + db.prepare( + `INSERT INTO sessions (id, user_id, kind, created_at, expires_at, last_used_at, device_kind, client_label, ip, id_token, handoff_hash, handoff_expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ).bind(id, opts.userId, opts.kind, now, now + ttl, now, deviceKind, clientLabel, clientIp(opts.request), opts.idToken, + await sha256b64url(code), now + HANDOFF_TTL_MS), + ]); + return { sessionId: id, handoffCode: code }; +} + +// Redeems a single-use handoff code for the session JWT. Exactly one caller +// can win the UPDATE; a replay, an expired code or a code for the other kind +// of session gets null. +export async function redeemHandoff(env: SessionEnv, code: string, kind: SessionKind, nowMs: number = Date.now()): Promise { + if (typeof code !== "string" || code.length < 16 || code.length > 128) return null; + const hash = await sha256b64url(code); + const row = await env.DB.prepare( + `UPDATE sessions SET handoff_hash = NULL, handoff_expires_at = NULL + WHERE handoff_hash = ? AND kind = ? AND handoff_expires_at > ? AND revoked_at IS NULL + RETURNING id, user_id, expires_at`, + ).bind(hash, kind, nowMs).first<{ id: string; user_id: string; expires_at: number }>(); + if (!row) return null; + const user = await env.DB.prepare("SELECT email, is_admin FROM users WHERE id = ?") + .bind(row.user_id).first<{ email: string; is_admin: number }>(); + if (!user) return null; + return signJwt({ userId: row.user_id, email: user.email, expiresAt: row.expires_at, isAdmin: Boolean(user.is_admin), sid: row.id }, env.JWT_SECRET); +} + +// Mints a ready-to-use session directly (local-dev quick login only). +export async function createSessionToken( + env: SessionEnv, + opts: { userId: string; email: string; isAdmin: boolean; kind: SessionKind; request: Request }, +): Promise { + const { sessionId, handoffCode } = await createPendingSession(env.DB, { ...opts, idToken: null }); + void sessionId; + const token = await redeemHandoff(env, handoffCode, opts.kind); + if (!token) throw new Error("session handoff failed"); + return token; +} + +// Revokes the session a token points at and returns the id_token kept for +// RP-initiated logout. Only the signature/expiry of the token is checked, not +// account standing: a disabled user must still be able to sign out. +export async function revokeSessionByToken( + env: SessionEnv, + token: string, + kind: SessionKind, +): Promise<{ revoked: boolean; idToken: string | null }> { + const claims = await verifyJwt(token, env.JWT_SECRET); + if (!claims?.sid) return { revoked: false, idToken: null }; + const row = await env.DB.prepare( + "UPDATE sessions SET revoked_at = ? WHERE id = ? AND user_id = ? AND kind = ? AND revoked_at IS NULL RETURNING id_token", + ).bind(Date.now(), claims.sid, claims.userId, kind).first<{ id_token: string | null }>(); + return { revoked: !!row, idToken: row?.id_token ?? null }; +} + +// Weekly-style sweep of dead session rows, run from the daily cron. +export const SESSION_SWEEP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; +export async function sweepSessions(db: D1Database, nowMs: number = Date.now()): Promise { + const cutoff = nowMs - SESSION_SWEEP_RETENTION_MS; + await db.prepare( + `DELETE FROM sessions WHERE expires_at <= ? AND (expires_at <= ? OR (revoked_at IS NOT NULL AND revoked_at < ?))`, + ).bind(cutoff + SESSION_TTL_MS, cutoff, cutoff).run(); + await db.prepare("DELETE FROM sessions WHERE handoff_hash IS NOT NULL AND handoff_expires_at <= ?").bind(nowMs).run(); + await db.prepare("DELETE FROM webhook_events WHERE processed_at < ?").bind(cutoff).run(); +} diff --git a/packages/api/src/auth.ts b/packages/api/src/auth.ts index 2e35fbf..f12554b 100644 --- a/packages/api/src/auth.ts +++ b/packages/api/src/auth.ts @@ -1,42 +1,47 @@ import type { Session } from "./lib"; import type { Env } from "./index"; -import { loadCurrentSession, sessionResultToResponse } from "../../auth/src/session"; +import { loadCurrentSession, sessionResultToResponse } from "./account/session"; -// Verifies the JWT and re-derives the session against the auth DB inline. -// Reads `users` + `sessions` directly via the AUTH_DB binding (one D1 batch), -// rather than round-tripping through the auth worker's /verify route, which -// would double the billable Worker invocations on every API request. +// Verifies the Annex session JWT and re-derives the session from cubedocs-main +// (one D1 batch: users mirror + billing + prefs + session row), with account +// standing from the identity service (cached ~60s, see account/identity.ts). // // Returns: // Session - authenticated; account is in good standing. -// Response - token was valid but the account is disabled / suspended. -// Pass this response straight back to the client. -// null - no/malformed Authorization header, or the token itself was -// invalid/expired. Caller maps this to a generic 401. -export async function authenticate(request: Request, env: Env): Promise { +// Response - token was valid but the account is disabled / suspended / +// blocked by a pending admin deletion. Pass it straight back. +// null - no/malformed Authorization header, or the token/session is +// invalid, revoked or expired. Caller maps this to a 401. +export async function authenticate( + request: Request, + env: Env, + ctx?: { waitUntil(p: Promise): void }, +): Promise { const authHeader = request.headers.get("Authorization"); if (!authHeader?.startsWith("Bearer ")) return null; - const result = await loadCurrentSession(authHeader.slice(7), env.AUTH_DB, env.JWT_SECRET); + const result = await loadCurrentSession(authHeader.slice(7), env, "app", ctx); if (result.kind === "ok") { + const s = result.session; return { - userId: result.session.userId, - email: result.session.email, - expiresAt: result.session.expiresAt, - personalPlan: result.session.personalPlan ?? "free", - personalPlanSince: result.session.personalPlanSince ?? null, - personalPlanStatus: result.session.personalPlanStatus ?? null, - personalPlanCancelAt: result.session.personalPlanCancelAt ?? null, - personalPlanStyle: result.session.personalPlanStyle ?? null, - personalPresenceColor: result.session.personalPresenceColor ?? null, - personalCritSparkles: result.session.personalCritSparkles ?? true, - readingFont: result.session.readingFont ?? null, - editingFont: result.session.editingFont ?? null, - uiFont: result.session.uiFont ?? null, - isAdmin: result.session.isAdmin ?? false, - sid: result.session.sid, - themeMode: result.session.themeMode ?? null, - themeCustomColor: result.session.themeCustomColor ?? null, + userId: s.userId, + email: s.email, + name: s.name, + expiresAt: s.expiresAt, + personalPlan: s.personalPlan, + personalPlanSince: s.personalPlanSince, + personalPlanStatus: s.personalPlanStatus, + personalPlanCancelAt: s.personalPlanCancelAt, + personalPlanStyle: s.personalPlanStyle, + personalPresenceColor: s.personalPresenceColor, + personalCritSparkles: s.personalCritSparkles, + readingFont: s.readingFont, + editingFont: s.editingFont, + uiFont: s.uiFont, + isAdmin: s.isAdmin, + sid: s.sid, + themeMode: s.themeMode, + themeCustomColor: s.themeCustomColor, }; } if (result.kind === "invalid") return null; diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index a1db0b2..f77faee 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -24,9 +24,12 @@ import { handleUserByHandle } from "./routes/userHandles"; import { pruneDocRevisions } from "./lib/docOps"; import { purgeExpiredTrash } from "./lib/trash"; import { DocCollabRoom } from "./collab/DocCollabRoom"; -import { resolvePersonalPlan } from "../../auth/src/plan"; +import { resolvePersonalPlan } from "./account/plan"; import { resolveAvatar, parseVariant, avatarKey, deleteAllAvatarVariants } from "./avatar"; import { resolveAccess } from "./lib/access"; +import type { IdentityService } from "./account/identity"; +import { sweepSessions } from "./account/session"; +import { handleAuthCallback, handleAuthExchange, handleAuthLogin, handleAuthLogout, handleDevQuickLogin } from "./routes/auth"; export { DocCollabRoom }; @@ -36,7 +39,24 @@ export interface Env { ASSETS: R2Bucket; AUTH: Fetcher; // Service binding to cubedocs-auth (mutating routes only) DOC_COLLAB?: DurableObjectNamespace; + // Annex-only HS256 secret for Annex's own session JWTs (no longer shared + // with the identity service). JWT_SECRET: string; + // Identity service (auth.cubityfir.st) RPC: account lookups, standing and + // deletions. Optional so unit tests and a local stack without the identity + // worker fall back to the users mirror. + IDENTITY?: IdentityService; + // OIDC client settings (see routes/auth.ts). OIDC_CLIENT_SECRET is a secret; + // the rest are vars. Redirect URIs default to APP_ORIGIN/api/auth/callback + // and APP_ORIGIN/. + OIDC_ISSUER?: string; + OIDC_CLIENT_ID?: string; + OIDC_CLIENT_SECRET?: string; + OIDC_REDIRECT_URI?: string; + OIDC_POST_LOGOUT_REDIRECT_URI?: string; + APP_ORIGIN?: string; + // "true" (with a localhost APP_ORIGIN) enables POST /dev/quick-login. + DEV_QUICK_LOGIN?: string; OPENAI_API_KEY?: string; // Cloudflare-for-SaaS custom domains (see routes/customDomains.ts). Optional: // when unset, the custom-domain endpoints report "not configured" instead of @@ -82,6 +102,10 @@ export default { .then(n => { if (n > 0) console.log(`[graph] reindexed ${n} stale site graphs`); }) .catch(err => console.error("[graph] stale reindex failed:", err)), ); + // Dead Annex sessions, abandoned sign-in handoffs, old webhook markers. + ctx.waitUntil( + sweepSessions(env.DB).catch(err => console.error("[sessions] sweep failed:", err)), + ); }, async fetch(request: Request, env: Env): Promise { @@ -108,6 +132,15 @@ export default { return addCorsHeaders(await handlePublicApi(request, env, url)); } + // Sign in with auth.cubityfir.st (routes/auth.ts). login/callback are + // top-level browser navigations (redirects, no CORS); exchange/logout + // are called by the SPA. + if (url.pathname === "/auth/login" && request.method === "GET") return await handleAuthLogin(request, env, url); + if (url.pathname === "/auth/callback" && request.method === "GET") return await handleAuthCallback(request, env, url); + if (url.pathname === "/auth/exchange" && request.method === "POST") return addCorsHeaders(await handleAuthExchange(request, env)); + if (url.pathname === "/auth/logout" && request.method === "POST") return addCorsHeaders(await handleAuthLogout(request, env)); + if (url.pathname === "/dev/quick-login" && request.method === "POST") return addCorsHeaders(await handleDevQuickLogin(request, env)); + // Proxy auth routes to the auth worker if ( url.pathname === "/register" || @@ -115,8 +148,7 @@ export default { url.pathname === "/force-change-password" || url.pathname === "/verify-email/resend" || url.pathname === "/admin/handoff/start" || - url.pathname === "/oauth/authorize" || - url.pathname === "/dev/quick-login" + url.pathname === "/oauth/authorize" ) { return env.AUTH.fetch(`https://auth${url.pathname}`, await proxyAuthInit(request)); } diff --git a/packages/api/src/lib.ts b/packages/api/src/lib.ts index 161665a..8c86d8b 100644 --- a/packages/api/src/lib.ts +++ b/packages/api/src/lib.ts @@ -1,6 +1,9 @@ export interface Session { userId: string; email: string; + // Display name from the users mirror (owned by the identity service). + // Optional so hand-built test sessions don't need it. + name?: string; expiresAt: number; personalPlan?: "free" | "ink"; personalPlanSince?: number | null; diff --git a/packages/api/src/me.test.ts b/packages/api/src/me.test.ts index 1b77c6e..983366a 100644 --- a/packages/api/src/me.test.ts +++ b/packages/api/src/me.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect, beforeEach, vi } from "vitest"; import { fileURLToPath } from "node:url"; import { createSqliteD1, type SqliteD1 } from "./test/sqliteD1"; -import { signJwt } from "../../auth/src/jwt"; +import { seedSession } from "./test/session"; import worker, { type Env } from "./index"; const AUTH_MIGRATIONS = fileURLToPath(new URL("../../auth/migrations", import.meta.url)); @@ -62,10 +62,8 @@ beforeEach(async () => { auth = createSqliteD1(AUTH_MIGRATIONS); r2 = new FakeR2(); authFetch = vi.fn(async () => Response.json({ ok: true })); - const now = Date.now(); auth.sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'u1@example.com', 'User One', 'x', datetime('now'))").run(); - auth.sqlite.prepare("INSERT INTO sessions (id, user_id, created_at, expires_at, last_used_at) VALUES ('s1', 'u1', ?, ?, ?)").run(now, now + 3_600_000, now); - token = await signJwt({ userId: "u1", email: "u1@example.com", expiresAt: now + 3_600_000, sid: "s1" }, JWT_SECRET); + token = await seedSession(api.sqlite, { userId: "u1", email: "u1@example.com", name: "User One", sid: "s1", secret: JWT_SECRET }); }); describe("POST /me/favourite-sites/:id cap", () => { diff --git a/packages/api/src/routes/auth.test.ts b/packages/api/src/routes/auth.test.ts new file mode 100644 index 0000000..99626ac --- /dev/null +++ b/packages/api/src/routes/auth.test.ts @@ -0,0 +1,354 @@ +// Sign in with auth.cubityfir.st, end to end through the worker's fetch +// handler against a fake OpenID provider and a real SQLite main DB. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { createSqliteD1, type SqliteD1 } from "../test/sqliteD1"; +import { createFakeIdp, type FakeIdp, type FakeUser } from "../test/fakeIdp"; +import { setOidcFetchForTests, STATE_COOKIE } from "./auth"; +import { clearOidcCaches } from "../account/oidc"; +import { clearIdentityCache, type IdentityService, type IdentityUser } from "../account/identity"; +import worker, { type Env } from "../index"; + +const APP = "https://docs.test"; +const CALLBACK = `${APP}/api/auth/callback`; +const SECRET = "jwt-secret"; + +let db: SqliteD1; +let idp: FakeIdp; +let identity: { getUser: ReturnType; getUsers: ReturnType; findUserByEmail: ReturnType; listDeletedUsers: ReturnType }; +let extraEnv: Partial; + +const ALICE: FakeUser = { sub: "user-alice", email: "alice@example.com", name: "Alice", roles: ["user"] }; + +function identityUser(over: Partial = {}): IdentityUser { + return { id: ALICE.sub, email: ALICE.email, name: ALICE.name, emailVerified: true, isAdmin: false, status: "active", suspendedUntil: null, createdAt: "2025-01-01T00:00:00.000Z", ...over }; +} + +function env(): Env { + return { + DB: db.db, + JWT_SECRET: SECRET, + OIDC_ISSUER: idp.issuer, + OIDC_CLIENT_ID: "annex-docs", + OIDC_CLIENT_SECRET: "s3cret", + APP_ORIGIN: APP, + IDENTITY: identity as unknown as IdentityService, + ...extraEnv, + } as unknown as Env; +} + +function call(method: string, path: string, init: { token?: string; cookie?: string; body?: unknown } = {}) { + const headers: Record = {}; + if (init.token) headers.Authorization = `Bearer ${init.token}`; + if (init.cookie) headers.Cookie = init.cookie; + if (init.body !== undefined) headers["Content-Type"] = "application/json"; + return worker.fetch(new Request(`https://api${path}`, { + method, + headers, + body: init.body !== undefined ? JSON.stringify(init.body) : undefined, + redirect: "manual", + }), env()); +} + +function cookieFrom(res: Response): string { + const set = res.headers.get("Set-Cookie") ?? ""; + return set.split(";")[0]; +} + +function fragment(res: Response): URLSearchParams { + const loc = res.headers.get("Location")!; + expect(loc.startsWith(`${APP}/auth/complete#`)).toBe(true); + return new URLSearchParams(loc.slice(loc.indexOf("#") + 1)); +} + +// login -> authorize at the IdP -> callback; returns the callback response. +async function signIn(user: FakeUser = ALICE, returnTo = "/projects"): Promise { + const login = await call("GET", `/auth/login?return_to=${encodeURIComponent(returnTo)}`); + expect(login.status).toBe(302); + const callbackUrl = new URL(idp.authorize(login.headers.get("Location")!, user)); + return call("GET", `/auth/callback${callbackUrl.search}`, { cookie: cookieFrom(login) }); +} + +async function signInToken(user: FakeUser = ALICE): Promise { + const cb = await signIn(user); + const code = fragment(cb).get("code")!; + const ex = await call("POST", "/auth/exchange", { body: { code } }); + expect(ex.status).toBe(200); + return ((await ex.json()) as { data: { token: string } }).data.token; +} + +beforeEach(async () => { + db = createSqliteD1(); + idp = await createFakeIdp({ clients: { "annex-docs": { secret: "s3cret", redirectUris: [CALLBACK] } } }); + setOidcFetchForTests(idp.fetch); + clearOidcCaches(); + clearIdentityCache(); + extraEnv = {}; + identity = { + getUser: vi.fn(async () => identityUser()), + getUsers: vi.fn(async () => []), + findUserByEmail: vi.fn(async () => null), + listDeletedUsers: vi.fn(async () => []), + }; +}); + +afterEach(() => setOidcFetchForTests(undefined)); + +describe("GET /auth/login", () => { + it("redirects to the issuer's authorize endpoint with PKCE, state and nonce, and sets a sealed state cookie", async () => { + const res = await call("GET", "/auth/login?return_to=/projects/p1"); + expect(res.status).toBe(302); + const loc = new URL(res.headers.get("Location")!); + expect(`${loc.origin}${loc.pathname}`).toBe(`${idp.issuer}/oauth/authorize`); + expect(loc.searchParams.get("client_id")).toBe("annex-docs"); + expect(loc.searchParams.get("redirect_uri")).toBe(CALLBACK); + expect(loc.searchParams.get("scope")).toBe("openid profile email roles"); + expect(loc.searchParams.get("code_challenge_method")).toBe("S256"); + expect(loc.searchParams.get("state")).toBeTruthy(); + expect(loc.searchParams.get("nonce")).toBeTruthy(); + const cookie = res.headers.get("Set-Cookie")!; + expect(cookie).toContain(`${STATE_COOKIE}=`); + expect(cookie).toContain("HttpOnly"); + expect(cookie).toContain("SameSite=Lax"); + expect(cookie).toContain("Secure"); + expect(cookie).toContain("Path=/api/auth"); + }); + + it("only passes prompt=login through", async () => { + const forced = new URL((await call("GET", "/auth/login?prompt=login")).headers.get("Location")!); + expect(forced.searchParams.get("prompt")).toBe("login"); + const other = new URL((await call("GET", "/auth/login?prompt=none")).headers.get("Location")!); + expect(other.searchParams.has("prompt")).toBe(false); + }); + + it("503s when sign-in isn't configured", async () => { + extraEnv = { OIDC_CLIENT_ID: undefined }; + expect((await call("GET", "/auth/login")).status).toBe(503); + }); +}); + +describe("GET /auth/callback", () => { + it("verifies the id_token, upserts the users mirror and hands the SPA a single-use code", async () => { + const res = await signIn(ALICE, "/projects/p1"); + expect(res.status).toBe(302); + expect(res.headers.get("Set-Cookie")).toContain("Max-Age=0"); + const frag = fragment(res); + expect(frag.get("return_to")).toBe("/projects/p1"); + const code = frag.get("code")!; + expect(code.length).toBeGreaterThan(20); + + expect(db.sqlite.prepare("SELECT email, name, is_admin, status FROM users WHERE id = ?").get(ALICE.sub)) + .toEqual({ email: ALICE.email, name: ALICE.name, is_admin: 0, status: "active" }); + const session = db.sqlite.prepare("SELECT kind, id_token, handoff_hash FROM sessions WHERE user_id = ?").get(ALICE.sub) as Record; + expect(session.kind).toBe("app"); + expect(session.id_token.split(".")).toHaveLength(3); + expect(session.handoff_hash).toBeTruthy(); + + const ex = await call("POST", "/auth/exchange", { body: { code } }); + expect(ex.status).toBe(200); + const token = ((await ex.json()) as { data: { token: string } }).data.token; + // The code is single use. + expect((await call("POST", "/auth/exchange", { body: { code } })).status).toBe(400); + + const me = await call("GET", "/me/favourite-sites", { token }); + expect(me.status).toBe(200); + }); + + it("refreshes name/email on the mirror and the member snapshots at sign-in", async () => { + await signInToken(); + db.sqlite.prepare("INSERT INTO projects (id, name, owner_id, created_at) VALUES ('p1', 'P', 'x', 't')").run(); + db.sqlite.prepare("INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at) VALUES ('m1', 'p1', ?, 'old@example.com', 'Old', 'editor', 'x', 't')").run(ALICE.sub); + await signInToken({ ...ALICE, name: "Alice Liddell", email: "liddell@example.com" }); + expect(db.sqlite.prepare("SELECT name, email FROM users WHERE id = ?").get(ALICE.sub)).toEqual({ name: "Alice Liddell", email: "liddell@example.com" }); + expect(db.sqlite.prepare("SELECT name, email FROM project_members WHERE id = 'm1'").get()).toEqual({ name: "Alice Liddell", email: "liddell@example.com" }); + }); + + it("records admin from the roles claim", async () => { + await signInToken({ ...ALICE, roles: ["user", "admin"] }); + expect(db.sqlite.prepare("SELECT is_admin FROM users WHERE id = ?").get(ALICE.sub)).toEqual({ is_admin: 1 }); + }); + + it("refuses a callback without the state cookie", async () => { + const login = await call("GET", "/auth/login"); + const cb = new URL(idp.authorize(login.headers.get("Location")!, ALICE)); + const res = await call("GET", `/auth/callback${cb.search}`); + expect(fragment(res).get("error")).toBe("login_expired"); + expect(idp.tokenRequests).toBe(0); + }); + + it("refuses a forged state cookie", async () => { + const login = await call("GET", "/auth/login"); + const cb = new URL(idp.authorize(login.headers.get("Location")!, ALICE)); + const [name, value] = cookieFrom(login).split("="); + const [body] = value.split("."); + const res = await call("GET", `/auth/callback${cb.search}`, { cookie: `${name}=${body}.AAAA` }); + expect(fragment(res).get("error")).toBe("login_expired"); + }); + + it("refuses a state mismatch (callback from another login)", async () => { + const first = await call("GET", "/auth/login"); + const second = await call("GET", "/auth/login"); + const cb = new URL(idp.authorize(first.headers.get("Location")!, ALICE)); + const res = await call("GET", `/auth/callback${cb.search}`, { cookie: cookieFrom(second) }); + expect(fragment(res).get("error")).toBeTruthy(); + expect(fragment(res).get("code")).toBeNull(); + expect(idp.tokenRequests).toBe(0); + }); + + it("refuses an id_token with the wrong nonce", async () => { + idp.tamper.nonce = "attacker-nonce"; + const res = await signIn(); + expect(fragment(res).get("error")).toBe("invalid_token_response"); + expect(db.sqlite.prepare("SELECT COUNT(*) AS n FROM sessions").get()).toEqual({ n: 0 }); + }); + + it("refuses an id_token for another audience", async () => { + idp.tamper.aud = "someone-else"; + expect(fragment(await signIn()).get("error")).toBe("invalid_token_response"); + }); + + it("refuses an id_token from another issuer", async () => { + idp.tamper.iss = "https://evil.test"; + expect(fragment(await signIn()).get("error")).toBe("invalid_token_response"); + }); + + it("refuses an expired id_token", async () => { + idp.tamper.expSec = Math.floor(Date.now() / 1000) - 3600; + expect(fragment(await signIn()).get("error")).toBe("invalid_token_response"); + }); + + it("refuses an id_token whose signature doesn't verify against the JWKS", async () => { + idp.tamper.signWithOtherKey = true; + expect(fragment(await signIn()).get("error")).toBe("invalid_signature"); + expect(db.sqlite.prepare("SELECT COUNT(*) AS n FROM users").get()).toEqual({ n: 0 }); + }); + + it("passes an OAuth error code through, never the description", async () => { + const login = await call("GET", "/auth/login"); + const res = await call("GET", "/auth/callback?error=access_denied&error_description=%3Cscript%3E", { cookie: cookieFrom(login) }); + const frag = fragment(res); + expect(frag.get("error")).toBe("access_denied"); + expect([...frag.keys()]).toEqual(["error"]); + }); + + it("refuses a user whose Annex data is scheduled for deletion", async () => { + await signInToken(); + db.sqlite.prepare("INSERT INTO user_deletions (user_id, id, requested_by, requested_by_email, execute_after) VALUES (?, 'd1', 'admin', 'a@x', 0)").run(ALICE.sub); + expect(fragment(await signIn()).get("error")).toBe("account_disabled"); + }); + + it("refuses an account Annex has processed as deleted on the identity service", async () => { + db.sqlite.prepare("INSERT INTO identity_deletions (user_id, deleted_at, deleted_by) VALUES (?, 1, 'self')").run(ALICE.sub); + expect(fragment(await signIn()).get("error")).toBe("account_deleted"); + expect(db.sqlite.prepare("SELECT COUNT(*) AS n FROM users").get()).toEqual({ n: 0 }); + }); + + it("falls back to / for an off-site return_to", async () => { + for (const bad of ["https://evil.test/", "//evil.test", "/\\evil.test", "javascript:alert(1)"]) { + const res = await signIn(ALICE, bad); + expect(fragment(res).get("return_to")).toBe("/"); + } + }); +}); + +describe("session standing", () => { + it("locks out a user disabled on the identity service", async () => { + const token = await signInToken(); + clearIdentityCache(); + identity.getUser.mockResolvedValue(identityUser({ status: "disabled" })); + const res = await call("GET", "/me/favourite-sites", { token }); + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ error: "account_disabled" }); + expect(db.sqlite.prepare("SELECT status FROM users WHERE id = ?").get(ALICE.sub)).toEqual({ status: "disabled" }); + }); + + it("reports a suspension with its end", async () => { + const token = await signInToken(); + clearIdentityCache(); + const until = Math.floor(Date.now() / 1000) + 600; + identity.getUser.mockResolvedValue(identityUser({ status: "suspended", suspendedUntil: until })); + const res = await call("GET", "/me/favourite-sites", { token }); + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ error: "account_suspended", until }); + }); + + it("treats an account deleted on the identity service as signed out", async () => { + const token = await signInToken(); + clearIdentityCache(); + identity.getUser.mockResolvedValue(null); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + }); + + it("caches standing per isolate instead of calling the identity service on every request", async () => { + const token = await signInToken(); + identity.getUser.mockClear(); + for (let i = 0; i < 3; i++) expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(200); + expect(identity.getUser).toHaveBeenCalledTimes(1); + }); + + it("falls back to the mirror's standing when the identity service is unreachable", async () => { + const token = await signInToken(); + clearIdentityCache(); + identity.getUser.mockRejectedValue(new Error("service binding unavailable")); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(200); + db.sqlite.prepare("UPDATE users SET status = 'disabled' WHERE id = ?").run(ALICE.sub); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(403); + }); + + it("blocks an existing session as soon as an admin deletion is scheduled", async () => { + const token = await signInToken(); + db.sqlite.prepare("INSERT INTO user_deletions (user_id, id, requested_by, requested_by_email, execute_after) VALUES (?, 'd1', 'admin', 'a@x', 0)").run(ALICE.sub); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(403); + }); + + it("refuses an app token on a session of the admin kind", async () => { + const token = await signInToken(); + db.sqlite.prepare("UPDATE sessions SET kind = 'admin'").run(); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + }); +}); + +describe("POST /auth/logout", () => { + it("revokes the Annex session and returns the end-session URL with id_token_hint", async () => { + const token = await signInToken(); + const idToken = (db.sqlite.prepare("SELECT id_token FROM sessions").get() as { id_token: string }).id_token; + const res = await call("POST", "/auth/logout", { token }); + expect(res.status).toBe(200); + const url = new URL(((await res.json()) as { data: { logoutUrl: string } }).data.logoutUrl); + expect(`${url.origin}${url.pathname}`).toBe(`${idp.issuer}/oauth/logout`); + expect(url.searchParams.get("id_token_hint")).toBe(idToken); + expect(url.searchParams.get("post_logout_redirect_uri")).toBe(`${APP}/`); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(401); + }); + + it("still signs a disabled user out", async () => { + const token = await signInToken(); + clearIdentityCache(); + identity.getUser.mockResolvedValue(identityUser({ status: "disabled" })); + const res = await call("POST", "/auth/logout", { token }); + expect(res.status).toBe(200); + expect(db.sqlite.prepare("SELECT revoked_at IS NOT NULL AS r FROM sessions").get()).toEqual({ r: 1 }); + }); +}); + +describe("POST /dev/quick-login", () => { + it("is a 404 unless DEV_QUICK_LOGIN is on AND the app origin is localhost", async () => { + extraEnv = { DEV_QUICK_LOGIN: "true" }; + expect((await call("POST", "/dev/quick-login", { body: { variant: "standard-free" } })).status).toBe(404); + extraEnv = { APP_ORIGIN: "http://localhost:5173" }; + expect((await call("POST", "/dev/quick-login", { body: { variant: "standard-free" } })).status).toBe(404); + }); + + it("mints a mirror-only dev user and a working session without asking the identity service", async () => { + extraEnv = { DEV_QUICK_LOGIN: "true", APP_ORIGIN: "http://localhost:5173" }; + const res = await call("POST", "/dev/quick-login", { body: { email: "E2E-a@example.com", name: "E2E A" } }); + expect(res.status).toBe(200); + const { token, userId } = ((await res.json()) as { data: { token: string; userId: string } }).data; + expect(userId.startsWith("dev-")).toBe(true); + identity.getUser.mockResolvedValue(null); + expect((await call("GET", "/me/favourite-sites", { token })).status).toBe(200); + expect(identity.getUser).not.toHaveBeenCalled(); + // Same email signs back in as the same dev user. + const again = await call("POST", "/dev/quick-login", { body: { email: "e2e-a@example.com" } }); + expect(((await again.json()) as { data: { userId: string } }).data.userId).toBe(userId); + }); +}); diff --git a/packages/api/src/routes/auth.ts b/packages/api/src/routes/auth.ts new file mode 100644 index 0000000..2f68b69 --- /dev/null +++ b/packages/api/src/routes/auth.ts @@ -0,0 +1,246 @@ +// Sign in with auth.cubityfir.st (Annex as an OIDC client). +// +// GET /auth/login?return_to=/path -> 302 to the identity service +// GET /auth/callback -> verifies, upserts the users mirror, +// creates an Annex session, 302 to the +// SPA's /auth/complete#code=... +// POST /auth/exchange { code } -> { token } (single use, 60s) +// POST /auth/logout -> revokes the Annex session and returns +// the identity service's end-session URL +// POST /dev/quick-login -> local dev only (DEV_QUICK_LOGIN) +// +// Browser paths are /api/auth/* (the frontend worker and the Vite dev proxy +// strip the /api prefix), so the state cookie is scoped to /api/auth. + +import { errorResponse, Errors, okResponse } from "../lib"; +import { + buildLoginRedirect, + buildLogoutUrl, + completeLogin, + openLoginState, + readCookie, + safeReturnTo, + sealLoginState, + stateCookie, + OidcError, + LOGIN_STATE_TTL_MS, + type OidcClientConfig, +} from "../account/oidc"; +import { createPendingSession, createSessionToken, redeemHandoff, revokeSessionByToken, type SessionEnv } from "../account/session"; +import { DEV_USER_PREFIX, isLocalDeploy, refreshMirror, type IdentityUser } from "../account/identity"; + +export interface AuthRouteEnv extends SessionEnv { + OIDC_ISSUER?: string; + OIDC_CLIENT_ID?: string; + OIDC_CLIENT_SECRET?: string; + OIDC_REDIRECT_URI?: string; + OIDC_POST_LOGOUT_REDIRECT_URI?: string; + APP_ORIGIN?: string; +} + +export const STATE_COOKIE = "annex_oidc"; +const STATE_COOKIE_PATH = "/api/auth"; +export const APP_SCOPE = "openid profile email roles"; + +// Test hook: lets tests point the flow at a fake identity provider. +let fetchOverride: typeof fetch | undefined; +export function setOidcFetchForTests(f: typeof fetch | undefined): void { + fetchOverride = f; +} + +function appOrigin(env: AuthRouteEnv): string { + return (env.APP_ORIGIN ?? "https://docs.cubityfir.st").replace(/\/+$/, ""); +} + +export function appOidcConfig(env: AuthRouteEnv): OidcClientConfig | null { + if (!env.OIDC_ISSUER || !env.OIDC_CLIENT_ID) return null; + const origin = appOrigin(env); + return { + issuer: env.OIDC_ISSUER.replace(/\/+$/, ""), + clientId: env.OIDC_CLIENT_ID, + clientSecret: env.OIDC_CLIENT_SECRET || undefined, + redirectUri: env.OIDC_REDIRECT_URI || `${origin}/api/auth/callback`, + postLogoutRedirectUri: env.OIDC_POST_LOGOUT_REDIRECT_URI || `${origin}/`, + scope: APP_SCOPE, + fetchImpl: fetchOverride, + }; +} + +function isSecure(env: AuthRouteEnv): boolean { + return appOrigin(env).startsWith("https://"); +} + +function redirect(location: string, cookies: string[] = []): Response { + const headers = new Headers({ Location: location, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }); + for (const c of cookies) headers.append("Set-Cookie", c); + return new Response(null, { status: 302, headers }); +} + +// Sends the browser to the SPA's /auth/complete with the outcome in the URL +// fragment (fragments never reach servers, logs or Referer headers). +function toComplete(env: AuthRouteEnv, fragment: Record, cookies: string[]): Response { + return redirect(`${appOrigin(env)}/auth/complete#${new URLSearchParams(fragment).toString()}`, cookies); +} + +function clearStateCookie(env: AuthRouteEnv): string { + return stateCookie(STATE_COOKIE, "", { path: STATE_COOKIE_PATH, secure: isSecure(env), maxAgeSec: 0 }); +} + +export async function handleAuthLogin(request: Request, env: AuthRouteEnv, url: URL): Promise { + const cfg = appOidcConfig(env); + if (!cfg) return Response.json({ ok: false, error: "sign_in_not_configured" }, { status: 503 }); + const returnTo = safeReturnTo(url.searchParams.get("return_to")); + // Only `login` (force re-authentication) is passed through; anything else + // would let a link drive the identity service's prompt handling. + const prompt = url.searchParams.get("prompt") === "login" ? "login" : undefined; + let login; + try { + login = await buildLoginRedirect(cfg, { returnTo, prompt }); + } catch (err) { + console.error("[auth] login redirect failed", String(err)); + return toComplete(env, { error: "identity_unavailable" }, []); + } + const sealed = await sealLoginState(login.state, env.JWT_SECRET); + return redirect(login.url, [ + stateCookie(STATE_COOKIE, sealed, { path: STATE_COOKIE_PATH, secure: isSecure(env), maxAgeSec: LOGIN_STATE_TTL_MS / 1000 }), + ]); +} + +export async function handleAuthCallback(request: Request, env: AuthRouteEnv, url: URL): Promise { + const cfg = appOidcConfig(env); + if (!cfg) return Response.json({ ok: false, error: "sign_in_not_configured" }, { status: 503 }); + const clear = clearStateCookie(env); + + const login = await openLoginState(readCookie(request, STATE_COOKIE), env.JWT_SECRET); + if (!login) return toComplete(env, { error: "login_expired" }, [clear]); + + // The user cancelled or the identity service refused: pass the OAuth error + // code through (a fixed vocabulary - never the free-text description). + const oauthError = url.searchParams.get("error"); + if (oauthError) { + const code = /^[a-z_]{1,64}$/.test(oauthError) ? oauthError : "sign_in_failed"; + return toComplete(env, { error: code }, [clear]); + } + + // The callback URL the identity service redirected to is our registered + // redirect_uri; rebuild it from config (behind the frontend worker the + // request URL is https://api/auth/callback). + const callbackUrl = new URL(cfg.redirectUri); + callbackUrl.search = url.search; + + let identity; + try { + identity = await completeLogin(cfg, callbackUrl, login); + } catch (err) { + const code = err instanceof OidcError ? err.code : "sign_in_failed"; + console.error("[auth] callback failed", { code, err: String(err) }); + return toComplete(env, { error: /^[a-z_]{1,64}$/.test(code) ? code : "sign_in_failed" }, [clear]); + } + + const outcome = await startSession(env, request, identity, "app"); + if ("error" in outcome) return toComplete(env, { error: outcome.error }, [clear]); + return toComplete(env, { code: outcome.handoffCode, return_to: login.returnTo }, [clear]); +} + +// Shared by the app and admin callbacks: refuses accounts Annex has blocked +// or processed as deleted, upserts the mirror, creates a pending session. +export async function startSession( + env: SessionEnv, + request: Request, + identity: { sub: string; email: string; emailVerified: boolean; name: string; roles: string[]; idToken: string }, + kind: "app" | "admin", +): Promise<{ handoffCode: string } | { error: string }> { + const [gone, blocked, existing] = await env.DB.batch([ + env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(identity.sub), + env.DB.prepare("SELECT 1 AS x FROM user_deletions WHERE user_id = ?").bind(identity.sub), + env.DB.prepare("SELECT created_at FROM users WHERE id = ?").bind(identity.sub), + ]); + if (gone.results.length > 0) return { error: "account_deleted" }; + if (blocked.results.length > 0) return { error: "account_disabled" }; + if (kind === "admin" && !identity.roles.includes("admin")) return { error: "not_admin" }; + + const now = Date.now(); + // The token endpoint only issues tokens to accounts in good standing, so + // the identity is active right now. + const user: IdentityUser = { + id: identity.sub, + email: identity.email, + name: identity.name, + emailVerified: identity.emailVerified, + isAdmin: identity.roles.includes("admin"), + status: "active", + suspendedUntil: null, + createdAt: (existing.results[0] as { created_at?: string } | undefined)?.created_at ?? new Date(now).toISOString(), + }; + await refreshMirror(env.DB, user, now, { login: true }); + const { handoffCode } = await createPendingSession(env.DB, { userId: user.id, kind, request, idToken: identity.idToken, nowMs: now }); + return { handoffCode }; +} + +export async function handleAuthExchange(request: Request, env: AuthRouteEnv): Promise { + const body = await request.json<{ code?: unknown }>().catch(() => null); + const code = typeof body?.code === "string" ? body.code : ""; + const token = await redeemHandoff(env, code, "app"); + if (!token) return Response.json({ ok: false, error: "invalid_code" }, { status: 400 }); + return okResponse({ token }); +} + +export async function handleAuthLogout(request: Request, env: AuthRouteEnv): Promise { + const cfg = appOidcConfig(env); + const authHeader = request.headers.get("Authorization"); + const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : ""; + const { idToken } = token ? await revokeSessionByToken(env, token, "app") : { idToken: null }; + const logoutUrl = cfg ? await buildLogoutUrl(cfg, idToken) : `${appOrigin(env)}/`; + return okResponse({ logoutUrl }); +} + +type DevVariant = "standard-free" | "standard-ink" | "admin-free" | "admin-ink"; + +// Local-dev sign-in without the identity service: mints a mirror-only user +// (id prefixed dev-) and a session. Doubly gated: DEV_QUICK_LOGIN must be +// "true" AND APP_ORIGIN must be a localhost origin, so a stray flag in +// production can never mint credential-free sessions. Standing checks skip +// the identity RPC for these users only under the same gate. +// +// Body: { variant } for a fresh dev user, or { email, name?, admin? } to sign +// in as (or create) a specific dev user - the e2e suites use the latter. +export async function handleDevQuickLogin(request: Request, env: AuthRouteEnv & { DEV_QUICK_LOGIN?: string }): Promise { + if (env.DEV_QUICK_LOGIN !== "true" || !isLocalDeploy(env)) return errorResponse(Errors.NOT_FOUND); + + const body = await request.json<{ variant?: DevVariant; email?: string; name?: string; admin?: boolean }>().catch(() => null); + if (!body) return errorResponse(Errors.BAD_REQUEST); + + let id: string; + let email: string; + let name: string; + let isAdmin: boolean; + let hasInk = false; + const now = Date.now(); + + if (typeof body.email === "string" && body.email.includes("@")) { + email = body.email.trim().toLowerCase(); + const existing = await env.DB.prepare("SELECT id, name, is_admin FROM users WHERE lower(email) = ? AND id LIKE 'dev-%'") + .bind(email).first<{ id: string; name: string; is_admin: number }>(); + id = existing?.id ?? `${DEV_USER_PREFIX}${crypto.randomUUID()}`; + name = typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing?.name ?? email.split("@")[0]; + isAdmin = typeof body.admin === "boolean" ? body.admin : Boolean(existing?.is_admin); + } else { + const variant = body.variant ?? "standard-free"; + isAdmin = variant === "admin-free" || variant === "admin-ink"; + hasInk = variant === "standard-ink" || variant === "admin-ink"; + id = `${DEV_USER_PREFIX}${crypto.randomUUID()}`; + email = `${id.slice(0, 12)}@localhost`; + name = `${isAdmin ? "Dev Admin" : "Dev User"}${hasInk ? " (Ink)" : ""}`; + } + + await refreshMirror(env.DB, { + id, email, name, emailVerified: true, isAdmin, status: "active", suspendedUntil: null, createdAt: new Date(now).toISOString(), + }, now, { login: true }); + if (hasInk) { + await env.DB.prepare( + "INSERT OR IGNORE INTO user_billing (user_id, granted_plan, granted_plan_reason, granted_plan_started_at) VALUES (?, 'ink', 'dev', ?)", + ).bind(id, now).run(); + } + const token = await createSessionToken(env, { userId: id, email, isAdmin, kind: "app", request }); + return okResponse({ token, userId: id }); +} diff --git a/packages/api/src/routes/members.ts b/packages/api/src/routes/members.ts index 0200866..3b0504e 100644 --- a/packages/api/src/routes/members.ts +++ b/packages/api/src/routes/members.ts @@ -2,7 +2,7 @@ import { okResponse, errorResponse, Errors, ROLE_RANK, type Role, type Member } import type { Env } from "../index"; import { resolveRole } from "../lib/access"; import type { Session } from "../lib"; -import { resolvePersonalPlan, type PersonalPlan } from "../../../auth/src/plan"; +import { resolvePersonalPlan, type PersonalPlan } from "../account/plan"; const VALID_ROLES: Role[] = ["limited", "viewer", "editor", "admin", "owner"]; diff --git a/packages/api/src/test/fakeIdp.ts b/packages/api/src/test/fakeIdp.ts new file mode 100644 index 0000000..c4492bd --- /dev/null +++ b/packages/api/src/test/fakeIdp.ts @@ -0,0 +1,157 @@ +// A minimal in-memory OpenID provider for tests, shaped like auth.cubityfir.st: +// discovery, JWKS, an authorize step (simulating the user signing in), a token +// endpoint that enforces client auth, redirect_uri and PKCE S256, and RS256 +// id_tokens. Plug `fetch` into the code under test. +import { b64url } from "../account/jwt"; + +export interface FakeUser { + sub: string; + email: string; + name: string; + emailVerified?: boolean; + roles?: string[]; +} + +interface CodeGrant { + user: FakeUser; + clientId: string; + redirectUri: string; + challenge: string; + nonce: string | null; + scope: string; +} + +export interface FakeIdp { + issuer: string; + fetch: typeof fetch; + // Simulates the browser at the authorization endpoint: validates the + // request like the real one would and returns the callback URL. + authorize(authorizeUrl: string, user: FakeUser): string; + // Knobs for negative tests. + tamper: { nonce?: string; signWithOtherKey?: boolean; aud?: string; iss?: string; expSec?: number }; + tokenRequests: number; +} + +const enc = new TextEncoder(); + +async function rsaKey(): Promise { + return crypto.subtle.generateKey( + { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + true, + ["sign", "verify"], + ) as Promise; +} + +async function sign(payload: Record, key: CryptoKey, kid: string): Promise { + const header = b64url(enc.encode(JSON.stringify({ alg: "RS256", typ: "JWT", kid }))); + const body = b64url(enc.encode(JSON.stringify(payload))); + const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, enc.encode(`${header}.${body}`)); + return `${header}.${body}.${b64url(sig)}`; +} + +async function s256(verifier: string): Promise { + return b64url(await crypto.subtle.digest("SHA-256", enc.encode(verifier))); +} + +export async function createFakeIdp(opts: { issuer?: string; clients: Record }): Promise { + const issuer = opts.issuer ?? "https://idp.test"; + const keys = await rsaKey(); + const otherKeys = await rsaKey(); + const kid = "test-key-1"; + const publicJwk = { ...(await crypto.subtle.exportKey("jwk", keys.publicKey)), kid, alg: "RS256", use: "sig" }; + const codes = new Map(); + + const idp: FakeIdp = { + issuer, + tamper: {}, + tokenRequests: 0, + authorize(authorizeUrl, user) { + const u = new URL(authorizeUrl); + if (`${u.origin}${u.pathname}` !== `${issuer}/oauth/authorize`) throw new Error(`unexpected authorize URL ${authorizeUrl}`); + const p = u.searchParams; + const client = opts.clients[p.get("client_id") ?? ""]; + const redirectUri = p.get("redirect_uri") ?? ""; + if (!client || !client.redirectUris.includes(redirectUri)) throw new Error("bad client/redirect"); + if (p.get("response_type") !== "code" || p.get("code_challenge_method") !== "S256" || !p.get("code_challenge")) { + throw new Error("bad authorize params"); + } + const code = crypto.randomUUID(); + codes.set(code, { + user, + clientId: p.get("client_id")!, + redirectUri, + challenge: p.get("code_challenge")!, + nonce: p.get("nonce"), + scope: p.get("scope") ?? "openid", + }); + const cb = new URL(redirectUri); + cb.searchParams.set("code", code); + if (p.get("state")) cb.searchParams.set("state", p.get("state")!); + cb.searchParams.set("iss", issuer); + return cb.toString(); + }, + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + const url = new URL(req.url); + if (url.pathname === "/.well-known/openid-configuration") { + return Response.json({ + issuer, + authorization_endpoint: `${issuer}/oauth/authorize`, + token_endpoint: `${issuer}/oauth/token`, + userinfo_endpoint: `${issuer}/oauth/userinfo`, + jwks_uri: `${issuer}/oauth/jwks`, + end_session_endpoint: `${issuer}/oauth/logout`, + response_types_supported: ["code"], + subject_types_supported: ["public"], + id_token_signing_alg_values_supported: ["RS256"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"], + authorization_response_iss_parameter_supported: true, + }); + } + if (url.pathname === "/oauth/jwks") return Response.json({ keys: [publicJwk] }); + if (url.pathname === "/oauth/token" && req.method === "POST") { + idp.tokenRequests++; + const form = new URLSearchParams(await req.text()); + let clientId = form.get("client_id") ?? ""; + let secret = form.get("client_secret") ?? undefined; + const basic = req.headers.get("Authorization"); + if (basic?.startsWith("Basic ")) { + const [id, s] = atob(basic.slice(6)).split(":").map(decodeURIComponent); + clientId = id; + secret = s; + } + const client = opts.clients[clientId]; + if (!client || (client.secret && client.secret !== secret)) return Response.json({ error: "invalid_client" }, { status: 401 }); + const grant = codes.get(form.get("code") ?? ""); + if (!grant || grant.clientId !== clientId || grant.redirectUri !== form.get("redirect_uri")) { + return Response.json({ error: "invalid_grant" }, { status: 400 }); + } + if ((await s256(form.get("code_verifier") ?? "")) !== grant.challenge) return Response.json({ error: "invalid_grant" }, { status: 400 }); + codes.delete(form.get("code")!); + const now = Math.floor(Date.now() / 1000); + const scopes = new Set(grant.scope.split(" ")); + const claims: Record = { + iss: idp.tamper.iss ?? issuer, + sub: grant.user.sub, + aud: idp.tamper.aud ?? clientId, + iat: now, + exp: idp.tamper.expSec ?? now + 3600, + auth_time: now, + sid: "idp-session-1", + ...(grant.nonce || idp.tamper.nonce ? { nonce: idp.tamper.nonce ?? grant.nonce } : {}), + ...(scopes.has("email") ? { email: grant.user.email, email_verified: grant.user.emailVerified ?? true } : {}), + ...(scopes.has("profile") ? { name: grant.user.name } : {}), + ...(scopes.has("roles") ? { roles: grant.user.roles ?? ["user"] } : {}), + }; + const idToken = await sign(claims, idp.tamper.signWithOtherKey ? otherKeys.privateKey : keys.privateKey, kid); + return Response.json( + { access_token: "at-" + crypto.randomUUID(), token_type: "Bearer", expires_in: 3600, id_token: idToken, scope: grant.scope }, + { headers: { "Cache-Control": "no-store" } }, + ); + } + return new Response("not found", { status: 404 }); + }) as typeof fetch, + }; + return idp; +} diff --git a/packages/api/src/test/session.ts b/packages/api/src/test/session.ts new file mode 100644 index 0000000..dce7497 --- /dev/null +++ b/packages/api/src/test/session.ts @@ -0,0 +1,23 @@ +// Test helper: seeds a users-mirror row + a live Annex session in a real +// SQLite main DB (see sqliteD1.ts) and returns a signed session token. +import type { DatabaseSync } from "node:sqlite"; +import { signJwt } from "../account/jwt"; + +export const TEST_JWT_SECRET = "test-secret"; + +export async function seedSession( + sqlite: DatabaseSync, + opts: { userId: string; email?: string; name?: string; isAdmin?: boolean; kind?: "app" | "admin"; sid?: string; secret?: string }, +): Promise { + const now = Date.now(); + const email = opts.email ?? `${opts.userId}@example.com`; + const sid = opts.sid ?? `s-${opts.userId}`; + sqlite.prepare( + `INSERT OR IGNORE INTO users (id, email, name, is_admin, created_at, first_seen_at, synced_at) + VALUES (?, ?, ?, ?, datetime('now'), ?, ?)`, + ).run(opts.userId, email, opts.name ?? opts.userId, opts.isAdmin ? 1 : 0, now, now); + sqlite.prepare( + "INSERT INTO sessions (id, user_id, kind, created_at, expires_at, last_used_at) VALUES (?, ?, ?, ?, ?, ?)", + ).run(sid, opts.userId, opts.kind ?? "app", now, now + 3_600_000, now); + return signJwt({ userId: opts.userId, email, expiresAt: now + 3_600_000, isAdmin: opts.isAdmin, sid }, opts.secret ?? TEST_JWT_SECRET); +} From 915c4aec5370117c0c786543acbed4a806437858 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:24:36 +0000 Subject: [PATCH 3/4] feat(api): serve Annex account data locally and drop AUTH_DB/AUTH Billing (Checkout, Customer Portal, Stripe webhook), the preference routes (ink prefs, fonts, theme, bio, handle, timezone), GET/PATCH /me and the profile card now run in the API worker against cubedocs-main. The frontend worker forwards /stripe/webhook to the API worker, so the URL in the Stripe dashboard is unchanged. Every AUTH_DB read and AUTH proxy is gone: invite-by-email asks the identity service (IdentityService.findUserByEmail) and mirrors the result; member plans, handles, reports, invite links, API-key owners and collab session re-checks read the users mirror; account standing comes from the identity service. Password, email, 2FA, passkey, session and account-deletion routes are removed (they live on auth.cubityfir.st), and PATCH /me refuses name changes. Server-side OIDC requests (discovery, JWKS, token) go through a new IDENTITY_OIDC service binding to cubityfirst-auth: a same-zone fetch() to auth.cubityfir.st would reach the origin, not the identity worker. Local dev falls back to the public issuer URL when the binding has no target. --- packages/api/cloudflare.config.ts | 39 +- packages/api/package.json | 1 + packages/api/src/account/badges.ts | 19 + packages/api/src/account/fonts.test.ts | 23 + packages/api/src/account/fonts.ts | 11 + packages/api/src/account/handle.test.ts | 35 ++ packages/api/src/account/handle.ts | 41 ++ packages/api/src/account/oidc.ts | 41 +- packages/api/src/account/plan.ts | 3 +- packages/api/src/account/requestSession.ts | 12 + packages/api/src/account/stripe-client.ts | 40 ++ packages/api/src/account/theme.test.ts | 41 ++ packages/api/src/account/theme.ts | 20 + packages/api/src/collab/DocCollabRoom.test.ts | 32 +- packages/api/src/collab/DocCollabRoom.ts | 61 +- packages/api/src/index.ts | 581 ++---------------- packages/api/src/lib.ts | 6 + packages/api/src/lib/apiKeys.test.ts | 26 +- packages/api/src/lib/apiKeys.ts | 20 +- packages/api/src/me.test.ts | 121 ++-- packages/api/src/routes/auth.test.ts | 50 +- packages/api/src/routes/auth.ts | 14 +- packages/api/src/routes/billing.test.ts | 107 ++++ packages/api/src/routes/billing.ts | 91 +++ packages/api/src/routes/inviteLinks.test.ts | 22 +- packages/api/src/routes/inviteLinks.ts | 13 +- packages/api/src/routes/me/me.ts | 157 +++++ packages/api/src/routes/me/update-bio.test.ts | 118 ++++ packages/api/src/routes/me/update-bio.ts | 69 +++ .../api/src/routes/me/update-handle.test.ts | 158 +++++ packages/api/src/routes/me/update-handle.ts | 85 +++ .../src/routes/me/update-ink-prefs.test.ts | 122 ++++ .../api/src/routes/me/update-ink-prefs.ts | 92 +++ .../src/routes/me/update-reading-font.test.ts | 119 ++++ .../api/src/routes/me/update-reading-font.ts | 64 ++ .../api/src/routes/me/update-theme.test.ts | 99 +++ packages/api/src/routes/me/update-theme.ts | 33 + packages/api/src/routes/members.test.ts | 18 +- packages/api/src/routes/members.ts | 28 +- packages/api/src/routes/organizations.test.ts | 23 +- packages/api/src/routes/organizations.ts | 38 +- packages/api/src/routes/projects.test.ts | 28 +- packages/api/src/routes/projects.ts | 14 +- packages/api/src/routes/reports.test.ts | 8 +- packages/api/src/routes/reports.ts | 4 +- packages/api/src/routes/stripeWebhook.test.ts | 392 ++++++++++++ packages/api/src/routes/stripeWebhook.ts | 293 +++++++++ packages/api/src/routes/userHandles.test.ts | 12 +- packages/api/src/routes/userHandles.ts | 6 +- packages/api/src/routes/v1.docs.test.ts | 10 +- packages/api/src/routes/v1.key.test.ts | 12 +- packages/api/src/routes/v1.ts | 20 +- packages/api/tsconfig.json | 2 +- packages/frontend/cloudflare.config.ts | 6 - packages/frontend/worker/index.ts | 12 +- pnpm-lock.yaml | 34 +- 56 files changed, 2673 insertions(+), 873 deletions(-) create mode 100644 packages/api/src/account/badges.ts create mode 100644 packages/api/src/account/fonts.test.ts create mode 100644 packages/api/src/account/fonts.ts create mode 100644 packages/api/src/account/handle.test.ts create mode 100644 packages/api/src/account/handle.ts create mode 100644 packages/api/src/account/requestSession.ts create mode 100644 packages/api/src/account/stripe-client.ts create mode 100644 packages/api/src/account/theme.test.ts create mode 100644 packages/api/src/account/theme.ts create mode 100644 packages/api/src/routes/billing.test.ts create mode 100644 packages/api/src/routes/billing.ts create mode 100644 packages/api/src/routes/me/me.ts create mode 100644 packages/api/src/routes/me/update-bio.test.ts create mode 100644 packages/api/src/routes/me/update-bio.ts create mode 100644 packages/api/src/routes/me/update-handle.test.ts create mode 100644 packages/api/src/routes/me/update-handle.ts create mode 100644 packages/api/src/routes/me/update-ink-prefs.test.ts create mode 100644 packages/api/src/routes/me/update-ink-prefs.ts create mode 100644 packages/api/src/routes/me/update-reading-font.test.ts create mode 100644 packages/api/src/routes/me/update-reading-font.ts create mode 100644 packages/api/src/routes/me/update-theme.test.ts create mode 100644 packages/api/src/routes/me/update-theme.ts create mode 100644 packages/api/src/routes/stripeWebhook.test.ts create mode 100644 packages/api/src/routes/stripeWebhook.ts diff --git a/packages/api/cloudflare.config.ts b/packages/api/cloudflare.config.ts index eba6f56..5fcf5f6 100644 --- a/packages/api/cloudflare.config.ts +++ b/packages/api/cloudflare.config.ts @@ -61,26 +61,30 @@ export default defineConfig({ OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), OIDC_CLIENT_ID: bindings.text("annex-docs"), APP_ORIGIN: bindings.text("https://docs.cubityfir.st"), + // Stripe price id for the Annex Ink supporter tier ($5/mo recurring). + // Not a secret - safe to commit. (Billing moved here from annex-auth.) + STRIPE_INK_PRICE_ID: bindings.text("price_1TVJk5Rckd4Ls9nPHpnY4tAN"), // Identity service RPC (cubityfirst-auth's IdentityService entrypoint): // account standing, invite-by-email lookups and the deletion sync. IDENTITY: bindings.worker({ worker: "cubityfirst-auth", exportName: "IdentityService", }), + // The identity worker's HTTP surface (default export) for server-side + // OIDC requests: discovery, JWKS and the token exchange. Required: a + // Worker's fetch() to auth.cubityfir.st from this same zone goes to the + // origin (a placeholder record), not to the identity worker. Only the + // browser redirects to /oauth/authorize and /oauth/logout use the + // public URL. Requests over a binding carry no CF-Connecting-IP, so all + // of Annex's token calls share one rate-limit bucket on the provider. + IDENTITY_OIDC: bindings.worker({ + worker: "cubityfirst-auth", + }), DB: bindings.d1({ name: "cubedocs-main", id: "267490be-7141-4d00-ab23-152742f2f6ef", }), - // Read-only access to the auth DB so this worker can verify sessions - // inline (one D1 batch read of users + sessions) instead of - // round-tripping through the auth worker's /verify route on every - // request. Migrations live with the auth worker - never apply - // migrations to cubedocs-auth from this package. - AUTH_DB: bindings.d1({ - name: "cubedocs-auth", - id: "db327d85-b8c2-4fed-adaa-25e748778c86", - }), - // Cloudflare Flagship feature flags. Shared app with the auth worker. + // Cloudflare Flagship feature flags. Shared with the admin worker. // Flags in use: // api (default on) - killswitch for the whole /v1 public API surface (v1.ts). // custom-theming (default off) - per-user gate for custom themes (index.ts). @@ -95,18 +99,13 @@ export default defineConfig({ ASSETS: bindings.r2({ name: "cubedocs-assets", }), - // Service binding to auth worker (zero-latency internal calls). - AUTH: bindings.worker({ - worker: "annex-auth", - }), DOC_COLLAB: bindings.durableObject({ worker: "annex-api", exportName: "DocCollabRoom", }), - // Per-user limiter for the invite-by-email lookup. The auth worker's - // /lookup also has its own coarser IP-keyed limiter - this one caps any - // single account from scraping the email→user map even when multiple - // users share an IP (office NAT). + // Per-user limiter for the invite-by-email lookup (routed to the + // identity service's findUserByEmail RPC): caps any single account from + // scraping the email→user map even when users share an IP (office NAT). RATE_LIMITER_INVITE_LOOKUP: bindings.rateLimit({ namespace: "2001", simple: { @@ -138,6 +137,10 @@ export default defineConfig({ // existing secrets are kept across `cf deploy`): // JWT_SECRET (signs Annex's own session JWTs; Annex-only) // OIDC_CLIENT_SECRET (the annex-docs client's secret from auth.cubityfir.st) + // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - moved from annex-auth) + // STRIPE_WEBHOOK_SECRET (whsec_... for the docs.cubityfir.st/stripe/webhook + // endpoint; the frontend worker forwards it here, so + // the URL in the Stripe dashboard is unchanged) // OPENAI_API_KEY (OpenAI API key for AI summarisation feature) // CF_API_TOKEN (Cloudflare token scoped to the zone with "SSL and // Certificates: Edit" - used to create/poll custom hostnames) diff --git a/packages/api/package.json b/packages/api/package.json index 6591951..ced23b1 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -17,6 +17,7 @@ "fflate": "^0.8.2", "lib0": "^0.2.0", "oauth4webapi": "3.8.8", + "stripe": "17.7.0", "y-protocols": "^1.0.6", "yjs": "^13.6.0" }, diff --git a/packages/api/src/account/badges.ts b/packages/api/src/account/badges.ts new file mode 100644 index 0000000..666eca1 --- /dev/null +++ b/packages/api/src/account/badges.ts @@ -0,0 +1,19 @@ +// Bitmask of per-user "badges" displayed on the profile card. Lives on the +// auth DB users table (column `badges`). Add a new badge by allocating the +// next free bit - no migration required. +// +// Pure module: imported by the api and admin workers via cross-package path +// the same way plan.ts is. + +export const BADGE_DEVELOPER = 1 << 0; +export const BADGE_BETA_TESTER = 1 << 1; + +export const ALL_BADGE_BITS = BADGE_DEVELOPER | BADGE_BETA_TESTER; + +export function hasBadge(bits: number, badge: number): boolean { + return (bits & badge) !== 0; +} + +export function setBadge(bits: number, badge: number, on: boolean): number { + return on ? bits | badge : bits & ~badge; +} diff --git a/packages/api/src/account/fonts.test.ts b/packages/api/src/account/fonts.test.ts new file mode 100644 index 0000000..557ee3e --- /dev/null +++ b/packages/api/src/account/fonts.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from "vitest"; +import { isFontChoice, FONT_CHOICES } from "./fonts"; + +describe("isFontChoice", () => { + it("accepts every value in FONT_CHOICES", () => { + for (const v of FONT_CHOICES) { + expect(isFontChoice(v)).toBe(true); + } + }); + + it("rejects unknown strings", () => { + expect(isFontChoice("comic-sans")).toBe(false); + expect(isFontChoice("")).toBe(false); + expect(isFontChoice("MONO")).toBe(false); + }); + + it("rejects non-strings", () => { + expect(isFontChoice(null)).toBe(false); + expect(isFontChoice(undefined)).toBe(false); + expect(isFontChoice(42)).toBe(false); + expect(isFontChoice({})).toBe(false); + }); +}); diff --git a/packages/api/src/account/fonts.ts b/packages/api/src/account/fonts.ts new file mode 100644 index 0000000..1eb358d --- /dev/null +++ b/packages/api/src/account/fonts.ts @@ -0,0 +1,11 @@ +// Allowed font-choice ids for the reading_font / editing_font columns on +// users. NULL on the row means "use the default" - the frontend treats +// missing values as the default sans stack. Adding a new choice: append +// the id here, add a CSS stack entry in packages/frontend/src/lib/fonts.ts, +// and add a row to the settings matrix in UserSettingsPage.tsx. +export const FONT_CHOICES = ["mono", "sans", "dyslexic"] as const; +export type FontChoice = typeof FONT_CHOICES[number]; + +export function isFontChoice(value: unknown): value is FontChoice { + return typeof value === "string" && (FONT_CHOICES as readonly string[]).includes(value); +} diff --git a/packages/api/src/account/handle.test.ts b/packages/api/src/account/handle.test.ts new file mode 100644 index 0000000..230deec --- /dev/null +++ b/packages/api/src/account/handle.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from "vitest"; +import { normalizeHandle, handleProblem, isValidHandle } from "./handle"; + +describe("normalizeHandle", () => { + it("trims, drops a single leading @ and lowercases", () => { + expect(normalizeHandle(" @Cubity_First ")).toBe("cubity_first"); + expect(normalizeHandle("@@x")).toBe("@x"); + }); +}); + +describe("handleProblem", () => { + it("accepts letters, digits, underscores and inner hyphens", () => { + for (const h of ["abc", "a-b_c", "user123", "9lives", "x".repeat(30)]) { + expect(handleProblem(h), h).toBeNull(); + } + }); + + it("enforces the 3-30 length window", () => { + expect(handleProblem("ab")).toBe("length"); + expect(handleProblem("x".repeat(31))).toBe("length"); + }); + + it("rejects disallowed characters and leading/trailing punctuation", () => { + for (const h of ["has space", "dot.ted", "Upper", "-lead", "trail_", "emoji😀x", "a/b", "..."]) { + expect(handleProblem(h), h).toBe("characters"); + } + }); + + it("rejects reserved names", () => { + expect(handleProblem("admin")).toBe("reserved"); + expect(handleProblem("support")).toBe("reserved"); + expect(isValidHandle("admin")).toBe(false); + expect(isValidHandle("admin2")).toBe(true); + }); +}); diff --git a/packages/api/src/account/handle.ts b/packages/api/src/account/handle.ts new file mode 100644 index 0000000..dac14fa --- /dev/null +++ b/packages/api/src/account/handle.ts @@ -0,0 +1,41 @@ +// Public profile handles (the `/@` link). Pure helpers shared by the +// auth worker's write path (routes/update-handle.ts) and the API worker's +// /users/by-handle resolver. Mirrored for client-side hints in +// packages/frontend/src/lib/handle.ts - keep the rules in sync; the server is +// authoritative. + +export const HANDLE_MIN_LENGTH = 3; +export const HANDLE_MAX_LENGTH = 30; + +// Lowercase letters, digits, `_` and `-`; must start and end with a letter or +// digit. No dots, so a handle can never be `.`/`..` or look like a file path. +const HANDLE_PATTERN = /^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/; + +// Names that would let someone impersonate staff or the product, or that read +// like app routes. Compared against the normalized handle. +const RESERVED_HANDLES = new Set([ + "admin", "administrator", "annex", "annexink", "api", "app", "auth", + "billing", "dashboard", "demo", "dev", "developer", "docs", "everyone", + "help", "here", "ink", "login", "logout", "me", "mod", "moderator", + "moderators", "null", "official", "oauth", "register", "root", "security", + "settings", "staff", "support", "system", "team", "undefined", "user", "users", +]); + +/** Trim, drop one leading `@`, lowercase. Does not validate. */ +export function normalizeHandle(input: string): string { + return input.trim().replace(/^@/, "").toLowerCase(); +} + +export type HandleProblem = "length" | "characters" | "reserved"; + +/** Validate an already-normalized handle. Returns null when it's acceptable. */ +export function handleProblem(handle: string): HandleProblem | null { + if (handle.length < HANDLE_MIN_LENGTH || handle.length > HANDLE_MAX_LENGTH) return "length"; + if (!HANDLE_PATTERN.test(handle)) return "characters"; + if (RESERVED_HANDLES.has(handle)) return "reserved"; + return null; +} + +export function isValidHandle(handle: string): boolean { + return handleProblem(handle) === null; +} diff --git a/packages/api/src/account/oidc.ts b/packages/api/src/account/oidc.ts index 596894c..82b2c1a 100644 --- a/packages/api/src/account/oidc.ts +++ b/packages/api/src/account/oidc.ts @@ -17,10 +17,45 @@ export interface OidcClientConfig { redirectUri: string; postLogoutRedirectUri: string; scope: string; - // Test hook: replaces fetch for discovery, token and JWKS requests. + // Service binding to the identity worker (cubityfirst-auth, default + // export). Every server-side request whose host is the issuer's host + // (discovery, JWKS, token) goes through it: Annex's workers share the + // cubityfir.st zone with auth.cubityfir.st, and a Worker's fetch() to + // another Worker's hostname on the same zone skips that Worker and hits + // the origin (a placeholder record), so a public fetch would fail in + // production. Only the browser redirects (authorize, logout) use the + // public URL. + binding?: { fetch(input: string, init?: RequestInit): Promise }; + // Local dev only: when the binding has no running target (no local + // `wrangler dev` of the identity worker), fall back to a direct fetch of + // the issuer URL. + allowPublicFallback?: boolean; + // Test hook: replaces the direct fetch (non-binding requests). fetchImpl?: typeof fetch; } +// Routes requests for the issuer's host through the service binding. +export function identityFetch(cfg: Pick): (url: string, init?: RequestInit) => Promise { + const direct = cfg.fetchImpl ?? ((u: string, i?: RequestInit) => fetch(u, i)); + const binding = cfg.binding; + if (!binding) return direct; + const issuerHost = new URL(cfg.issuer).host; + return async (url, init) => { + if (new URL(url).host !== issuerHost) return direct(url, init); + if (!cfg.allowPublicFallback) return binding.fetch(url, init); + // A request body can only be read once; keep a copy for the retry. + const body = typeof init?.body === "string" || init?.body instanceof URLSearchParams ? init.body : undefined; + try { + const res = await binding.fetch(url, init); + // wrangler dev answers a binding with no local target with a 503. + if (res.status !== 503) return res; + } catch { + // fall through to the direct fetch + } + return direct(url, { ...init, body }); + }; +} + export interface VerifiedIdentity { sub: string; email: string; @@ -53,8 +88,8 @@ function httpOptions(cfg: OidcClientConfig): oauth.HttpRequestOptions<"GET" | "P const opts: oauth.HttpRequestOptions<"GET" | "POST", unknown> = { signal: () => AbortSignal.timeout(10_000) }; // Local dev points at `wrangler dev` of the identity worker over http. if (new URL(cfg.issuer).protocol === "http:") opts[oauth.allowInsecureRequests] = true; - if (cfg.fetchImpl) { - const f = cfg.fetchImpl; + if (cfg.binding || cfg.fetchImpl) { + const f = identityFetch(cfg); opts[oauth.customFetch] = (url, init) => f(url, init as RequestInit); } return opts; diff --git a/packages/api/src/account/plan.ts b/packages/api/src/account/plan.ts index 3d81f2d..ffc3f41 100644 --- a/packages/api/src/account/plan.ts +++ b/packages/api/src/account/plan.ts @@ -7,8 +7,7 @@ // shows a banner but the perks stay on) // 3. free // -// Keep this a pure function so the api worker can import it via the -// same cross-package path it already uses for loadCurrentSession. +// Keep this a pure function: the admin worker imports it cross-package. export type PersonalPlan = "free" | "ink"; diff --git a/packages/api/src/account/requestSession.ts b/packages/api/src/account/requestSession.ts new file mode 100644 index 0000000..fcc6577 --- /dev/null +++ b/packages/api/src/account/requestSession.ts @@ -0,0 +1,12 @@ +import { errorResponse, Errors, type Session } from "../lib"; +import { authenticate } from "../auth"; +import type { Env } from "../index"; + +// The per-route session check the account routes (routes/me/*) were written +// against in the old auth worker: an authenticated docs-app session, or the +// Response to return (401, or 403 for a disabled/suspended/blocked account). +export async function requireAuthenticatedSession(request: Request, env: Env): Promise { + const result = await authenticate(request, env); + if (result === null) return errorResponse(Errors.UNAUTHORIZED); + return result; +} diff --git a/packages/api/src/account/stripe-client.ts b/packages/api/src/account/stripe-client.ts new file mode 100644 index 0000000..3b58fae --- /dev/null +++ b/packages/api/src/account/stripe-client.ts @@ -0,0 +1,40 @@ +import Stripe from "stripe"; +export interface StripeEnv { + DB: D1Database; + STRIPE_SECRET_KEY?: string; +} + +// Stripe SDK initialized for the Workers runtime. The default Node http +// client + crypto won't work even with nodejs_compat - we have to plug +// in fetch and SubtleCrypto explicitly. +let cached: Stripe | null = null; +let cachedKey: string | null = null; + +export function getStripe(secretKey: string): Stripe { + if (cached && cachedKey === secretKey) return cached; + cached = new Stripe(secretKey, { + httpClient: Stripe.createFetchHttpClient(), + }); + cachedKey = secretKey; + return cached; +} + +export function getStripeWebhookCryptoProvider(): Stripe.CryptoProvider { + return Stripe.createSubtleCryptoProvider(); +} + +// Best-effort: keep the Stripe customer's email in sync when the account email +// changes, so receipts/dunning mail follows the user. stripe_customer_id is the +// durable link - a failure here never blocks the email change itself. +export async function syncStripeCustomerEmail(env: StripeEnv, userId: string, newEmail: string): Promise { + if (!env.STRIPE_SECRET_KEY) return; + try { + const row = await env.DB.prepare( + "SELECT stripe_customer_id FROM user_billing WHERE user_id = ?", + ).bind(userId).first<{ stripe_customer_id: string | null }>(); + if (!row?.stripe_customer_id) return; + await getStripe(env.STRIPE_SECRET_KEY).customers.update(row.stripe_customer_id, { email: newEmail }); + } catch (err) { + console.error("syncStripeCustomerEmail failed", { userId, err }); + } +} diff --git a/packages/api/src/account/theme.test.ts b/packages/api/src/account/theme.test.ts new file mode 100644 index 0000000..3cd68e6 --- /dev/null +++ b/packages/api/src/account/theme.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from "vitest"; +import { isThemeMode, isHexColor, THEME_MODES } from "./theme"; + +describe("isThemeMode", () => { + it("accepts every value in THEME_MODES", () => { + for (const v of THEME_MODES) expect(isThemeMode(v)).toBe(true); + }); + + it("rejects unknown / wrong-case strings", () => { + expect(isThemeMode("solarized")).toBe(false); + expect(isThemeMode("")).toBe(false); + expect(isThemeMode("DARK")).toBe(false); + }); + + it("rejects non-strings", () => { + expect(isThemeMode(null)).toBe(false); + expect(isThemeMode(undefined)).toBe(false); + expect(isThemeMode(1)).toBe(false); + expect(isThemeMode({})).toBe(false); + }); +}); + +describe("isHexColor", () => { + it("accepts #rrggbb in either case", () => { + expect(isHexColor("#2e7d6b")).toBe(true); + expect(isHexColor("#ABCDEF")).toBe(true); + }); + + it("rejects short form, missing hash, bad digits", () => { + expect(isHexColor("#abc")).toBe(false); + expect(isHexColor("2e7d6b")).toBe(false); + expect(isHexColor("#2e7d6g")).toBe(false); + expect(isHexColor("#2e7d6b ")).toBe(false); + }); + + it("rejects non-strings", () => { + expect(isHexColor(null)).toBe(false); + expect(isHexColor(undefined)).toBe(false); + expect(isHexColor(0xffffff)).toBe(false); + }); +}); diff --git a/packages/api/src/account/theme.ts b/packages/api/src/account/theme.ts new file mode 100644 index 0000000..67ad61c --- /dev/null +++ b/packages/api/src/account/theme.ts @@ -0,0 +1,20 @@ +// Allowed theme modes for the theme_mode column on user_preferences. NULL on +// the row means "use the default" (dark) - the frontend treats a missing / +// unknown value as dark. 'custom' additionally stores a #rrggbb base in +// theme_custom_color, from which the frontend derives the full palette. +// +// Setting the theme is gated (admins, or the custom-theming flag) in the +// PATCH /me/theme route in src/index.ts. Keep this list in sync with +// THEME_MODES in packages/frontend/src/lib/theme.ts. +export const THEME_MODES = ["dark", "light", "custom"] as const; +export type ThemeMode = typeof THEME_MODES[number]; + +export function isThemeMode(value: unknown): value is ThemeMode { + return typeof value === "string" && (THEME_MODES as readonly string[]).includes(value); +} + +const HEX_RE = /^#[0-9a-fA-F]{6}$/; + +export function isHexColor(value: unknown): value is string { + return typeof value === "string" && HEX_RE.test(value); +} diff --git a/packages/api/src/collab/DocCollabRoom.test.ts b/packages/api/src/collab/DocCollabRoom.test.ts index a230509..525cdef 100644 --- a/packages/api/src/collab/DocCollabRoom.test.ts +++ b/packages/api/src/collab/DocCollabRoom.test.ts @@ -44,14 +44,23 @@ function fakeWs(userId: string, sid?: string): FakeWs { return ws; } -function makeRoom(sockets: FakeWs[], db: D1Database, authDb?: D1Database): { revalidateAccess(): Promise> } { +// Session rows live in the same DB as roles now; route the session re-check +// query to `sessionsDb` and everything else to the roles stub. +function withSessions(db: D1Database, sessionsDb?: D1Database): D1Database { + if (!sessionsDb) return db; + return { + prepare: (sql: string) => (/FROM sessions/.test(sql) ? sessionsDb.prepare(sql) : db.prepare(sql)), + } as unknown as D1Database; +} + +function makeRoom(sockets: FakeWs[], db: D1Database, sessionsDb?: D1Database): { revalidateAccess(): Promise> } { const ctx = { getWebSockets: () => sockets, storage: { get: async (k: string) => (k === "docKey" ? "proj-1/doc-1" : undefined) }, }; const room = new DocCollabRoom( ctx as unknown as ConstructorParameters[0], - { DB: db, AUTH_DB: authDb } as unknown as ConstructorParameters[1], + { DB: withSessions(db, sessionsDb) } as unknown as ConstructorParameters[1], ); return room as unknown as { revalidateAccess(): Promise> }; } @@ -126,7 +135,7 @@ describe("DocCollabRoom.revalidateAccess (closes sockets that lost editor+)", () }); }); -// AUTH_DB stub for the session re-check: sessions[sid] is the joined row, or +// Session re-check stub: sessions[sid] is the joined session + users row, or // undefined (no row) / "throw". function authDbFor(sessions: Record[0] | "throw">) { return { @@ -142,7 +151,11 @@ function authDbFor(sessions: Record } as unknown as D1Database; } -const live = { expires_at: Date.now() + 60_000, revoked_at: null, moderation: 0, force_password_change: 0 }; +const live = { + expires_at: Date.now() + 60_000, revoked_at: null, kind: "app", blocked: 0, + id: "u", email: "u@example.com", name: "U", email_verified: 1, is_admin: 0, + status: "active", suspended_until: null, created_at: "2025-01-01", +}; describe("DocCollabRoom.revalidateAccess (session + account re-check)", () => { it("closes only the socket whose session was revoked; the user's other session stays", async () => { @@ -169,7 +182,7 @@ describe("DocCollabRoom.revalidateAccess (session + account re-check)", () => { a: { project: "editor", org: null }, b: { project: "editor", org: null }, c: { project: "editor", org: null }, }); const room = makeRoom([suspended, expired, missing], db, authDbFor({ - s1: { ...live, moderation: Math.floor(Date.now() / 1000) + 3600 }, + s1: { ...live, status: "suspended", suspended_until: Math.floor(Date.now() / 1000) + 3600 }, s2: { ...live, expires_at: Date.now() - 1 }, })); @@ -179,7 +192,7 @@ describe("DocCollabRoom.revalidateAccess (session + account re-check)", () => { expect(missing.closedWith?.code).toBe(1008); }); - it("fails open on an AUTH_DB error and skips sockets without a sid", async () => { + it("fails open on a session lookup error and skips sockets without a sid", async () => { const errored = fakeWs("a", "s1"); const legacy = fakeWs("b"); const { db } = dbForRoles({ a: { project: "editor", org: null }, b: { project: "editor", org: null } }); @@ -197,9 +210,10 @@ describe("sessionStillValid", () => { it("mirrors loadCurrentSession's gates", () => { expect(sessionStillValid(live, now)).toBe(true); expect(sessionStillValid(null, now)).toBe(false); - expect(sessionStillValid({ ...live, force_password_change: 1 }, now)).toBe(false); - expect(sessionStillValid({ ...live, moderation: -1 }, now)).toBe(false); + expect(sessionStillValid({ ...live, status: "disabled" }, now)).toBe(false); + expect(sessionStillValid({ ...live, blocked: 1 }, now)).toBe(false); + expect(sessionStillValid({ ...live, kind: "admin" }, now)).toBe(false); // An elapsed suspension no longer blocks. - expect(sessionStillValid({ ...live, moderation: Math.floor(now / 1000) - 10 }, now)).toBe(true); + expect(sessionStillValid({ ...live, status: "suspended", suspended_until: Math.floor(now / 1000) - 10 }, now)).toBe(true); }); }); diff --git a/packages/api/src/collab/DocCollabRoom.ts b/packages/api/src/collab/DocCollabRoom.ts index dd30e88..567aa52 100644 --- a/packages/api/src/collab/DocCollabRoom.ts +++ b/packages/api/src/collab/DocCollabRoom.ts @@ -7,6 +7,7 @@ import type { Env } from "../index"; import { ROLE_RANK } from "../lib"; import { resolveAccess } from "../lib/access"; import { latestDocRevisionContent, snapshotDocRevision } from "../lib/docOps"; +import { accountStanding, standingFromMirror, type MirrorUser } from "../account/identity"; const MSG_SYNC = 0; const MSG_AWARENESS = 1; @@ -338,24 +339,29 @@ export class DocCollabRoom implements DurableObject { if (uids.size === 0) return revoked; // The socket was authenticated once, at upgrade. Re-check the session row - // and account state too, so "revoke other sessions", a password change, - // session expiry, or an admin disable/suspend closes it - membership alone - // wouldn't. Same fail-open rule on a lookup error. + // and account standing too, so a sign-out, session expiry, a pending admin + // deletion, or a disable/suspend on the identity service closes it - + // membership alone wouldn't. Same fail-open rule on a lookup error. const sessionOkById = new Map(); - const authDb = this.env.AUTH_DB; - if (authDb) { - await Promise.all([...sids].map(async (sid) => { - try { - const row = await authDb.prepare( - `SELECT s.expires_at, s.revoked_at, u.moderation, u.force_password_change - FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.id = ?`, - ).bind(sid).first<{ expires_at: number; revoked_at: number | null; moderation: number; force_password_change: number }>(); - sessionOkById.set(sid, sessionStillValid(row, now)); - } catch { - sessionOkById.set(sid, true); - } - })); - } + await Promise.all([...sids].map(async (sid) => { + try { + const row = await this.env.DB.prepare( + `SELECT s.expires_at, s.revoked_at, s.kind, (d.user_id IS NOT NULL) AS blocked, + u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at + FROM sessions s + JOIN users u ON u.id = s.user_id + LEFT JOIN user_deletions d ON d.user_id = u.id + WHERE s.id = ?`, + ).bind(sid).first(); + let ok = sessionStillValid(row, now); + // Live standing from the identity service (cached ~60s per isolate, + // falls back to the mirror when the service can't be reached). + if (ok && row) ok = (await accountStanding(this.env, row, now)).ok; + sessionOkById.set(sid, ok); + } catch { + sessionOkById.set(sid, true); + } + })); const allowedById = new Map(); await Promise.all([...uids].map(async (uid) => { try { @@ -666,17 +672,24 @@ function safeDecode(v: string): string { try { return decodeURIComponent(v); } catch { return v; } } -// Mirrors loadCurrentSession's session/account gates (revoked, expired, -// force-password-change, disabled, suspended). A missing row = invalid. +export interface SessionCheckRow extends MirrorUser { + expires_at: number; + revoked_at: number | null; + kind: string; + blocked: number; +} + +// Mirrors loadCurrentSession's session gates (revoked, expired, wrong kind, +// blocked by a pending admin deletion) plus the mirror's last known standing. +// A missing row = invalid. export function sessionStillValid( - row: { expires_at: number; revoked_at: number | null; moderation: number; force_password_change: number } | null, + row: Pick | null, now: number, ): boolean { if (!row) return false; if (row.revoked_at !== null) return false; if (row.expires_at <= now) return false; - if (row.force_password_change) return false; - if (row.moderation === -1) return false; - if (row.moderation > 0 && Math.floor(now / 1000) < row.moderation) return false; - return true; + if (row.kind !== "app") return false; + if (row.blocked) return false; + return standingFromMirror(row, now).ok; } diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index f77faee..c190ad1 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -19,25 +19,29 @@ import { handleApiKeys } from "./routes/apiKeys"; import { handleOrganizations } from "./routes/organizations"; import { handleCustomDomain } from "./routes/customDomains"; import { handleTrash } from "./routes/trash"; -import { cleanupDeletedAccount } from "./lib/projectDelete"; import { handleUserByHandle } from "./routes/userHandles"; import { pruneDocRevisions } from "./lib/docOps"; import { purgeExpiredTrash } from "./lib/trash"; import { DocCollabRoom } from "./collab/DocCollabRoom"; -import { resolvePersonalPlan } from "./account/plan"; import { resolveAvatar, parseVariant, avatarKey, deleteAllAvatarVariants } from "./avatar"; import { resolveAccess } from "./lib/access"; import type { IdentityService } from "./account/identity"; import { sweepSessions } from "./account/session"; import { handleAuthCallback, handleAuthExchange, handleAuthLogin, handleAuthLogout, handleDevQuickLogin } from "./routes/auth"; +import { handleBillingCheckout, handleBillingPortal } from "./routes/billing"; +import { handleStripeWebhook } from "./routes/stripeWebhook"; +import { handleGetMe, handlePatchMe, handleUserProfile } from "./routes/me/me"; +import { handleUpdateInkPrefs } from "./routes/me/update-ink-prefs"; +import { handleUpdateReadingFont } from "./routes/me/update-reading-font"; +import { handleUpdateTheme } from "./routes/me/update-theme"; +import { handleUpdateBio } from "./routes/me/update-bio"; +import { handleUpdateHandle } from "./routes/me/update-handle"; export { DocCollabRoom }; export interface Env { DB: D1Database; - AUTH_DB: D1Database; // Read-only: users + sessions, used for inline JWT verify ASSETS: R2Bucket; - AUTH: Fetcher; // Service binding to cubedocs-auth (mutating routes only) DOC_COLLAB?: DurableObjectNamespace; // Annex-only HS256 secret for Annex's own session JWTs (no longer shared // with the identity service). @@ -46,6 +50,10 @@ export interface Env { // deletions. Optional so unit tests and a local stack without the identity // worker fall back to the users mirror. IDENTITY?: IdentityService; + // The identity worker's HTTP surface (cubityfirst-auth default export) for + // server-side OIDC requests. Required in production: a fetch() to + // auth.cubityfir.st from a Worker on the same zone never reaches it. + IDENTITY_OIDC?: Fetcher; // OIDC client settings (see routes/auth.ts). OIDC_CLIENT_SECRET is a secret; // the rest are vars. Redirect URIs default to APP_ORIGIN/api/auth/callback // and APP_ORIGIN/. @@ -57,6 +65,11 @@ export interface Env { APP_ORIGIN?: string; // "true" (with a localhost APP_ORIGIN) enables POST /dev/quick-login. DEV_QUICK_LOGIN?: string; + // Annex Ink billing (routes/billing.ts, routes/stripeWebhook.ts). The keys + // are secrets; STRIPE_INK_PRICE_ID is a var. + STRIPE_SECRET_KEY?: string; + STRIPE_WEBHOOK_SECRET?: string; + STRIPE_INK_PRICE_ID?: string; OPENAI_API_KEY?: string; // Cloudflare-for-SaaS custom domains (see routes/customDomains.ts). Optional: // when unset, the custom-domain endpoints report "not configured" instead of @@ -141,378 +154,58 @@ export default { if (url.pathname === "/auth/logout" && request.method === "POST") return addCorsHeaders(await handleAuthLogout(request, env)); if (url.pathname === "/dev/quick-login" && request.method === "POST") return addCorsHeaders(await handleDevQuickLogin(request, env)); - // Proxy auth routes to the auth worker - if ( - url.pathname === "/register" || - url.pathname === "/login" || - url.pathname === "/force-change-password" || - url.pathname === "/verify-email/resend" || - url.pathname === "/admin/handoff/start" || - url.pathname === "/oauth/authorize" - ) { - return env.AUTH.fetch(`https://auth${url.pathname}`, await proxyAuthInit(request)); + // Stripe webhook - public, signature-verified (routes/stripeWebhook.ts). + // The frontend worker forwards docs.cubityfir.st/stripe/webhook here + // verbatim; the raw body must reach the handler untouched. + if (url.pathname === "/stripe/webhook" && request.method === "POST") { + return await handleStripeWebhook(request, env); } - // /verify-email - public like the passthrough list above, but the - // response is inspected: a change-confirm token applies a new email - // inside the auth worker, and the denormalized member-row snapshots in - // THIS worker's DB must be synced at that exact apply event. - if (url.pathname === "/verify-email") { - const authRes = await env.AUTH.fetch("https://auth/verify-email", await proxyAuthInit(request)); - const json = await authRes.clone().json<{ ok?: boolean; data?: { emailChanged?: boolean; userId?: string; email?: string } }>().catch(() => null); - if (json?.ok && json.data?.emailChanged && json.data.userId && json.data.email) { - await syncMemberEmails(env, json.data.userId, json.data.email); - } - return addCorsHeaders(authRes); - } - - // TOTP management routes - authenticated, proxied to auth worker with userId injected - if (url.pathname.startsWith("/me/totp")) { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const totpPath = url.pathname.replace("/me/totp", "/totp"); - const body = request.method !== "GET" ? await request.json>() : {}; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch(`https://auth${totpPath}`, { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(authRes); - } - - // WebAuthn management routes - authenticated, proxied to auth worker with userId injected - if (url.pathname.startsWith("/me/webauthn")) { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const webauthnPath = url.pathname.replace("/me/webauthn", "/webauthn"); - const body = await request.json>(); - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch(`https://auth${webauthnPath}`, { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ ...body, userId: session.userId }), - }); - return addCorsHeaders(authRes); - } - - // WebAuthn login ceremony - unauthenticated, forwarded directly - if (url.pathname.startsWith("/webauthn/auth")) { - return addCorsHeaders( - await env.AUTH.fetch(`https://auth${url.pathname}`, await proxyAuthInit(request)), - ); - } - - // /me/sessions/* - authenticated, proxied to auth worker. - // GET /me/sessions → list user's active sessions - // POST /me/sessions/revoke → revoke a specific session by id - // POST /me/sessions/revoke-others → revoke all but the current - // POST /me/sessions/logout → revoke the current session (proper logout) - if (url.pathname === "/me/sessions" && request.method === "GET") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/sessions/list", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: "{}", - }); - return addCorsHeaders(authRes); - } - if (url.pathname === "/me/sessions/revoke" && request.method === "POST") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json>(); - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/sessions/revoke", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(authRes); - } - if (url.pathname === "/me/sessions/revoke-others" && request.method === "POST") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/sessions/revoke-others", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: "{}", - }); - return addCorsHeaders(authRes); - } - if (url.pathname === "/me/sessions/logout" && request.method === "POST") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/sessions/logout", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: "{}", - }); - return addCorsHeaders(authRes); - } - - // /billing/* - authenticated, proxied to auth worker (Stripe Checkout - // and Customer Portal session creation). Public Stripe webhook is - // hit directly on the auth worker, not through here. + // /billing/* - Stripe Checkout and Customer Portal sessions. if (url.pathname === "/billing/checkout" && request.method === "POST") { const session = await getSession(request, env); if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/billing/checkout", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: "{}", - }); - return addCorsHeaders(authRes); + return addCorsHeaders(await handleBillingCheckout(env, session)); } if (url.pathname === "/billing/portal" && request.method === "POST") { const session = await getSession(request, env); if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/billing/portal", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: "{}", - }); - return addCorsHeaders(authRes); - } - - // PATCH /me/password - change password - if (url.pathname === "/me/password" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json>(); - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/change-password", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(authRes); - } - - // PATCH /me/email - change account email (password + MFA gated in the - // auth worker). When the change applies immediately (verification flag - // off), sync the denormalized member-row snapshots in this worker's DB. - if (url.pathname === "/me/email" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json>(); - const authHeader = request.headers.get("Authorization"); - // /change-email is IP-rate-limited in the auth worker; the service - // binding drops CF-Connecting-IP, so re-forward the edge-observed IP - // as X-Client-IP or every user shares one "unknown" bucket. - const ip = request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"); - const authRes = await env.AUTH.fetch("https://auth/change-email", { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(authHeader ? { Authorization: authHeader } : {}), - ...(ip ? { "X-Client-IP": ip } : {}), - }, - body: JSON.stringify(body), - }); - const json = await authRes.clone().json<{ ok?: boolean; data?: { applied?: boolean; email?: string } }>().catch(() => null); - if (json?.ok && json.data?.applied && json.data.email) { - await syncMemberEmails(env, session.userId, json.data.email); - } - return addCorsHeaders(authRes); - } - - // POST /me/email/resend | /me/email/cancel - manage a pending - // confirm-first email change. - if ((url.pathname === "/me/email/resend" || url.pathname === "/me/email/cancel") && request.method === "POST") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const authPath = url.pathname === "/me/email/resend" ? "/change-email/resend" : "/change-email/cancel"; - // Resend is IP-rate-limited in the auth worker - forward the client IP - // (see the /me/email comment above). - const ip = request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"); - const authRes = await env.AUTH.fetch(`https://auth${authPath}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(authHeader ? { Authorization: authHeader } : {}), - ...(ip ? { "X-Client-IP": ip } : {}), - }, - body: "{}", - }); - return addCorsHeaders(authRes); + return addCorsHeaders(await handleBillingPortal(env, session)); } - // GET /me - returns authenticated user's name and email + // GET /me - the signed-in user: identity facts from the users mirror, + // Annex prefs/plan from the session (routes/me/me.ts). if (url.pathname === "/me" && request.method === "GET") { const session = await getSession(request, env); if (session instanceof Response) return session; - const authHeader = request.headers.get("Authorization"); - const [lookupRes, customThemingEnabled] = await Promise.all([ - env.AUTH.fetch("https://auth/lookup-by-id", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ userId: session.userId }), - }), - env.FLAGS - ? env.FLAGS.getBooleanValue("custom-theming", false, { userId: session.userId }) - : Promise.resolve(true), - ]); - if (!lookupRes.ok) return addCorsHeaders(errorResponse(Errors.INTERNAL)); - const data = await lookupRes.json<{ ok: boolean; data?: { name: string; email: string; emailVerified: boolean; emailVerificationEnabled: boolean; pendingEmail: string | null; timezone: string | null; bio: string | null; handle?: string | null; handleLocked?: boolean } }>(); - if (!data.ok || !data.data) return addCorsHeaders(errorResponse(Errors.INTERNAL)); - return addCorsHeaders(Response.json({ - ok: true, - data: { - name: data.data.name, - email: data.data.email, - emailVerified: data.data.emailVerified, - emailVerificationEnabled: data.data.emailVerificationEnabled, - pendingEmail: data.data.pendingEmail ?? null, - userId: session.userId, - timezone: data.data.timezone, - bio: data.data.bio, - handle: data.data.handle ?? null, - handleLocked: data.data.handleLocked ?? false, - personalPlan: session.personalPlan ?? "free", - personalPlanSince: session.personalPlanSince ?? null, - personalPlanStatus: session.personalPlanStatus ?? null, - personalPlanCancelAt: session.personalPlanCancelAt ?? null, - personalPlanStyle: session.personalPlanStyle ?? null, - personalPresenceColor: session.personalPresenceColor ?? null, - personalCritSparkles: session.personalCritSparkles ?? true, - readingFont: session.readingFont ?? null, - editingFont: session.editingFont ?? null, - uiFont: session.uiFont ?? null, - isAdmin: session.isAdmin ?? false, - themeMode: session.themeMode ?? null, - themeCustomColor: session.themeCustomColor ?? null, - customThemingEnabled, - }, - })); + return addCorsHeaders(await handleGetMe(env, session)); } - // PATCH /me - update authenticated user's name and/or timezone + // PATCH /me - timezone. The name is managed on auth.cubityfir.st. if (url.pathname === "/me" && request.method === "PATCH") { const session = await getSession(request, env); if (session instanceof Response) return session; - const body = await request.json<{ name?: string; timezone?: string | null }>(); - const authHeader = request.headers.get("Authorization"); - const responseData: { name?: string; timezone?: string | null } = {}; - - if (body.name !== undefined) { - if (!body.name?.trim()) return addCorsHeaders(errorResponse(Errors.BAD_REQUEST)); - const updateRes = await env.AUTH.fetch("https://auth/update-name", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ name: body.name.trim() }), - }); - if (!updateRes.ok) return addCorsHeaders(errorResponse(Errors.INTERNAL)); - const trimmedName = body.name.trim(); - // Keep the denormalized site- and org-membership name snapshots in - // sync; the <> guard skips rows that already match. - await env.DB.batch([ - env.DB.prepare("UPDATE project_members SET name = ? WHERE user_id = ? AND name <> ?") - .bind(trimmedName, session.userId, trimmedName), - env.DB.prepare("UPDATE organization_members SET name = ? WHERE user_id = ? AND name <> ?") - .bind(trimmedName, session.userId, trimmedName), - ]); - responseData.name = trimmedName; - } - - if ("timezone" in body) { - const updateRes = await env.AUTH.fetch("https://auth/update-timezone", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ timezone: body.timezone ?? null }), - }); - if (!updateRes.ok) return addCorsHeaders(updateRes.status === 400 ? errorResponse(Errors.BAD_REQUEST) : errorResponse(Errors.INTERNAL)); - responseData.timezone = body.timezone ?? null; - } - - if (!responseData.name && !("timezone" in body)) return addCorsHeaders(errorResponse(Errors.BAD_REQUEST)); - return addCorsHeaders(Response.json({ ok: true, data: responseData })); - } - - // PATCH /me/ink-prefs - update Ink supporter cosmetic prefs (ring style + presence colour) - if (url.pathname === "/me/ink-prefs" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json(); - const authHeader = request.headers.get("Authorization"); - const updateRes = await env.AUTH.fetch("https://auth/update-ink-prefs", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(updateRes); - } - - // PATCH /me/reading-font - update user's reading/editing prose-font choices - if (url.pathname === "/me/reading-font" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json(); - const authHeader = request.headers.get("Authorization"); - const updateRes = await env.AUTH.fetch("https://auth/update-reading-font", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(updateRes); - } - - // PATCH /me/theme - set site theme (dark/light/custom). Admins always - // have access; other users require the custom-theming Flagship flag. - if (url.pathname === "/me/theme" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - if (!session.isAdmin) { - const flagEnabled = env.FLAGS - ? await env.FLAGS.getBooleanValue("custom-theming", false, { userId: session.userId }) - : true; - if (!flagEnabled) return addCorsHeaders(errorResponse(Errors.FORBIDDEN)); + return addCorsHeaders(await handlePatchMe(request, env, session)); + } + + // Annex preferences (routes/me/*). Each handler authenticates itself. + if (request.method === "PATCH") { + if (url.pathname === "/me/ink-prefs") return addCorsHeaders(await handleUpdateInkPrefs(request, env)); + if (url.pathname === "/me/reading-font") return addCorsHeaders(await handleUpdateReadingFont(request, env)); + if (url.pathname === "/me/bio") return addCorsHeaders(await handleUpdateBio(request, env)); + if (url.pathname === "/me/handle") return addCorsHeaders(await handleUpdateHandle(request, env)); + // Site theme: admins always; other users need the custom-theming flag. + if (url.pathname === "/me/theme") { + const session = await getSession(request, env); + if (session instanceof Response) return session; + if (!session.isAdmin) { + const flagEnabled = env.FLAGS + ? await env.FLAGS.getBooleanValue("custom-theming", false, { userId: session.userId }) + : true; + if (!flagEnabled) return addCorsHeaders(errorResponse(Errors.FORBIDDEN)); + } + return addCorsHeaders(await handleUpdateTheme(request, env)); } - const body = await request.json(); - const authHeader = request.headers.get("Authorization"); - const updateRes = await env.AUTH.fetch("https://auth/update-theme", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(updateRes); - } - - // PATCH /me/bio - Ink-only supporter bio. Proxied so the auth worker - // can plan-gate against the live row (avoids JWT-staleness writes). - if (url.pathname === "/me/bio" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json(); - const authHeader = request.headers.get("Authorization"); - const updateRes = await env.AUTH.fetch("https://auth/update-bio", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(updateRes); - } - - // PATCH /me/handle - set or clear the opt-in public profile handle (the - // /@ link). The auth worker validates + enforces uniqueness - // (409 when taken). - if (url.pathname === "/me/handle" && request.method === "PATCH") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - const body = await request.json(); - const authHeader = request.headers.get("Authorization"); - const updateRes = await env.AUTH.fetch("https://auth/update-handle", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - return addCorsHeaders(updateRes); } // GET /me/favourite-sites/search?q= - find published sites by name for @@ -685,47 +378,6 @@ export default { return addCorsHeaders(Response.json({ ok: true })); } - // DELETE /me - delete the authenticated user's account - if (url.pathname === "/me" && request.method === "DELETE") { - const session = await getSession(request, env); - if (session instanceof Response) return session; - - const ownedCount = await env.DB.prepare( - "SELECT COUNT(*) as count FROM projects WHERE owner_id = ?", - ).bind(session.userId).first<{ count: number }>(); - if (ownedCount && ownedCount.count > 0) { - return addCorsHeaders(Response.json({ ok: false, error: "owns_projects" }, { status: 400 })); - } - - // Same guard for organizations: an owned org has no transfer path and - // its owner row can't be removed/re-roled, so deleting the account would - // orphan it. Force the user to delete/hand off owned orgs first. - const ownedOrgCount = await env.DB.prepare( - "SELECT COUNT(*) as count FROM organizations WHERE owner_id = ?", - ).bind(session.userId).first<{ count: number }>(); - if (ownedOrgCount && ownedOrgCount.count > 0) { - return addCorsHeaders(Response.json({ ok: false, error: "owns_organizations" }, { status: 400 })); - } - - const body = await request.json>(); - const authHeader = request.headers.get("Authorization"); - const authRes = await env.AUTH.fetch("https://auth/delete-account", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify(body), - }); - const authJson = await authRes.json<{ ok: boolean; error?: string }>(); - if (!authJson.ok) return addCorsHeaders(Response.json(authJson, { status: authRes.status })); - - // The account is gone: delete any owned site in full (same cleanup as - // DELETE /projects/:id - R2, revisions, FTS, custom domain), then the - // remaining memberships and the avatar. Best-effort per step (see - // lib/projectDelete.ts) - there is nothing left to roll back to. - await cleanupDeletedAccount(env, session.userId); - - return addCorsHeaders(Response.json({ ok: true })); - } - // GET /users/by-handle/:handle - authenticated, resolves a /@ // profile link to a user id (routes/userHandles.ts). const userHandleMatch = url.pathname.match(/^\/users\/by-handle\/([^/]+)$/); @@ -749,84 +401,7 @@ export default { if (userProfileMatch && request.method === "GET") { const session = await getSession(request, env); if (session instanceof Response) return session; - const targetUserId = userProfileMatch[1]; - - const lookupRes = await env.AUTH.fetch("https://auth/lookup-by-id", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userId: targetUserId }), - }); - if (!lookupRes.ok) { - return addCorsHeaders(lookupRes.status === 404 ? errorResponse(Errors.NOT_FOUND) : errorResponse(Errors.INTERNAL)); - } - const lookupData = await lookupRes.json<{ ok: boolean; data?: { userId: string; name: string; email: string; createdAt: string; timezone: string | null; badges?: number; bio?: string | null; handle?: string | null } }>(); - if (!lookupData.ok || !lookupData.data) return addCorsHeaders(errorResponse(Errors.NOT_FOUND)); - - const sharedRows = await env.DB.prepare( - `SELECT p.id, p.name, target.role as their_role - FROM projects p - JOIN project_members caller ON caller.project_id = p.id AND caller.user_id = ? AND caller.accepted = 1 - JOIN project_members target ON target.project_id = p.id AND target.user_id = ? AND target.accepted = 1 - ORDER BY p.name ASC`, - ).bind(session.userId, targetUserId).all<{ id: string; name: string; their_role: string }>(); - - const favouriteRows = await env.DB.prepare( - `SELECT p.id, p.name, p.vanity_slug, p.logo_square_updated_at, p.logo_wide_updated_at, ufp.note - FROM user_favourite_projects ufp - JOIN projects p ON p.id = ufp.project_id - WHERE ufp.user_id = ? AND p.published_at IS NOT NULL - ORDER BY ufp.created_at DESC`, - ).bind(targetUserId).all<{ id: string; name: string; vanity_slug: string | null; logo_square_updated_at: string | null; logo_wide_updated_at: string | null; note: string | null }>(); - - const planRow = await env.AUTH_DB.prepare( - `SELECT p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, - b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, - b.personal_plan_cancel_at, - b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at - FROM users u - LEFT JOIN user_billing b ON b.user_id = u.id - LEFT JOIN user_preferences p ON p.user_id = u.id - WHERE u.id = ?`, - ).bind(targetUserId).first<{ - personal_plan: string | null; - personal_plan_status: string | null; - personal_plan_started_at: number | null; - personal_plan_cancel_at: number | null; - personal_plan_style: string | null; - personal_presence_color: string | null; - personal_crit_sparkles: number | null; - granted_plan: string | null; - granted_plan_expires_at: number | null; - granted_plan_started_at: number | null; - }>(); - const resolvedPlan = planRow ? resolvePersonalPlan(planRow) : { plan: "free" as const, since: null, style: null, presenceColor: null }; - - const profileData: Record = { - userId: lookupData.data.userId, - name: lookupData.data.name, - createdAt: lookupData.data.createdAt, - sharedProjects: sharedRows.results.map(r => ({ id: r.id, name: r.name, theirRole: r.their_role })), - favouriteSites: favouriteRows.results.map(r => ({ - id: r.id, - name: r.name, - vanitySlug: r.vanity_slug, - logoSquareUpdatedAt: r.logo_square_updated_at, - logoWideUpdatedAt: r.logo_wide_updated_at, - note: r.note, - })), - personalPlan: resolvedPlan.plan, - personalPlanSince: resolvedPlan.since, - personalPlanStyle: resolvedPlan.style, - badges: lookupData.data.badges ?? 0, - }; - if (lookupData.data.timezone) profileData.timezone = lookupData.data.timezone; - if (lookupData.data.handle) profileData.handle = lookupData.data.handle; - // Bio is supporter-gated on display: only render if the target user - // currently holds Ink. The column persists across cancel/resub cycles - // so a user gets their bio back if they re-subscribe. - if (resolvedPlan.plan === "ink" && lookupData.data.bio) profileData.bio = lookupData.data.bio; - - return addCorsHeaders(Response.json({ ok: true, data: profileData })); + return addCorsHeaders(await handleUserProfile(env, session, decodeURIComponent(userProfileMatch[1]))); } // Pending invites @@ -946,8 +521,8 @@ async function handleCollabUpgrade(request: Request, url: URL, env: Env, docId: if (!collabEnabled) return new Response("Realtime collaboration is temporarily disabled", { status: 503 }); // Token arrives as a query param (browsers can't set headers on WS). - // Re-wrap it as a Bearer header so authenticate() / the AUTH service binding handles it - // the same way every other route does - works in local dev without JWT_SECRET. + // Re-wrap it as a Bearer header so authenticate() handles it the same way + // every other route does. const token = url.searchParams.get("token"); if (!token) return new Response("Unauthorized", { status: 401 }); const authReq = new Request("https://placeholder/", { @@ -993,58 +568,6 @@ async function handleCollabUpgrade(request: Request, url: URL, env: Env, docId: return stub.fetch(upstream); } -// Builds the fetch init for re-dispatching an incoming request over the AUTH -// service binding. -// -// X-Client-IP: service-binding hops drop CF-Connecting-IP, so the edge-observed -// client IP travels as X-Client-IP - the frontend worker's /api proxy sets it, -// and we re-forward it here for the auth worker's login/register rate limiters -// and session-row IP capture. CF-Connecting-IP always wins when present (it's -// set by the Cloudflare edge and unspoofable), so a client-supplied X-Client-IP -// on a directly-routed request is never trusted. -// -// Shape: `fetch(url, init)` with a buffered body, NOT a forwarded Request -// object - wrangler's cross-process dev registry 503s when handed the original -// streamed request. These auth payloads are small JSON, so buffering is free. -// Keep the denormalized member-row email snapshots in this worker's DB in sync -// when the account email changes in the auth worker (same precedent as the -// name sync in PATCH /me). Pending invites are keyed by user_id, so they keep -// working either way - this only refreshes the displayed/stored address. -// Best-effort: by the time this runs the change has already applied in the -// auth DB, so a snapshot-sync failure must not turn the response into an -// error (on /verify-email that would read as "invalid link" after a -// successful change). -async function syncMemberEmails(env: Env, userId: string, email: string): Promise { - try { - await env.DB.batch([ - env.DB.prepare("UPDATE project_members SET email = ? WHERE user_id = ? AND email <> ?") - .bind(email, userId, email), - env.DB.prepare("UPDATE organization_members SET email = ? WHERE user_id = ? AND email <> ?") - .bind(email, userId, email), - ]); - } catch (err) { - console.error("syncMemberEmails failed", { userId, err }); - } -} - -async function proxyAuthInit(request: Request): Promise { - const headers = new Headers(request.headers); - // Hop-by-hop headers must not survive re-dispatch. Host must match the - // binding URL, Content-Length is re-derived from the buffered body, and a - // forwarded `Expect: 100-continue` makes wrangler's cross-process dev tunnel - // return the interim 100 as the final response when the handler outlasts the - // continue window (e.g. PBKDF2 on register/login). - headers.delete("Host"); - headers.delete("Content-Length"); - headers.delete("Expect"); - const ip = request.headers.get("CF-Connecting-IP") ?? request.headers.get("X-Client-IP"); - if (ip) headers.set("X-Client-IP", ip); - else headers.delete("X-Client-IP"); - const body = - request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer(); - return { method: request.method, headers, body }; -} - async function getSession(request: Request, env: Env): Promise { const result = await authenticate(request, env); if (result === null) return addCorsHeaders(errorResponse(Errors.UNAUTHORIZED)); diff --git a/packages/api/src/lib.ts b/packages/api/src/lib.ts index 8c86d8b..e2f48a7 100644 --- a/packages/api/src/lib.ts +++ b/packages/api/src/lib.ts @@ -407,3 +407,9 @@ export async function serveR2Object( headers: { ...baseHeaders, "Content-Length": String(size) }, }); } + +// True only for a SQLite/D1 UNIQUE-constraint violation (e.g. two users +// racing to claim the same profile handle). +export function isUniqueConstraintError(err: unknown): boolean { + return err instanceof Error && err.message.includes("UNIQUE constraint failed"); +} diff --git a/packages/api/src/lib/apiKeys.test.ts b/packages/api/src/lib/apiKeys.test.ts index 1008094..2210d0a 100644 --- a/packages/api/src/lib/apiKeys.test.ts +++ b/packages/api/src/lib/apiKeys.test.ts @@ -129,16 +129,20 @@ interface StubRow { revoked_at: string | null; } -type OwnerRow = { moderation: number; force_password_change: number }; +// The owner's users-mirror row (+ whether an admin deletion blocks them). +type OwnerRow = { status: string; suspended_until: number | null; blocked: number }; +const ACTIVE: OwnerRow = { status: "active", suspended_until: null, blocked: 0 }; -function makeEnv(row: StubRow | null, owner: OwnerRow | null = { moderation: 0, force_password_change: 0 }) { +function makeEnv(row: StubRow | null, owner: OwnerRow | null = ACTIVE) { const run = vi.fn().mockResolvedValue({ meta: { changes: 1 } }); const first = vi.fn().mockResolvedValue(row); const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - const ownerFirst = vi.fn().mockResolvedValue(owner); - const authPrepare = vi.fn().mockReturnValue({ bind: vi.fn().mockReturnValue({ first: ownerFirst }) }); - return { env: { DB: { prepare }, AUTH_DB: { prepare: authPrepare } } as unknown as Env, prepare, bind, first, run }; + const ownerFirst = vi.fn().mockResolvedValue( + owner && { id: "user-1", email: "o@example.com", name: "O", email_verified: 1, is_admin: 0, created_at: "2025", ...owner }, + ); + const ownerBind = vi.fn().mockReturnValue({ first: ownerFirst }); + const prepare = vi.fn((sql: string) => (/FROM users u/.test(sql) ? { bind: ownerBind } : { bind })); + return { env: { DB: { prepare } } as unknown as Env, prepare, bind, first, run }; } function validRow(over: Partial = {}): StubRow { @@ -177,13 +181,13 @@ describe("authenticateApiKey", () => { expect(await authenticateApiKey("annx_expired", env)).toBeNull(); }); - it("returns null when the owner's account is gone, disabled, suspended, or force-reset", async () => { + it("returns null when the owner's account is gone, disabled, suspended, or blocked by a pending deletion", async () => { const future = Math.floor(Date.now() / 1000) + 3600; for (const owner of [ null, - { moderation: -1, force_password_change: 0 }, - { moderation: future, force_password_change: 0 }, - { moderation: 0, force_password_change: 1 }, + { ...ACTIVE, status: "disabled" }, + { ...ACTIVE, status: "suspended", suspended_until: future }, + { ...ACTIVE, blocked: 1 }, ]) { const { env } = makeEnv(validRow(), owner); expect(await authenticateApiKey("annx_owner_blocked", env)).toBeNull(); @@ -191,7 +195,7 @@ describe("authenticateApiKey", () => { }); it("accepts a key whose owner's suspension has elapsed", async () => { - const { env } = makeEnv(validRow(), { moderation: Math.floor(Date.now() / 1000) - 10, force_password_change: 0 }); + const { env } = makeEnv(validRow(), { ...ACTIVE, status: "suspended", suspended_until: Math.floor(Date.now() / 1000) - 10 }); expect(await authenticateApiKey("annx_valid", env)).not.toBeNull(); }); diff --git a/packages/api/src/lib/apiKeys.ts b/packages/api/src/lib/apiKeys.ts index 33f4cec..c6762cd 100644 --- a/packages/api/src/lib/apiKeys.ts +++ b/packages/api/src/lib/apiKeys.ts @@ -1,5 +1,6 @@ import { ROLE_RANK, type Role } from "../lib"; import type { Env } from "../index"; +import { accountStanding, type MirrorUser } from "../account/identity"; // ── Scoped API keys for the public /v1 API ────────────────────────────────── // @@ -140,15 +141,16 @@ export async function authenticateApiKey(token: string, env: Env): Promise(); - if (!owner) return null; - if (owner.force_password_change) return null; - if (owner.moderation === -1) return null; - if (owner.moderation > 0 && Math.floor(nowMs / 1000) < owner.moderation) return null; + // sessions would: account deleted, Annex data scheduled for deletion, or + // disabled/suspended on the identity service (mirrors loadCurrentSession). + const owner = await env.DB.prepare( + `SELECT u.id, u.email, u.name, u.email_verified, u.is_admin, u.status, u.suspended_until, u.created_at, + (d.user_id IS NOT NULL) AS blocked + FROM users u LEFT JOIN user_deletions d ON d.user_id = u.id + WHERE u.id = ?`, + ).bind(row.user_id).first(); + if (!owner || owner.blocked) return null; + if (!(await accountStanding(env, owner, nowMs)).ok) return null; // Lazy "last used" bookkeeping. The API worker's fetch handler has no // ExecutionContext, so this is a cheap awaited write (throttled to one per diff --git a/packages/api/src/me.test.ts b/packages/api/src/me.test.ts index 983366a..6fece73 100644 --- a/packages/api/src/me.test.ts +++ b/packages/api/src/me.test.ts @@ -1,14 +1,12 @@ -// /me routes driven through the worker's fetch handler with a real signed JWT, -// real SQLite for both the API and auth DBs, and an in-memory R2: the -// favourites cap, DELETE /me's site cleanup and PATCH /me's name sync. +// /me routes driven through the worker's fetch handler with a real signed +// session JWT and real SQLite: the favourites cap, GET/PATCH /me from the +// users mirror, and the profile card. -import { describe, it, expect, beforeEach, vi } from "vitest"; -import { fileURLToPath } from "node:url"; +import { describe, it, expect, beforeEach } from "vitest"; import { createSqliteD1, type SqliteD1 } from "./test/sqliteD1"; import { seedSession } from "./test/session"; import worker, { type Env } from "./index"; -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../auth/migrations", import.meta.url)); const JWT_SECRET = "test-secret"; const T = "2026-10-01T00:00:00.000Z"; @@ -24,13 +22,11 @@ class FakeR2 { } let api: SqliteD1; -let auth: SqliteD1; let r2: FakeR2; -let authFetch: ReturnType; let token: string; function env(): Env { - return { DB: api.db, AUTH_DB: auth.db, ASSETS: r2, JWT_SECRET, AUTH: { fetch: authFetch } } as unknown as Env; + return { DB: api.db, ASSETS: r2, JWT_SECRET, OIDC_ISSUER: "https://auth.example" } as unknown as Env; } function call(method: string, path: string, body?: unknown) { @@ -59,10 +55,7 @@ function addFavourite(projectId: string, createdAt = Date.now()) { beforeEach(async () => { api = createSqliteD1(); - auth = createSqliteD1(AUTH_MIGRATIONS); r2 = new FakeR2(); - authFetch = vi.fn(async () => Response.json({ ok: true })); - auth.sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'u1@example.com', 'User One', 'x', datetime('now'))").run(); token = await seedSession(api.sqlite, { userId: "u1", email: "u1@example.com", name: "User One", sid: "s1", secret: JWT_SECRET }); }); @@ -94,70 +87,62 @@ describe("POST /me/favourite-sites/:id cap", () => { }); }); -describe("DELETE /me", () => { - it("refuses while the caller owns a site, before touching the auth worker", async () => { - addSite("mine", true, "u1"); - const res = await call("DELETE", "/me", { password: "pw" }); - expect(res.status).toBe(400); - expect(authFetch).not.toHaveBeenCalled(); - }); - - it("fully deletes a site that appeared after the ownership check (revisions, FTS, R2), plus memberships + avatar", async () => { - // Someone else's site the user is a member of: must survive. - addSite("other", true); - exec("INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at) VALUES ('m-other', 'other', 'u1', 'u1@example.com', 'User One', 'editor', 'owner-x', ?)", T); - exec("INSERT INTO asset_revisions (id, asset_type, asset_id, project_id, editor_id, editor_name, created_at) VALUES ('r-other', 'doc', 'd-other', 'other', 'u1', 'U', ?)", T); - r2.keys.add("other/d-other"); - - // The auth worker deletes the account; a site created in the race window - // between the owns_projects check and that call gets cleaned up after it. - authFetch.mockImplementation(async () => { - addSite("race", false, "u1"); - exec("INSERT INTO docs (id, title, project_id, author_id, created_at, updated_at) VALUES ('d1', 'Doc', 'race', 'u1', ?, ?)", T, T); - exec("INSERT INTO files (id, name, mime_type, size, project_id, uploaded_by, created_at) VALUES ('f1', 'f', 'image/png', 1, 'race', 'u1', ?)", T); - exec("INSERT INTO asset_revisions (id, asset_type, asset_id, project_id, editor_id, editor_name, created_at) VALUES ('r1', 'doc', 'd1', 'race', 'u1', 'U', ?)", T); - exec("INSERT INTO docs_fts (title, body, pid, doc_id, project_id) VALUES ('Doc', 'b', hex('race'), 'd1', 'race')"); - exec("INSERT INTO docs_fts_map (rid, doc_id) VALUES (last_insert_rowid(), 'd1')"); - for (const k of ["race/d1", "race/d1/v/r1", "files/f1", "site-logos/race-square"]) r2.keys.add(k); - return Response.json({ ok: true }); - }); - for (const k of ["avatars/u1-dark", "avatars/u1-light"]) r2.keys.add(k); - - const res = await call("DELETE", "/me", { password: "pw" }); +describe("GET /me", () => { + it("serves identity facts from the users mirror plus Annex prefs and account links", async () => { + exec("INSERT INTO user_preferences (user_id, timezone, handle, handle_locked) VALUES ('u1', 'Europe/London', 'one', 1)"); + const res = await call("GET", "/me"); expect(res.status).toBe(200); + expect(((await res.json()) as { data: unknown }).data).toMatchObject({ + userId: "u1", + name: "User One", + email: "u1@example.com", + timezone: "Europe/London", + handle: "one", + handleLocked: true, + personalPlan: "free", + accountUrl: "https://auth.example/account", + securityUrl: "https://auth.example/account/security", + }); + }); +}); - expect(count("SELECT COUNT(*) AS n FROM projects WHERE id = 'race'")).toBe(0); - expect(count("SELECT COUNT(*) AS n FROM asset_revisions WHERE project_id = 'race'")).toBe(0); - expect(count("SELECT COUNT(*) AS n FROM docs_fts WHERE project_id = 'race'")).toBe(0); - expect(count("SELECT COUNT(*) AS n FROM docs_fts_map WHERE doc_id = 'd1'")).toBe(0); - expect(count("SELECT COUNT(*) AS n FROM project_members WHERE user_id = 'u1'")).toBe(0); - expect([...r2.keys].sort()).toEqual(["other/d-other"]); - expect(count("SELECT COUNT(*) AS n FROM asset_revisions WHERE project_id = 'other'")).toBe(1); +describe("PATCH /me", () => { + it("refuses a name change: the name is managed on the identity service", async () => { + const res = await call("PATCH", "/me", { name: "New Name" }); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ error: "name_managed_by_identity", accountUrl: "https://auth.example/account" }); + expect(api.sqlite.prepare("SELECT name FROM users WHERE id = 'u1'").get()).toEqual({ name: "User One" }); }); - it("does no cleanup when the auth worker refuses (wrong password)", async () => { - addSite("other", true); - exec("INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at) VALUES ('m1', 'other', 'u1', 'e', 'n', 'editor', 'x', ?)", T); - r2.keys.add("avatars/u1-dark"); - authFetch.mockResolvedValue(Response.json({ ok: false, error: "invalid_password" }, { status: 401 })); + it("sets and clears the timezone, rejecting unknown zones", async () => { + expect((await call("PATCH", "/me", { timezone: "Not/AZone" })).status).toBe(400); + expect((await call("PATCH", "/me", { timezone: "Asia/Tokyo" })).status).toBe(200); + expect(api.sqlite.prepare("SELECT timezone FROM user_preferences WHERE user_id = 'u1'").get()).toEqual({ timezone: "Asia/Tokyo" }); + expect((await call("PATCH", "/me", { timezone: null })).status).toBe(200); + expect(api.sqlite.prepare("SELECT timezone FROM user_preferences WHERE user_id = 'u1'").get()).toEqual({ timezone: null }); + }); +}); - const res = await call("DELETE", "/me", { password: "nope" }); - expect(res.status).toBe(401); - expect(count("SELECT COUNT(*) AS n FROM project_members WHERE user_id = 'u1'")).toBe(1); - expect(r2.keys.has("avatars/u1-dark")).toBe(true); +describe("DELETE /me", () => { + it("is gone: accounts are deleted on the identity service", async () => { + expect((await call("DELETE", "/me")).status).toBe(404); + expect(count("SELECT COUNT(*) AS n FROM users WHERE id = 'u1'")).toBe(1); }); }); -describe("PATCH /me name sync", () => { - it("updates the denormalized name on site and org memberships", async () => { - addSite("s1", true); - exec("INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at) VALUES ('m1', 's1', 'u1', 'e', 'Old', 'editor', 'x', ?)", T); - exec("INSERT INTO organizations (id, name, owner_id, created_at) VALUES ('o1', 'Org', 'x', ?)", T); - exec("INSERT INTO organization_members (id, organization_id, user_id, email, name, role, invited_by, created_at, accepted) VALUES ('om1', 'o1', 'u1', 'e', 'Old', 'viewer', 'x', ?, 1)", T); +describe("GET /users/:userId", () => { + it("builds the profile card from the mirror, shows the bio only while the user holds Ink, and 404s unknown users", async () => { + exec("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES ('u2', 'u2@example.com', 'Two', '2025-01-01', 0, 0)"); + exec("INSERT INTO user_preferences (user_id, bio, badges, handle) VALUES ('u2', 'hello', 3, 'two')"); + let data = ((await (await call("GET", "/users/u2")).json()) as { data: Record }).data; + expect(data).toMatchObject({ userId: "u2", name: "Two", badges: 3, handle: "two", personalPlan: "free" }); + expect(data.bio).toBeUndefined(); + expect(data.email).toBeUndefined(); - const res = await call("PATCH", "/me", { name: " New Name " }); - expect(res.status).toBe(200); - expect(api.sqlite.prepare("SELECT name FROM project_members WHERE id = 'm1'").get()).toEqual({ name: "New Name" }); - expect(api.sqlite.prepare("SELECT name FROM organization_members WHERE id = 'om1'").get()).toEqual({ name: "New Name" }); + exec("INSERT INTO user_billing (user_id, granted_plan, granted_plan_started_at) VALUES ('u2', 'ink', 1)"); + data = ((await (await call("GET", "/users/u2")).json()) as { data: Record }).data; + expect(data).toMatchObject({ personalPlan: "ink", bio: "hello" }); + + expect((await call("GET", "/users/nobody")).status).toBe(404); }); }); diff --git a/packages/api/src/routes/auth.test.ts b/packages/api/src/routes/auth.test.ts index 99626ac..e015972 100644 --- a/packages/api/src/routes/auth.test.ts +++ b/packages/api/src/routes/auth.test.ts @@ -4,7 +4,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { createSqliteD1, type SqliteD1 } from "../test/sqliteD1"; import { createFakeIdp, type FakeIdp, type FakeUser } from "../test/fakeIdp"; import { setOidcFetchForTests, STATE_COOKIE } from "./auth"; -import { clearOidcCaches } from "../account/oidc"; +import { clearOidcCaches, identityFetch } from "../account/oidc"; import { clearIdentityCache, type IdentityService, type IdentityUser } from "../account/identity"; import worker, { type Env } from "../index"; @@ -250,6 +250,54 @@ describe("GET /auth/callback", () => { }); }); +describe("server-side OIDC requests over the IDENTITY_OIDC service binding", () => { + it("does discovery, JWKS and the token exchange through the binding, never a direct fetch", async () => { + const direct = vi.fn(async () => { throw new Error("same-zone fetch would hit the origin"); }); + setOidcFetchForTests(direct as unknown as typeof fetch); + const viaBinding = vi.fn((url: string, init?: RequestInit) => idp.fetch(url, init)); + extraEnv = { IDENTITY_OIDC: { fetch: viaBinding } as unknown as Fetcher }; + + const token = await signInToken(); + expect(token.split(".")).toHaveLength(3); + expect(direct).not.toHaveBeenCalled(); + const paths = viaBinding.mock.calls.map(([u]) => new URL(u).pathname); + expect(paths).toEqual(expect.arrayContaining(["/.well-known/openid-configuration", "/oauth/token", "/oauth/jwks"])); + // The browser still goes to the public authorize URL. + const login = await call("GET", "/auth/login"); + expect(login.headers.get("Location")!.startsWith(`${idp.issuer}/oauth/authorize?`)).toBe(true); + }); +}); + +describe("identityFetch", () => { + const ISSUER = "https://auth.example"; + it("routes only the issuer's host through the binding", async () => { + const binding = { fetch: vi.fn(async () => new Response("b")) }; + const direct = vi.fn(async () => new Response("d")); + const f = identityFetch({ issuer: ISSUER, binding, fetchImpl: direct as unknown as typeof fetch }); + expect(await (await f(`${ISSUER}/oauth/token`, { method: "POST", body: "x" })).text()).toBe("b"); + expect(await (await f("https://elsewhere.example/x")).text()).toBe("d"); + }); + + it("never falls back to a direct fetch outside local dev", async () => { + const binding = { fetch: vi.fn(async () => new Response("down", { status: 503 })) }; + const direct = vi.fn(async () => new Response("d")); + const f = identityFetch({ issuer: ISSUER, binding, fetchImpl: direct as unknown as typeof fetch }); + expect((await f(`${ISSUER}/oauth/jwks`)).status).toBe(503); + expect(direct).not.toHaveBeenCalled(); + }); + + it("falls back to the public issuer in local dev when the binding has no target", async () => { + const direct = vi.fn(async (_u: string, init?: RequestInit) => new Response(String(init?.body ?? ""))); + for (const binding of [ + { fetch: vi.fn(async () => new Response("no local session", { status: 503 })) }, + { fetch: vi.fn(async () => { throw new Error("binding unavailable"); }) }, + ]) { + const f = identityFetch({ issuer: ISSUER, binding, allowPublicFallback: true, fetchImpl: direct as unknown as typeof fetch }); + expect(await (await f(`${ISSUER}/oauth/token`, { method: "POST", body: "grant" })).text()).toBe("grant"); + } + }); +}); + describe("session standing", () => { it("locks out a user disabled on the identity service", async () => { const token = await signInToken(); diff --git a/packages/api/src/routes/auth.ts b/packages/api/src/routes/auth.ts index 2f68b69..b4774ee 100644 --- a/packages/api/src/routes/auth.ts +++ b/packages/api/src/routes/auth.ts @@ -28,6 +28,7 @@ import { } from "../account/oidc"; import { createPendingSession, createSessionToken, redeemHandoff, revokeSessionByToken, type SessionEnv } from "../account/session"; import { DEV_USER_PREFIX, isLocalDeploy, refreshMirror, type IdentityUser } from "../account/identity"; +import { syncStripeCustomerEmail } from "../account/stripe-client"; export interface AuthRouteEnv extends SessionEnv { OIDC_ISSUER?: string; @@ -36,6 +37,9 @@ export interface AuthRouteEnv extends SessionEnv { OIDC_REDIRECT_URI?: string; OIDC_POST_LOGOUT_REDIRECT_URI?: string; APP_ORIGIN?: string; + // Service binding to the identity worker's HTTP surface (default export of + // cubityfirst-auth): discovery, JWKS and the token exchange go through it. + IDENTITY_OIDC?: { fetch(input: string, init?: RequestInit): Promise }; } export const STATE_COOKIE = "annex_oidc"; @@ -62,6 +66,8 @@ export function appOidcConfig(env: AuthRouteEnv): OidcClientConfig | null { redirectUri: env.OIDC_REDIRECT_URI || `${origin}/api/auth/callback`, postLogoutRedirectUri: env.OIDC_POST_LOGOUT_REDIRECT_URI || `${origin}/`, scope: APP_SCOPE, + binding: env.IDENTITY_OIDC, + allowPublicFallback: isLocalDeploy(env), fetchImpl: fetchOverride, }; } @@ -145,7 +151,7 @@ export async function handleAuthCallback(request: Request, env: AuthRouteEnv, ur // Shared by the app and admin callbacks: refuses accounts Annex has blocked // or processed as deleted, upserts the mirror, creates a pending session. export async function startSession( - env: SessionEnv, + env: SessionEnv & { STRIPE_SECRET_KEY?: string }, request: Request, identity: { sub: string; email: string; emailVerified: boolean; name: string; roles: string[]; idToken: string }, kind: "app" | "admin", @@ -153,7 +159,7 @@ export async function startSession( const [gone, blocked, existing] = await env.DB.batch([ env.DB.prepare("SELECT 1 AS x FROM identity_deletions WHERE user_id = ?").bind(identity.sub), env.DB.prepare("SELECT 1 AS x FROM user_deletions WHERE user_id = ?").bind(identity.sub), - env.DB.prepare("SELECT created_at FROM users WHERE id = ?").bind(identity.sub), + env.DB.prepare("SELECT created_at, email FROM users WHERE id = ?").bind(identity.sub), ]); if (gone.results.length > 0) return { error: "account_deleted" }; if (blocked.results.length > 0) return { error: "account_disabled" }; @@ -173,6 +179,10 @@ export async function startSession( createdAt: (existing.results[0] as { created_at?: string } | undefined)?.created_at ?? new Date(now).toISOString(), }; await refreshMirror(env.DB, user, now, { login: true }); + // The email is changed on the identity service now; keep the Stripe + // customer's receipt address in step when a sign-in brings a new one. + const previousEmail = (existing.results[0] as { email?: string } | undefined)?.email; + if (previousEmail && previousEmail !== user.email) await syncStripeCustomerEmail(env, user.id, user.email); const { handoffCode } = await createPendingSession(env.DB, { userId: user.id, kind, request, idToken: identity.idToken, nowMs: now }); return { handoffCode }; } diff --git a/packages/api/src/routes/billing.test.ts b/packages/api/src/routes/billing.test.ts new file mode 100644 index 0000000..7ee24dc --- /dev/null +++ b/packages/api/src/routes/billing.test.ts @@ -0,0 +1,107 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleBillingCheckout, handleBillingPortal } from "./billing"; + +vi.mock("../account/stripe-client", () => ({ + getStripe: vi.fn(), +})); + +import { getStripe } from "../account/stripe-client"; + +const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; + +function makeEnv(userRow: Record | null) { + return { + DB: { + prepare: vi.fn().mockReturnValue({ + bind: vi.fn().mockReturnValue({ + first: vi.fn().mockResolvedValue(userRow), + }), + }), + }, + STRIPE_SECRET_KEY: "sk_test_xxx", + STRIPE_INK_PRICE_ID: "price_xxx", + APP_ORIGIN: "https://docs.example.com", + } as unknown as Parameters[0]; +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("handleBillingCheckout", () => { + it("returns 404 when user row missing", async () => { + const res = await handleBillingCheckout(makeEnv(null), mockSession); + expect(res.status).toBe(404); + }); + + it("creates checkout with customer_email when no stripe_customer_id", async () => { + const create = vi.fn().mockResolvedValue({ url: "https://checkout.stripe.com/abc" }); + vi.mocked(getStripe).mockReturnValue({ + checkout: { sessions: { create } }, + } as unknown as ReturnType); + + const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: null }); + const res = await handleBillingCheckout(env, mockSession); + expect(res.status).toBe(200); + const body = await res.json<{ data: { url: string } }>(); + expect(body.data.url).toBe("https://checkout.stripe.com/abc"); + + expect(create).toHaveBeenCalledOnce(); + const args = create.mock.calls[0][0]; + expect(args.mode).toBe("subscription"); + expect(args.customer_email).toBe("u@example.com"); + expect(args.customer).toBeUndefined(); + expect(args.client_reference_id).toBe("user-1"); + expect(args.line_items).toEqual([{ price: "price_xxx", quantity: 1 }]); + }); + + it("reuses existing stripe_customer_id when present", async () => { + const create = vi.fn().mockResolvedValue({ url: "https://checkout.stripe.com/def" }); + vi.mocked(getStripe).mockReturnValue({ + checkout: { sessions: { create } }, + } as unknown as ReturnType); + + const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: "cus_existing" }); + await handleBillingCheckout(env, mockSession); + + const args = create.mock.calls[0][0]; + expect(args.customer).toBe("cus_existing"); + expect(args.customer_email).toBeUndefined(); + }); + + it("returns 500 when Stripe doesn't return a url", async () => { + const create = vi.fn().mockResolvedValue({ url: null }); + vi.mocked(getStripe).mockReturnValue({ + checkout: { sessions: { create } }, + } as unknown as ReturnType); + + const env = makeEnv({ email: "u@example.com", name: "U", stripe_customer_id: null }); + const res = await handleBillingCheckout(env, mockSession); + expect(res.status).toBe(500); + }); +}); + +describe("handleBillingPortal", () => { + it("returns 400 when user has no stripe_customer_id", async () => { + const env = makeEnv({ stripe_customer_id: null }); + const res = await handleBillingPortal(env, mockSession); + expect(res.status).toBe(400); + }); + + it("creates a portal session and returns the url", async () => { + const create = vi.fn().mockResolvedValue({ url: "https://billing.stripe.com/portal/xyz" }); + vi.mocked(getStripe).mockReturnValue({ + billingPortal: { sessions: { create } }, + } as unknown as ReturnType); + + const env = makeEnv({ stripe_customer_id: "cus_1" }); + const res = await handleBillingPortal(env, mockSession); + expect(res.status).toBe(200); + const body = await res.json<{ data: { url: string } }>(); + expect(body.data.url).toBe("https://billing.stripe.com/portal/xyz"); + + const args = create.mock.calls[0][0]; + expect(args.customer).toBe("cus_1"); + expect(args.return_url).toBe("https://docs.example.com/settings#billing"); + }); +}); diff --git a/packages/api/src/routes/billing.ts b/packages/api/src/routes/billing.ts new file mode 100644 index 0000000..0c0e35e --- /dev/null +++ b/packages/api/src/routes/billing.ts @@ -0,0 +1,91 @@ +import { okResponse, errorResponse, Errors, type Session } from "../lib"; +import { getStripe } from "../account/stripe-client"; + +// What the billing routes and the Stripe webhook need from the API worker's +// Env. Billing moved here from the retired auth worker with the identity +// split; Stripe customers are still keyed by Annex user id. +export interface BillingEnv { + DB: D1Database; + STRIPE_SECRET_KEY?: string; + STRIPE_WEBHOOK_SECRET?: string; + STRIPE_INK_PRICE_ID?: string; + APP_ORIGIN?: string; +} + +function appOrigin(env: BillingEnv): string { + return (env.APP_ORIGIN ?? "https://docs.cubityfir.st").replace(/\/+$/, ""); +} + +interface UserBillingRow { + email: string; + name: string; + stripe_customer_id: string | null; +} + +// POST /billing/checkout +// Creates a Stripe Checkout Session for the Annex Ink subscription and +// returns the redirect URL. The browser navigates to it; on success +// Stripe sends us back to /settings#billing and the webhook fires +// checkout.session.completed which links the customer + sub to the user. +export async function handleBillingCheckout(env: BillingEnv, session: Session): Promise { + if (!env.STRIPE_SECRET_KEY || !env.STRIPE_INK_PRICE_ID) { + return errorResponse(Errors.INTERNAL); + } + + const user = await env.DB.prepare( + `SELECT u.email, u.name, b.stripe_customer_id + FROM users u + LEFT JOIN user_billing b ON b.user_id = u.id + WHERE u.id = ?`, + ).bind(session.userId).first(); + if (!user) return errorResponse(Errors.NOT_FOUND); + + const stripe = getStripe(env.STRIPE_SECRET_KEY); + const returnUrl = `${appOrigin(env)}/settings#billing`; + + // Reuse an existing customer when we have one (resub case); otherwise + // let Checkout create a new customer and we'll link it on webhook. + const customerArgs = user.stripe_customer_id + ? { customer: user.stripe_customer_id } + : { customer_email: user.email }; + + const checkout = await stripe.checkout.sessions.create({ + mode: "subscription", + line_items: [{ price: env.STRIPE_INK_PRICE_ID, quantity: 1 }], + client_reference_id: session.userId, + // Stripe doesn't guarantee event ordering. Stamping userId into the + // subscription metadata means every customer.subscription.* event + // can resolve back to a user even if checkout.session.completed + // hasn't been processed yet. + subscription_data: { metadata: { userId: session.userId } }, + success_url: returnUrl, + cancel_url: returnUrl, + allow_promotion_codes: true, + ...customerArgs, + }); + + if (!checkout.url) return errorResponse(Errors.INTERNAL); + return okResponse({ url: checkout.url }); +} + +// POST /billing/portal +// Creates a Stripe Customer Portal session so the user can manage their +// subscription (update card, cancel, view invoices). Requires that we've +// already linked a stripe_customer_id - i.e. they've completed at least +// one Checkout. Free users get a 400. +export async function handleBillingPortal(env: BillingEnv, session: Session): Promise { + if (!env.STRIPE_SECRET_KEY) return errorResponse(Errors.INTERNAL); + + const user = await env.DB.prepare( + "SELECT stripe_customer_id FROM user_billing WHERE user_id = ?", + ).bind(session.userId).first<{ stripe_customer_id: string | null }>(); + if (!user?.stripe_customer_id) return errorResponse(Errors.BAD_REQUEST); + + const stripe = getStripe(env.STRIPE_SECRET_KEY); + const portal = await stripe.billingPortal.sessions.create({ + customer: user.stripe_customer_id, + return_url: `${appOrigin(env)}/settings#billing`, + }); + + return okResponse({ url: portal.url }); +} diff --git a/packages/api/src/routes/inviteLinks.test.ts b/packages/api/src/routes/inviteLinks.test.ts index ff7b2dc..02185c4 100644 --- a/packages/api/src/routes/inviteLinks.test.ts +++ b/packages/api/src/routes/inviteLinks.test.ts @@ -9,7 +9,7 @@ import { authenticate } from "../auth"; const user = { userId: "caller-1", email: "a@example.com" } as unknown as Parameters[2]; -function makeEnv(opts?: { lookupOk?: boolean }) { +function makeEnv() { const firsts: unknown[] = []; const alls: unknown[] = []; const runs: unknown[] = []; @@ -22,19 +22,13 @@ function makeEnv(opts?: { lookupOk?: boolean }) { const bind = vi.fn(() => ({ first, all, run })); const prepare = vi.fn((_sql: string) => ({ bind })); const batch = vi.fn(() => Promise.resolve([])); - const authFetch = vi.fn(async () => { - if (opts?.lookupOk === false) return new Response("", { status: 500 }); - return Response.json({ ok: true, data: { name: "Bob", email: "bob@x.z" } }, { status: 200 }); - }); return { env: { DB: { prepare, batch }, - AUTH: { fetch: authFetch }, } as unknown as Parameters[1], run, batch, prepare, - authFetch, queueFirst: (v: unknown) => firsts.push(v), queueRun: (v: unknown) => runs.push(v), queueAll: (v: unknown) => alls.push(v), @@ -264,13 +258,14 @@ describe("handleInvitePublic POST accept", () => { expect(json.data.role).toBe("viewer"); }); - it("creates a new membership after a successful lookup", async () => { - const { env, queueFirst, prepare, authFetch } = makeEnv(); + it("creates a new membership with the caller's name/email from the users mirror", async () => { + const { env, queueFirst, prepare } = makeEnv(); queueFirst(validLink()); queueFirst(null); // not yet a member + queueFirst({ name: "Bob", email: "bob@x.z" }); // users mirror row const res = await callPublic(env, "POST", "/invites/tok/accept"); expect(res.status).toBe(201); - expect(authFetch).toHaveBeenCalled(); + expect(prepare.mock.calls.some(c => c[0].includes("FROM users WHERE id = ?"))).toBe(true); expect(prepare.mock.calls.some(c => c[0].includes("INSERT INTO project_members"))).toBe(true); const json = (await res.json()) as { data: { role: string } }; expect(json.data.role).toBe("editor"); @@ -280,6 +275,7 @@ describe("handleInvitePublic POST accept", () => { const { env, queueFirst, queueRun, prepare } = makeEnv(); queueFirst(validLink()); queueFirst(null); + queueFirst({ name: "Bob", email: "bob@x.z" }); queueRun({ meta: { changes: 0 } }); // conditional use_count claim loses the race const res = await callPublic(env, "POST", "/invites/tok/accept"); expect(res.status).toBe(410); @@ -290,16 +286,18 @@ describe("handleInvitePublic POST accept", () => { const { env, queueFirst, queueRun, prepare } = makeEnv(); queueFirst(validLink()); queueFirst(null); + queueFirst({ name: "Bob", email: "bob@x.z" }); queueRun({ meta: { changes: 1 } }); // claim succeeds queueRun(new Error("UNIQUE constraint failed")); // insert loses to the other tab await expect(callPublic(env, "POST", "/invites/tok/accept")).rejects.toThrow(/UNIQUE/); expect(prepare.mock.calls.some(c => c[0].includes("use_count = use_count - 1"))).toBe(true); }); - it("500s when the auth-worker lookup fails", async () => { - const { env, queueFirst } = makeEnv({ lookupOk: false }); + it("500s when the caller has no users-mirror row", async () => { + const { env, queueFirst } = makeEnv(); queueFirst(validLink()); queueFirst(null); + queueFirst(null); const res = await callPublic(env, "POST", "/invites/tok/accept"); expect(res.status).toBe(500); }); diff --git a/packages/api/src/routes/inviteLinks.ts b/packages/api/src/routes/inviteLinks.ts index 5a78292..08d98f1 100644 --- a/packages/api/src/routes/inviteLinks.ts +++ b/packages/api/src/routes/inviteLinks.ts @@ -190,15 +190,10 @@ export async function handleInvitePublic( return okResponse({ projectId: link.project_id, role: existing.role }, 201); } - // Look up user info from auth worker - const lookupRes = await env.AUTH.fetch("https://auth/lookup-by-id", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userId: session.userId }), - }); - if (!lookupRes.ok) return errorResponse(Errors.INTERNAL); - const lookupData = await lookupRes.json<{ ok: boolean; data?: { name: string; email: string } }>(); - if (!lookupData.ok || !lookupData.data) return errorResponse(Errors.INTERNAL); + // The member row's name/email snapshot comes from the users mirror. + const me = await env.DB.prepare("SELECT name, email FROM users WHERE id = ?").bind(session.userId).first<{ name: string; email: string }>(); + if (!me) return errorResponse(Errors.INTERNAL); + const lookupData = { data: me }; if (!(await claimLinkUse(env, token))) return linkExhausted(); const memberId = crypto.randomUUID(); diff --git a/packages/api/src/routes/me/me.ts b/packages/api/src/routes/me/me.ts new file mode 100644 index 0000000..01a3918 --- /dev/null +++ b/packages/api/src/routes/me/me.ts @@ -0,0 +1,157 @@ +// GET/PATCH /me and GET /users/:userId, served from cubedocs-main. +// +// Identity facts (name, email, verification) come from the users mirror, +// which the identity service owns: Annex no longer changes them. Annex-only +// facts (timezone, bio, handle, badges, fonts, theme, Ink) come from +// user_preferences / user_billing. + +import { errorResponse, Errors, okResponse, type Session } from "../../lib"; +import { resolvePersonalPlan } from "../../account/plan"; +import type { Env } from "../../index"; + +// Where the identity service's own account pages live, for the settings +// page's "Manage your account" links. +export function identityAccountUrls(env: Pick): { accountUrl: string; securityUrl: string } { + const issuer = (env.OIDC_ISSUER ?? "https://auth.cubityfir.st").replace(/\/+$/, ""); + return { accountUrl: `${issuer}/account`, securityUrl: `${issuer}/account/security` }; +} + +export async function handleGetMe(env: Env, session: Session): Promise { + const [row, customThemingEnabled] = await Promise.all([ + env.DB.prepare( + `SELECT u.name, u.email, u.email_verified, p.timezone, p.bio, p.handle, p.handle_locked + FROM users u LEFT JOIN user_preferences p ON p.user_id = u.id + WHERE u.id = ?`, + ).bind(session.userId).first<{ + name: string; email: string; email_verified: number; + timezone: string | null; bio: string | null; handle: string | null; handle_locked: number | null; + }>(), + env.FLAGS + ? env.FLAGS.getBooleanValue("custom-theming", false, { userId: session.userId }) + : Promise.resolve(true), + ]); + if (!row) return errorResponse(Errors.UNAUTHORIZED); + + return okResponse({ + name: row.name, + email: row.email, + emailVerified: row.email_verified === 1, + userId: session.userId, + timezone: row.timezone, + bio: row.bio, + handle: row.handle ?? null, + handleLocked: !!row.handle_locked, + personalPlan: session.personalPlan ?? "free", + personalPlanSince: session.personalPlanSince ?? null, + personalPlanStatus: session.personalPlanStatus ?? null, + personalPlanCancelAt: session.personalPlanCancelAt ?? null, + personalPlanStyle: session.personalPlanStyle ?? null, + personalPresenceColor: session.personalPresenceColor ?? null, + personalCritSparkles: session.personalCritSparkles ?? true, + readingFont: session.readingFont ?? null, + editingFont: session.editingFont ?? null, + uiFont: session.uiFont ?? null, + isAdmin: session.isAdmin ?? false, + themeMode: session.themeMode ?? null, + themeCustomColor: session.themeCustomColor ?? null, + customThemingEnabled, + ...identityAccountUrls(env), + }); +} + +// PATCH /me - timezone only. The display name belongs to the identity +// service now (auth.cubityfir.st/account); Annex picks changes up from it. +export async function handlePatchMe(request: Request, env: Env, session: Session): Promise { + const body = await request.json<{ name?: unknown; timezone?: string | null }>().catch(() => null); + if (!body || typeof body !== "object") return errorResponse(Errors.BAD_REQUEST); + if ("name" in body) { + return Response.json( + { ok: false, error: "name_managed_by_identity", status: 400, ...identityAccountUrls(env) }, + { status: 400 }, + ); + } + if (!("timezone" in body)) return errorResponse(Errors.BAD_REQUEST); + + const timezone = body.timezone ?? null; + if (timezone !== null) { + if (typeof timezone !== "string") return errorResponse(Errors.BAD_REQUEST); + try { + new Intl.DateTimeFormat("en-US", { timeZone: timezone }); + } catch { + return errorResponse(Errors.BAD_REQUEST); + } + } + await env.DB.prepare( + `INSERT INTO user_preferences (user_id, timezone) VALUES (?, ?) + ON CONFLICT(user_id) DO UPDATE SET timezone = excluded.timezone`, + ).bind(session.userId, timezone).run(); + return okResponse({ timezone }); +} + +// GET /users/:userId - profile card: name, plan, badges, bio (Ink only), +// handle, timezone, shared sites and favourites. +export async function handleUserProfile(env: Env, session: Session, targetUserId: string): Promise { + const user = await env.DB.prepare( + `SELECT u.id, u.name, u.created_at, + p.timezone, p.badges, p.bio, p.handle, + p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, + b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, + b.personal_plan_cancel_at, + b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at + FROM users u + LEFT JOIN user_billing b ON b.user_id = u.id + LEFT JOIN user_preferences p ON p.user_id = u.id + WHERE u.id = ?`, + ).bind(targetUserId).first<{ + id: string; name: string; created_at: string; + timezone: string | null; badges: number | null; bio: string | null; handle: string | null; + personal_plan: string | null; personal_plan_status: string | null; personal_plan_started_at: number | null; + personal_plan_cancel_at: number | null; personal_plan_style: string | null; personal_presence_color: string | null; + personal_crit_sparkles: number | null; granted_plan: string | null; granted_plan_expires_at: number | null; + granted_plan_started_at: number | null; + }>(); + if (!user) return errorResponse(Errors.NOT_FOUND); + + const [sharedRows, favouriteRows] = await Promise.all([ + env.DB.prepare( + `SELECT p.id, p.name, target.role as their_role + FROM projects p + JOIN project_members caller ON caller.project_id = p.id AND caller.user_id = ? AND caller.accepted = 1 + JOIN project_members target ON target.project_id = p.id AND target.user_id = ? AND target.accepted = 1 + ORDER BY p.name ASC`, + ).bind(session.userId, targetUserId).all<{ id: string; name: string; their_role: string }>(), + env.DB.prepare( + `SELECT p.id, p.name, p.vanity_slug, p.logo_square_updated_at, p.logo_wide_updated_at, ufp.note + FROM user_favourite_projects ufp + JOIN projects p ON p.id = ufp.project_id + WHERE ufp.user_id = ? AND p.published_at IS NOT NULL + ORDER BY ufp.created_at DESC`, + ).bind(targetUserId).all<{ id: string; name: string; vanity_slug: string | null; logo_square_updated_at: string | null; logo_wide_updated_at: string | null; note: string | null }>(), + ]); + + const resolvedPlan = resolvePersonalPlan(user); + const profile: Record = { + userId: user.id, + name: user.name, + createdAt: user.created_at, + sharedProjects: sharedRows.results.map(r => ({ id: r.id, name: r.name, theirRole: r.their_role })), + favouriteSites: favouriteRows.results.map(r => ({ + id: r.id, + name: r.name, + vanitySlug: r.vanity_slug, + logoSquareUpdatedAt: r.logo_square_updated_at, + logoWideUpdatedAt: r.logo_wide_updated_at, + note: r.note, + })), + personalPlan: resolvedPlan.plan, + personalPlanSince: resolvedPlan.since, + personalPlanStyle: resolvedPlan.style, + badges: user.badges ?? 0, + }; + if (user.timezone) profile.timezone = user.timezone; + if (user.handle) profile.handle = user.handle; + // Bio is supporter-gated on display: only shown while the user holds Ink. + // The column persists across cancel/resub so it comes back on resubscribe. + if (resolvedPlan.plan === "ink" && user.bio) profile.bio = user.bio; + return okResponse(profile); +} diff --git a/packages/api/src/routes/me/update-bio.test.ts b/packages/api/src/routes/me/update-bio.test.ts new file mode 100644 index 0000000..4486878 --- /dev/null +++ b/packages/api/src/routes/me/update-bio.test.ts @@ -0,0 +1,118 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleUpdateBio } from "./update-bio"; +import type { PlanRow } from "../../account/plan"; + +vi.mock("../../account/requestSession", () => ({ + requireAuthenticatedSession: vi.fn(), +})); + +import { requireAuthenticatedSession } from "../../account/requestSession"; + +const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; + +const inkRow: PlanRow = { + granted_plan: "ink", + granted_plan_expires_at: null, + granted_plan_started_at: 1, + personal_plan: null, + personal_plan_status: null, + personal_plan_started_at: null, + personal_plan_cancel_at: null, + personal_plan_style: null, + personal_presence_color: null, + personal_crit_sparkles: null, +}; + +const freeRow: PlanRow = { ...inkRow, granted_plan: null, granted_plan_started_at: null }; + +// The handler calls .first() for the plan-gate query and .run() for the upsert, +// both off the same prepare().bind() chain, so the chain exposes both. +function makeEnv(planRow: PlanRow | null) { + const first = vi.fn().mockResolvedValue(planRow); + const run = vi.fn().mockResolvedValue({}); + const bind = vi.fn().mockReturnValue({ first, run }); + const prepare = vi.fn().mockReturnValue({ bind }); + return { + env: { DB: { prepare } } as unknown as Parameters[1], + prepare, + bind, + first, + run, + }; +} + +function req(body: unknown) { + return new Request("http://localhost/update-bio", { + method: "POST", + headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); +}); + +describe("handleUpdateBio", () => { + it("returns 401 when the session is invalid", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue( + Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), + ); + const { env } = makeEnv(inkRow); + const res = await handleUpdateBio(req({ bio: "hello" }), env); + expect(res.status).toBe(401); + }); + + it("rejects a body without a bio field", async () => { + const { env, prepare } = makeEnv(inkRow); + const res = await handleUpdateBio(req({}), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("rejects a bio over the length cap", async () => { + const { env } = makeEnv(inkRow); + const res = await handleUpdateBio(req({ bio: "x".repeat(281) }), env); + expect(res.status).toBe(400); + }); + + it("returns 403 for a free (non-Ink) user", async () => { + const { env, run } = makeEnv(freeRow); + const res = await handleUpdateBio(req({ bio: "supporter" }), env); + expect(res.status).toBe(403); + expect(run).not.toHaveBeenCalled(); + }); + + it("returns 404 when the user row is missing", async () => { + const { env } = makeEnv(null); + const res = await handleUpdateBio(req({ bio: "supporter" }), env); + expect(res.status).toBe(404); + }); + + it("writes a trimmed bio for an Ink user", async () => { + const { env, run, bind } = makeEnv(inkRow); + const res = await handleUpdateBio(req({ bio: " My bio " }), env); + expect(res.status).toBe(200); + const json = (await res.json()) as { ok: boolean; data: { bio: string | null } }; + expect(json.data.bio).toBe("My bio"); + expect(run).toHaveBeenCalledOnce(); + expect(bind).toHaveBeenLastCalledWith("user-1", "My bio"); + }); + + it("treats an empty/whitespace bio as a clear (null)", async () => { + const { env, bind } = makeEnv(inkRow); + const res = await handleUpdateBio(req({ bio: " " }), env); + expect(res.status).toBe(200); + const json = (await res.json()) as { data: { bio: string | null } }; + expect(json.data.bio).toBeNull(); + expect(bind).toHaveBeenLastCalledWith("user-1", null); + }); + + it("treats explicit null as a clear", async () => { + const { env, bind } = makeEnv(inkRow); + const res = await handleUpdateBio(req({ bio: null }), env); + expect(res.status).toBe(200); + expect(bind).toHaveBeenLastCalledWith("user-1", null); + }); +}); diff --git a/packages/api/src/routes/me/update-bio.ts b/packages/api/src/routes/me/update-bio.ts new file mode 100644 index 0000000..631e86f --- /dev/null +++ b/packages/api/src/routes/me/update-bio.ts @@ -0,0 +1,69 @@ +import { requireAuthenticatedSession } from "../../account/requestSession"; +import { okResponse, errorResponse, Errors } from "../../lib"; +import { resolvePersonalPlan } from "../../account/plan"; +import type { Env } from "../../index"; + +const MAX_BIO_LENGTH = 280; + +// PATCH the supporter bio. Pass `null` (or empty/whitespace string) to clear. +// +// Gated to active Ink plan via resolvePersonalPlan, mirroring update-ink-prefs: +// refusing here rather than just hiding the UI prevents a downgrade race +// (sub canceled mid-session, request submitted before JWT refresh) from +// silently writing. +export async function handleUpdateBio(request: Request, env: Env): Promise { + const session = await requireAuthenticatedSession(request, env); + if (session instanceof Response) return session; + + const body = await request.json<{ bio?: string | null }>(); + if (!("bio" in body)) return errorResponse(Errors.BAD_REQUEST); + + let normalized: string | null; + if (body.bio === null) { + normalized = null; + } else if (typeof body.bio === "string") { + const trimmed = body.bio.trim(); + if (trimmed.length === 0) { + normalized = null; + } else if (trimmed.length > MAX_BIO_LENGTH) { + return errorResponse(Errors.BAD_REQUEST); + } else { + normalized = trimmed; + } + } else { + return errorResponse(Errors.BAD_REQUEST); + } + + const planRow = await env.DB.prepare( + `SELECT p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, + b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, + b.personal_plan_cancel_at, + b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at + FROM users u + LEFT JOIN user_billing b ON b.user_id = u.id + LEFT JOIN user_preferences p ON p.user_id = u.id + WHERE u.id = ?`, + ).bind(session.userId).first<{ + personal_plan: string | null; + personal_plan_status: string | null; + personal_plan_started_at: number | null; + personal_plan_cancel_at: number | null; + personal_plan_style: string | null; + personal_presence_color: string | null; + personal_crit_sparkles: number | null; + granted_plan: string | null; + granted_plan_expires_at: number | null; + granted_plan_started_at: number | null; + }>(); + if (!planRow) return errorResponse(Errors.NOT_FOUND); + + const resolved = resolvePersonalPlan(planRow); + if (resolved.plan !== "ink") return errorResponse(Errors.FORBIDDEN); + + await env.DB.prepare( + `INSERT INTO user_preferences (user_id, bio) VALUES (?, ?) + ON CONFLICT(user_id) DO UPDATE SET bio = excluded.bio`, + ).bind(session.userId, normalized).run(); + + return okResponse({ bio: normalized }); +} diff --git a/packages/api/src/routes/me/update-handle.test.ts b/packages/api/src/routes/me/update-handle.test.ts new file mode 100644 index 0000000..1974466 --- /dev/null +++ b/packages/api/src/routes/me/update-handle.test.ts @@ -0,0 +1,158 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { createSqliteD1 } from "../../test/sqliteD1"; +import { handleUpdateHandle } from "./update-handle"; + +vi.mock("../../account/requestSession", () => ({ + requireAuthenticatedSession: vi.fn(), +})); + +import { requireAuthenticatedSession } from "../../account/requestSession"; + +// Real SQLite with every main-DB migration applied, so uniqueness is the +// actual partial unique index on user_preferences.handle rather than a mocked +// error. + +function makeEnv() { + const { db, sqlite } = createSqliteD1(); + const user = sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES (?, ?, 'U', datetime('now'), 0, 0)"); + user.run("user-1", "a@example.com"); + user.run("user-2", "b@example.com"); + const handleOf = (userId: string) => + (sqlite.prepare("SELECT handle FROM user_preferences WHERE user_id = ?").get(userId) as { handle: string | null } | undefined)?.handle; + return { env: { DB: db } as unknown as Parameters[1], sqlite, handleOf }; +} + +function as(userId: string) { + vi.mocked(requireAuthenticatedSession).mockResolvedValue({ userId, email: `${userId}@example.com`, expiresAt: Date.now() + 3600_000 }); +} + +function req(body: unknown) { + return new Request("http://localhost/update-handle", { + method: "POST", + headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + as("user-1"); +}); + +describe("handleUpdateHandle", () => { + it("returns 401 when the session is invalid", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue( + Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), + ); + const { env } = makeEnv(); + const res = await handleUpdateHandle(req({ handle: "someone" }), env); + expect(res.status).toBe(401); + }); + + it("rejects a body without a handle field", async () => { + const { env } = makeEnv(); + expect((await handleUpdateHandle(req({}), env)).status).toBe(400); + expect((await handleUpdateHandle(req({ handle: 42 }), env)).status).toBe(400); + }); + + it("rejects invalid and reserved handles with a reason, writing nothing", async () => { + const { env, handleOf } = makeEnv(); + for (const [handle, reason] of [["ab", "length"], ["bad name", "characters"], ["admin", "reserved"]] as const) { + const res = await handleUpdateHandle(req({ handle }), env); + expect(res.status, handle).toBe(400); + expect(((await res.json()) as { reason: string }).reason).toBe(reason); + } + expect(handleOf("user-1")).toBeUndefined(); + }); + + it("creates the satellite row and stores the normalized handle", async () => { + const { env, handleOf } = makeEnv(); + const res = await handleUpdateHandle(req({ handle: " @Cubity_First " }), env); + expect(res.status).toBe(200); + expect(((await res.json()) as { data: { handle: string } }).data.handle).toBe("cubity_first"); + expect(handleOf("user-1")).toBe("cubity_first"); + }); + + it("updates an existing preferences row without touching other columns", async () => { + const { env, sqlite, handleOf } = makeEnv(); + sqlite.prepare("INSERT INTO user_preferences (user_id, bio) VALUES ('user-1', 'hello')").run(); + await handleUpdateHandle(req({ handle: "first" }), env); + await handleUpdateHandle(req({ handle: "second" }), env); + expect(handleOf("user-1")).toBe("second"); + expect((sqlite.prepare("SELECT bio FROM user_preferences WHERE user_id = 'user-1'").get() as { bio: string }).bio).toBe("hello"); + }); + + it("re-saving your own handle is not a conflict", async () => { + const { env } = makeEnv(); + await handleUpdateHandle(req({ handle: "mine" }), env); + expect((await handleUpdateHandle(req({ handle: "MINE" }), env)).status).toBe(200); + }); + + it("returns 409 when another user holds the handle, case-insensitively", async () => { + const { env, handleOf } = makeEnv(); + await handleUpdateHandle(req({ handle: "taken" }), env); + as("user-2"); + const res = await handleUpdateHandle(req({ handle: "Taken" }), env); + expect(res.status).toBe(409); + expect(handleOf("user-2")).toBeUndefined(); + }); + + it("an admin lock blocks claiming, renaming and clearing (403 locked)", async () => { + const { env, sqlite, handleOf } = makeEnv(); + // Locked with no handle: the user can't claim one. + sqlite.prepare("INSERT INTO user_preferences (user_id, handle_locked) VALUES ('user-1', 1)").run(); + let res = await handleUpdateHandle(req({ handle: "wanted" }), env); + expect(res.status).toBe(403); + expect(((await res.json()) as { reason: string }).reason).toBe("locked"); + expect(handleOf("user-1")).toBeNull(); + + // Locked with an admin-assigned handle: can't rename or clear it. + sqlite.prepare("UPDATE user_preferences SET handle = 'official' WHERE user_id = 'user-1'").run(); + expect((await handleUpdateHandle(req({ handle: "other" }), env)).status).toBe(403); + expect((await handleUpdateHandle(req({ handle: null }), env)).status).toBe(403); + expect(handleOf("user-1")).toBe("official"); + }); + + it("the write itself re-checks the lock (lock lands after the pre-read)", async () => { + const { env, sqlite, handleOf } = makeEnv(); + sqlite.prepare("INSERT INTO user_preferences (user_id, handle) VALUES ('user-1', 'before')").run(); + // Simulate the admin lock landing between the handler's lock read and its + // write: the first SELECT sees unlocked, then the row flips to locked. + const realPrepare = env.DB.prepare.bind(env.DB); + let lockReads = 0; + (env.DB as unknown as { prepare: (sql: string) => D1PreparedStatement }).prepare = (sql: string) => { + if (sql.startsWith("SELECT handle_locked") && lockReads++ === 0) { + const stmt = realPrepare(sql); + return { + bind: (...args: unknown[]) => { + const bound = stmt.bind(...args); + return { + first: async () => { + const row = await bound.first(); + sqlite.prepare("UPDATE user_preferences SET handle_locked = 1 WHERE user_id = 'user-1'").run(); + return row; + }, + }; + }, + } as unknown as D1PreparedStatement; + } + return realPrepare(sql); + }; + const res = await handleUpdateHandle(req({ handle: "after" }), env); + expect(res.status).toBe(403); + expect(handleOf("user-1")).toBe("before"); + }); + + it("clearing (null or blank) releases the handle for someone else", async () => { + const { env, handleOf } = makeEnv(); + await handleUpdateHandle(req({ handle: "shared" }), env); + const res = await handleUpdateHandle(req({ handle: " " }), env); + expect(((await res.json()) as { data: { handle: null } }).data.handle).toBeNull(); + expect(handleOf("user-1")).toBeNull(); + + as("user-2"); + expect((await handleUpdateHandle(req({ handle: "shared" }), env)).status).toBe(200); + as("user-1"); + expect((await handleUpdateHandle(req({ handle: null }), env)).status).toBe(200); + }); +}); diff --git a/packages/api/src/routes/me/update-handle.ts b/packages/api/src/routes/me/update-handle.ts new file mode 100644 index 0000000..567b9e4 --- /dev/null +++ b/packages/api/src/routes/me/update-handle.ts @@ -0,0 +1,85 @@ +import { requireAuthenticatedSession } from "../../account/requestSession"; +import { okResponse, errorResponse, Errors, isUniqueConstraintError } from "../../lib"; +import { normalizeHandle, handleProblem } from "../../account/handle"; +import type { Env } from "../../index"; + +// Set or clear the caller's public profile handle (the opt-in `/@` +// link). `{ handle: null }` (or an empty string) turns the link off and +// releases the name. Not plan-gated. Refused (403, reason "locked") while an +// admin has locked the user's handle. +// +// Uniqueness is enforced by the partial unique index on +// user_preferences.handle (0035), so a concurrent claim of the same name loses +// with a 409 rather than racing a SELECT-then-write check. +export async function handleUpdateHandle(request: Request, env: Env): Promise { + const session = await requireAuthenticatedSession(request, env); + if (session instanceof Response) return session; + + let body: { handle?: unknown }; + try { + body = await request.json<{ handle?: unknown }>(); + } catch { + return errorResponse(Errors.BAD_REQUEST); + } + if (!body || typeof body !== "object" || !("handle" in body)) return errorResponse(Errors.BAD_REQUEST); + + let handle: string | null; + if (body.handle === null) { + handle = null; + } else if (typeof body.handle === "string") { + const normalized = normalizeHandle(body.handle); + if (normalized.length === 0) { + handle = null; + } else { + const problem = handleProblem(normalized); + if (problem) { + return Response.json({ ok: false, ...Errors.BAD_REQUEST, reason: problem }, { status: 400 }); + } + handle = normalized; + } + } else { + return errorResponse(Errors.BAD_REQUEST); + } + + // Admin lock (0035 handle_locked): the user can't change their handle at + // all - neither claim one nor rename/clear an admin-assigned one. The + // guard is repeated inside each write's WHERE so a lock applied between + // this read and the write still wins. + if (await isLocked(env, session.userId)) return lockedResponse(); + + if (handle === null) { + // Clearing never needs to create a satellite row. Zero changes is normal + // (no row / already clear) unless a lock landed since the read above. + const res = await env.DB.prepare("UPDATE user_preferences SET handle = NULL WHERE user_id = ? AND handle_locked = 0") + .bind(session.userId).run(); + if (res.meta.changes === 0 && await isLocked(env, session.userId)) return lockedResponse(); + return okResponse({ handle: null }); + } + + let changes: number; + try { + const res = await env.DB.prepare( + `INSERT INTO user_preferences (user_id, handle) VALUES (?, ?) + ON CONFLICT(user_id) DO UPDATE SET handle = excluded.handle + WHERE user_preferences.handle_locked = 0`, + ).bind(session.userId, handle).run(); + changes = res.meta.changes; + } catch (err) { + if (isUniqueConstraintError(err)) return errorResponse(Errors.CONFLICT); + throw err; + } + // The upsert always touches one row unless the DO UPDATE's lock guard held. + if (changes === 0) return lockedResponse(); + + return okResponse({ handle }); +} + +async function isLocked(env: Env, userId: string): Promise { + const row = await env.DB.prepare("SELECT handle_locked FROM user_preferences WHERE user_id = ?") + .bind(userId).first<{ handle_locked: number }>(); + return !!row?.handle_locked; +} + +function lockedResponse(): Response { + return Response.json({ ok: false, ...Errors.FORBIDDEN, reason: "locked" }, { status: 403 }); +} diff --git a/packages/api/src/routes/me/update-ink-prefs.test.ts b/packages/api/src/routes/me/update-ink-prefs.test.ts new file mode 100644 index 0000000..2102eb6 --- /dev/null +++ b/packages/api/src/routes/me/update-ink-prefs.test.ts @@ -0,0 +1,122 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleUpdateInkPrefs } from "./update-ink-prefs"; +import type { PlanRow } from "../../account/plan"; + +vi.mock("../../account/requestSession", () => ({ + requireAuthenticatedSession: vi.fn(), +})); + +import { requireAuthenticatedSession } from "../../account/requestSession"; + +const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; + +const inkRow: PlanRow = { + granted_plan: "ink", + granted_plan_expires_at: null, + granted_plan_started_at: 1, + personal_plan: null, + personal_plan_status: null, + personal_plan_started_at: null, + personal_plan_cancel_at: null, + personal_plan_style: null, + personal_presence_color: null, + personal_crit_sparkles: null, +}; + +const freeRow: PlanRow = { ...inkRow, granted_plan: null, granted_plan_started_at: null }; + +function makeEnv(planRow: PlanRow | null) { + const first = vi.fn().mockResolvedValue(planRow); + const run = vi.fn().mockResolvedValue({}); + const bind = vi.fn().mockReturnValue({ first, run }); + const prepare = vi.fn().mockReturnValue({ bind }); + return { + env: { DB: { prepare } } as unknown as Parameters[1], + prepare, + bind, + first, + run, + }; +} + +function req(body: unknown) { + return new Request("http://localhost/update-ink-prefs", { + method: "POST", + headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); +}); + +describe("handleUpdateInkPrefs", () => { + it("returns 401 when the session is invalid", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue( + Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), + ); + const { env } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); + expect(res.status).toBe(401); + }); + + it("rejects an empty body", async () => { + const { env, prepare } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({}), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("rejects a bogus ring style", async () => { + const { env } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({ style: "rainbow" }), env); + expect(res.status).toBe(400); + }); + + it("rejects a non-hex presence colour", async () => { + const { env } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({ presenceColor: "red" }), env); + expect(res.status).toBe(400); + }); + + it("rejects a non-boolean critSparkles", async () => { + const { env } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({ critSparkles: "yes" }), env); + expect(res.status).toBe(400); + }); + + it("returns 403 for a free (non-Ink) user", async () => { + const { env, run } = makeEnv(freeRow); + const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); + expect(res.status).toBe(403); + expect(run).not.toHaveBeenCalled(); + }); + + it("writes a valid style for an Ink user", async () => { + const { env, run, bind } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs(req({ style: "aurora" }), env); + expect(res.status).toBe(200); + const json = (await res.json()) as { data: { style: string | null } }; + expect(json.data.style).toBe("aurora"); + expect(run).toHaveBeenCalledOnce(); + expect(bind).toHaveBeenLastCalledWith("user-1", "aurora"); + }); + + it("persists critSparkles as 0/1", async () => { + const { env, bind } = makeEnv(inkRow); + await handleUpdateInkPrefs(req({ critSparkles: false }), env); + expect(bind).toHaveBeenLastCalledWith("user-1", 0); + }); + + it("writes all three prefs together", async () => { + const { env, bind } = makeEnv(inkRow); + const res = await handleUpdateInkPrefs( + req({ style: "ember", presenceColor: "#aabbcc", critSparkles: true }), + env, + ); + expect(res.status).toBe(200); + expect(bind).toHaveBeenLastCalledWith("user-1", "ember", "#aabbcc", 1); + }); +}); diff --git a/packages/api/src/routes/me/update-ink-prefs.ts b/packages/api/src/routes/me/update-ink-prefs.ts new file mode 100644 index 0000000..dca7df7 --- /dev/null +++ b/packages/api/src/routes/me/update-ink-prefs.ts @@ -0,0 +1,92 @@ +import { requireAuthenticatedSession } from "../../account/requestSession"; +import { okResponse, errorResponse, Errors } from "../../lib"; +import { resolvePersonalPlan, isInkRingStyle, isInkPresenceColor } from "../../account/plan"; +import type { Env } from "../../index"; + +// Patch Ink supporter cosmetic prefs: ring style + presence colour. Both +// fields are optional in the body; pass `null` to reset back to default +// (NULL on the row means "use the deterministic default" - see plan.ts). +// +// Gated on the caller having an active Ink plan via resolvePersonalPlan, so +// expired-grant or canceled-paid users can't keep tweaking. Refusing here +// rather than just hiding the UI in the frontend stops a pre-emptive +// downgrade race (sub canceled mid-session, user submits update before the +// JWT refresh) from silently writing. +export async function handleUpdateInkPrefs(request: Request, env: Env): Promise { + const session = await requireAuthenticatedSession(request, env); + if (session instanceof Response) return session; + + const body = await request.json<{ style?: string | null; presenceColor?: string | null; critSparkles?: boolean | null }>(); + + if (!("style" in body) && !("presenceColor" in body) && !("critSparkles" in body)) return errorResponse(Errors.BAD_REQUEST); + + if ("style" in body && body.style !== null && !isInkRingStyle(body.style)) { + return errorResponse(Errors.BAD_REQUEST); + } + if ("presenceColor" in body && body.presenceColor !== null && !isInkPresenceColor(body.presenceColor)) { + return errorResponse(Errors.BAD_REQUEST); + } + if ("critSparkles" in body && body.critSparkles !== null && typeof body.critSparkles !== "boolean") { + return errorResponse(Errors.BAD_REQUEST); + } + + const planRow = await env.DB.prepare( + `SELECT p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, + b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, + b.personal_plan_cancel_at, + b.granted_plan, b.granted_plan_expires_at, b.granted_plan_started_at + FROM users u + LEFT JOIN user_billing b ON b.user_id = u.id + LEFT JOIN user_preferences p ON p.user_id = u.id + WHERE u.id = ?`, + ).bind(session.userId).first<{ + personal_plan: string | null; + personal_plan_status: string | null; + personal_plan_started_at: number | null; + personal_plan_cancel_at: number | null; + personal_plan_style: string | null; + personal_presence_color: string | null; + personal_crit_sparkles: number | null; + granted_plan: string | null; + granted_plan_expires_at: number | null; + granted_plan_started_at: number | null; + }>(); + if (!planRow) return errorResponse(Errors.NOT_FOUND); + + const resolved = resolvePersonalPlan(planRow); + if (resolved.plan !== "ink") return errorResponse(Errors.FORBIDDEN); + + // Upsert only the touched columns into user_preferences (see update-reading-font.ts + // for the same pattern). + const cols: string[] = []; + const placeholders: string[] = []; + const updates: string[] = []; + const values: unknown[] = []; + if ("style" in body) { + cols.push("personal_plan_style"); placeholders.push("?"); + updates.push("personal_plan_style = excluded.personal_plan_style"); + values.push(body.style ?? null); + } + if ("presenceColor" in body) { + cols.push("personal_presence_color"); placeholders.push("?"); + updates.push("personal_presence_color = excluded.personal_presence_color"); + values.push(body.presenceColor ?? null); + } + if ("critSparkles" in body) { + cols.push("personal_crit_sparkles"); placeholders.push("?"); + updates.push("personal_crit_sparkles = excluded.personal_crit_sparkles"); + // NULL means "use the default" (on). Persist 0/1 for explicit values. + values.push(body.critSparkles === null ? null : body.critSparkles ? 1 : 0); + } + + await env.DB.prepare( + `INSERT INTO user_preferences (user_id, ${cols.join(", ")}) VALUES (?, ${placeholders.join(", ")}) + ON CONFLICT(user_id) DO UPDATE SET ${updates.join(", ")}`, + ).bind(session.userId, ...values).run(); + + return okResponse({ + style: "style" in body ? (body.style ?? null) : resolved.style, + presenceColor: "presenceColor" in body ? (body.presenceColor ?? null) : resolved.presenceColor, + critSparkles: "critSparkles" in body ? (body.critSparkles ?? true) : resolved.critSparkles, + }); +} diff --git a/packages/api/src/routes/me/update-reading-font.test.ts b/packages/api/src/routes/me/update-reading-font.test.ts new file mode 100644 index 0000000..899caa2 --- /dev/null +++ b/packages/api/src/routes/me/update-reading-font.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleUpdateReadingFont } from "./update-reading-font"; + +vi.mock("../../account/requestSession", () => ({ + requireAuthenticatedSession: vi.fn(), +})); + +import { requireAuthenticatedSession } from "../../account/requestSession"; + +const mockSession = { userId: "user-1", email: "test@example.com", expiresAt: Date.now() + 3600_000 }; + +function makeEnv() { + const run = vi.fn().mockResolvedValue({}); + const bind = vi.fn().mockReturnValue({ run }); + const prepare = vi.fn().mockReturnValue({ bind }); + return { + env: { DB: { prepare } } as unknown as Parameters[1], + prepare, + bind, + run, + }; +} + +function req(body: unknown) { + return new Request("http://localhost/update-reading-font", { + method: "POST", + headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); +}); + +describe("handleUpdateReadingFont", () => { + it("returns 401 when session is invalid", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue( + Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), + ); + const { env } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: "mono" }), env); + expect(res.status).toBe(401); + }); + + it("rejects empty body", async () => { + const { env, prepare } = makeEnv(); + const res = await handleUpdateReadingFont(req({}), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("rejects bogus readingFont value", async () => { + const { env, prepare } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: "comic-sans" }), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("rejects bogus editingFont value", async () => { + const { env, prepare } = makeEnv(); + const res = await handleUpdateReadingFont(req({ editingFont: "papyrus" }), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("writes valid readingFont and returns echo", async () => { + const { env, prepare, run, bind } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: "dyslexic" }), env); + expect(res.status).toBe(200); + const json = await res.json() as { ok: boolean; data: { readingFont: string | null } }; + expect(json.ok).toBe(true); + expect(json.data.readingFont).toBe("dyslexic"); + expect(prepare).toHaveBeenCalledWith(expect.stringContaining("reading_font")); + // user_id leads (UPSERT key), then the column values + expect(bind).toHaveBeenCalledWith("user-1", "dyslexic"); + expect(run).toHaveBeenCalledOnce(); + }); + + it("writes both fields when both are present", async () => { + const { env, prepare, bind } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: "sans", editingFont: "mono" }), env); + expect(res.status).toBe(200); + const sql = prepare.mock.calls[0]?.[0] as string; + expect(sql).toContain("reading_font"); + expect(sql).toContain("editing_font"); + expect(bind).toHaveBeenCalledWith("user-1", "sans", "mono"); + }); + + it("writes uiFont when present", async () => { + const { env, prepare, bind } = makeEnv(); + const res = await handleUpdateReadingFont(req({ uiFont: "dyslexic" }), env); + expect(res.status).toBe(200); + expect(prepare.mock.calls[0]?.[0]).toContain("ui_font"); + expect(bind).toHaveBeenCalledWith("user-1", "dyslexic"); + }); + + it("rejects bogus uiFont value", async () => { + const { env, prepare } = makeEnv(); + const res = await handleUpdateReadingFont(req({ uiFont: "wingdings" }), env); + expect(res.status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("writes all three fields together", async () => { + const { env, bind } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: "sans", editingFont: "mono", uiFont: "dyslexic" }), env); + expect(res.status).toBe(200); + expect(bind).toHaveBeenCalledWith("user-1", "sans", "mono", "dyslexic"); + }); + + it("treats null as a reset (NULL on the row)", async () => { + const { env, bind } = makeEnv(); + const res = await handleUpdateReadingFont(req({ readingFont: null }), env); + expect(res.status).toBe(200); + expect(bind).toHaveBeenCalledWith("user-1", null); + }); +}); diff --git a/packages/api/src/routes/me/update-reading-font.ts b/packages/api/src/routes/me/update-reading-font.ts new file mode 100644 index 0000000..28bd044 --- /dev/null +++ b/packages/api/src/routes/me/update-reading-font.ts @@ -0,0 +1,64 @@ +import { requireAuthenticatedSession } from "../../account/requestSession"; +import { okResponse, errorResponse, Errors } from "../../lib"; +import { isFontChoice } from "../../account/fonts"; +import type { Env } from "../../index"; + +// Patch the user's prose-font choices for reading and editing modes. Both +// fields are optional in the body; pass `null` to reset to the default +// (NULL on the row → frontend falls back to the default sans stack). +// +// Unlike update-ink-prefs, this is NOT gated on the Ink plan - OpenDyslexic +// in particular is an accessibility feature, so every user can pick it. +export async function handleUpdateReadingFont(request: Request, env: Env): Promise { + const session = await requireAuthenticatedSession(request, env); + if (session instanceof Response) return session; + + const body = await request.json<{ readingFont?: string | null; editingFont?: string | null; uiFont?: string | null }>(); + + if (!("readingFont" in body) && !("editingFont" in body) && !("uiFont" in body)) return errorResponse(Errors.BAD_REQUEST); + + if ("readingFont" in body && body.readingFont !== null && !isFontChoice(body.readingFont)) { + return errorResponse(Errors.BAD_REQUEST); + } + if ("editingFont" in body && body.editingFont !== null && !isFontChoice(body.editingFont)) { + return errorResponse(Errors.BAD_REQUEST); + } + if ("uiFont" in body && body.uiFont !== null && !isFontChoice(body.uiFont)) { + return errorResponse(Errors.BAD_REQUEST); + } + + // Build an upsert that only touches the columns the caller actually sent. + // INSERT supplies values for those columns (user_id always first); ON CONFLICT + // mirrors the same SET clause so existing rows aren't clobbered for unrelated + // pref columns. + const cols: string[] = []; + const placeholders: string[] = []; + const updates: string[] = []; + const values: unknown[] = []; + if ("readingFont" in body) { + cols.push("reading_font"); placeholders.push("?"); + updates.push("reading_font = excluded.reading_font"); + values.push(body.readingFont ?? null); + } + if ("editingFont" in body) { + cols.push("editing_font"); placeholders.push("?"); + updates.push("editing_font = excluded.editing_font"); + values.push(body.editingFont ?? null); + } + if ("uiFont" in body) { + cols.push("ui_font"); placeholders.push("?"); + updates.push("ui_font = excluded.ui_font"); + values.push(body.uiFont ?? null); + } + + await env.DB.prepare( + `INSERT INTO user_preferences (user_id, ${cols.join(", ")}) VALUES (?, ${placeholders.join(", ")}) + ON CONFLICT(user_id) DO UPDATE SET ${updates.join(", ")}`, + ).bind(session.userId, ...values).run(); + + return okResponse({ + readingFont: "readingFont" in body ? (body.readingFont ?? null) : undefined, + editingFont: "editingFont" in body ? (body.editingFont ?? null) : undefined, + uiFont: "uiFont" in body ? (body.uiFont ?? null) : undefined, + }); +} diff --git a/packages/api/src/routes/me/update-theme.test.ts b/packages/api/src/routes/me/update-theme.test.ts new file mode 100644 index 0000000..b22041d --- /dev/null +++ b/packages/api/src/routes/me/update-theme.test.ts @@ -0,0 +1,99 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleUpdateTheme } from "./update-theme"; + +vi.mock("../../account/requestSession", () => ({ + requireAuthenticatedSession: vi.fn(), +})); + +import { requireAuthenticatedSession } from "../../account/requestSession"; + +const adminSession = { userId: "user-1", email: "a@example.com", expiresAt: Date.now() + 3600_000, isAdmin: true }; + +function makeEnv() { + const run = vi.fn().mockResolvedValue({}); + const bind = vi.fn().mockReturnValue({ run }); + const prepare = vi.fn().mockReturnValue({ bind }); + return { + env: { DB: { prepare } } as unknown as Parameters[1], + prepare, + bind, + run, + }; +} + +function req(body: unknown) { + return new Request("http://localhost/update-theme", { + method: "POST", + headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(requireAuthenticatedSession).mockResolvedValue(adminSession); +}); + +describe("handleUpdateTheme", () => { + it("returns 401 when the session is invalid", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue( + Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), + ); + const { env } = makeEnv(); + expect((await handleUpdateTheme(req({ theme: "dark" }), env)).status).toBe(401); + }); + + // The admin / custom-theming gate intentionally lives in the API worker's + // PATCH /me/theme, NOT in this handler - so a non-admin session still writes + // here. This guards against the handler accidentally growing its own gate. + it("does not self-gate on admin (gate lives in the API worker's PATCH /me/theme)", async () => { + vi.mocked(requireAuthenticatedSession).mockResolvedValue({ ...adminSession, isAdmin: false }); + const { env, prepare } = makeEnv(); + const res = await handleUpdateTheme(req({ theme: "light" }), env); + expect(res.status).toBe(200); + expect(prepare).toHaveBeenCalled(); + }); + + it("rejects a missing / unknown theme", async () => { + const { env, prepare } = makeEnv(); + expect((await handleUpdateTheme(req({}), env)).status).toBe(400); + expect((await handleUpdateTheme(req({ theme: "solarized" }), env)).status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("rejects custom without a valid #rrggbb colour", async () => { + const { env, prepare } = makeEnv(); + expect((await handleUpdateTheme(req({ theme: "custom" }), env)).status).toBe(400); + expect((await handleUpdateTheme(req({ theme: "custom", customColor: "teal" }), env)).status).toBe(400); + expect((await handleUpdateTheme(req({ theme: "custom", customColor: "#abc" }), env)).status).toBe(400); + expect(prepare).not.toHaveBeenCalled(); + }); + + it("writes dark and nulls the custom colour", async () => { + const { env, prepare, bind, run } = makeEnv(); + const res = await handleUpdateTheme(req({ theme: "dark" }), env); + expect(res.status).toBe(200); + const json = await res.json() as { ok: boolean; data: { theme: string; customColor: string | null } }; + expect(json.ok).toBe(true); + expect(json.data).toEqual({ theme: "dark", customColor: null }); + expect(prepare).toHaveBeenCalledWith(expect.stringContaining("theme_mode")); + expect(bind).toHaveBeenCalledWith("user-1", "dark", null); + expect(run).toHaveBeenCalledOnce(); + }); + + it("writes light and ignores any supplied colour", async () => { + const { env, bind } = makeEnv(); + const res = await handleUpdateTheme(req({ theme: "light", customColor: "#2e7d6b" }), env); + expect(res.status).toBe(200); + expect(bind).toHaveBeenCalledWith("user-1", "light", null); + }); + + it("writes custom with a normalised (lower-cased) colour", async () => { + const { env, bind } = makeEnv(); + const res = await handleUpdateTheme(req({ theme: "custom", customColor: "#2E7D6B" }), env); + expect(res.status).toBe(200); + const json = await res.json() as { data: { theme: string; customColor: string | null } }; + expect(json.data).toEqual({ theme: "custom", customColor: "#2e7d6b" }); + expect(bind).toHaveBeenCalledWith("user-1", "custom", "#2e7d6b"); + }); +}); diff --git a/packages/api/src/routes/me/update-theme.ts b/packages/api/src/routes/me/update-theme.ts new file mode 100644 index 0000000..241d686 --- /dev/null +++ b/packages/api/src/routes/me/update-theme.ts @@ -0,0 +1,33 @@ +import { requireAuthenticatedSession } from "../../account/requestSession"; +import { okResponse, errorResponse, Errors } from "../../lib"; +import { isThemeMode, isHexColor } from "../../account/theme"; +import type { Env } from "../../index"; + +// Sets the user's site theme (dark / light / custom). Available to any +// authenticated user - callers are responsible for Flagship flag gating. +// +// `customColor` is only persisted for the 'custom' mode; any other mode nulls +// it so a stale colour doesn't linger and re-apply if the user flips back to +// custom later. Both columns are written every time (single radio on the UI), +// so no partial-column upsert juggling like update-reading-font. +export async function handleUpdateTheme(request: Request, env: Env): Promise { + const session = await requireAuthenticatedSession(request, env); + if (session instanceof Response) return session; + + const body = await request.json<{ theme?: unknown; customColor?: unknown }>(); + + if (!isThemeMode(body.theme)) return errorResponse(Errors.BAD_REQUEST); + + let customColor: string | null = null; + if (body.theme === "custom") { + if (!isHexColor(body.customColor)) return errorResponse(Errors.BAD_REQUEST); + customColor = body.customColor.toLowerCase(); + } + + await env.DB.prepare( + `INSERT INTO user_preferences (user_id, theme_mode, theme_custom_color) VALUES (?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET theme_mode = excluded.theme_mode, theme_custom_color = excluded.theme_custom_color`, + ).bind(session.userId, body.theme, customColor).run(); + + return okResponse({ theme: body.theme, customColor }); +} diff --git a/packages/api/src/routes/members.test.ts b/packages/api/src/routes/members.test.ts index 840532a..b10803b 100644 --- a/packages/api/src/routes/members.test.ts +++ b/packages/api/src/routes/members.test.ts @@ -2,6 +2,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { handleMembers } from "./members"; vi.mock("../lib/access", () => ({ resolveRole: vi.fn() })); +// Invite-by-email lookups go to the identity service (account/identity.ts); +// the tests drive its result directly. +vi.mock("../account/identity", () => ({ findUserByEmail: vi.fn() })); + +import { findUserByEmail } from "../account/identity"; import { resolveRole } from "../lib/access"; @@ -18,17 +23,18 @@ function makeEnv(opts?: { lookupStatus?: number; lookupUser?: { userId: string; const bind = vi.fn((...args: unknown[]) => { bindCalls.push(args); return { first, all, run }; }); const prepare = vi.fn((_sql: string) => ({ bind })); const batch = vi.fn((_stmts: unknown[]) => Promise.resolve([])); - const authAll = vi.fn(() => Promise.resolve({ results: [] })); - const authFetch = vi.fn(async () => { + // Stands in for the identity-service lookup (named for the old auth-worker + // fetch it replaced so the assertions below read the same). + const authFetch = vi.mocked(findUserByEmail); + authFetch.mockImplementation(async () => { const status = opts?.lookupStatus ?? 200; - if (status !== 200) return new Response("", { status }); - return Response.json({ ok: true, data: opts?.lookupUser ?? { userId: "invitee-1", email: "b@example.com", name: "Bob" } }, { status: 200 }); + if (status !== 200) return null; + const u = opts?.lookupUser ?? { userId: "invitee-1", email: "b@example.com", name: "Bob" }; + return { id: u.userId, email: u.email, name: u.name }; }); return { env: { DB: { prepare, batch }, - AUTH_DB: { prepare: vi.fn(() => ({ bind: vi.fn(() => ({ all: authAll })) })) }, - AUTH: { fetch: authFetch }, RATE_LIMITER_INVITE_LOOKUP: { limit: vi.fn(async () => ({ success: opts?.rateOk ?? true })) }, } as unknown as Parameters[1], run, diff --git a/packages/api/src/routes/members.ts b/packages/api/src/routes/members.ts index 3b0504e..0c83898 100644 --- a/packages/api/src/routes/members.ts +++ b/packages/api/src/routes/members.ts @@ -1,3 +1,4 @@ +import { findUserByEmail } from "../account/identity"; import { okResponse, errorResponse, Errors, ROLE_RANK, type Role, type Member } from "../lib"; import type { Env } from "../index"; import { resolveRole } from "../lib/access"; @@ -30,7 +31,7 @@ interface MemberPlanInfo { style: string | null; } -// One D1 read against AUTH_DB returns the plan columns for every user +// One D1 read returns the plan columns for every user // id in the list. Empty list short-circuits - D1 doesn't accept zero // placeholders in IN(). Map keys are user ids; values include the // resolved plan plus the chosen ring style so the members list can @@ -40,7 +41,7 @@ export async function loadMemberPlans(env: Env, userIds: string[]): Promise "?").join(","); - const rows = await env.AUTH_DB.prepare( + const rows = await env.DB.prepare( `SELECT u.id, p.personal_plan_style, p.personal_presence_color, p.personal_crit_sparkles, b.personal_plan, b.personal_plan_status, b.personal_plan_started_at, b.personal_plan_cancel_at, @@ -132,24 +133,13 @@ export async function handleMembers( const { success } = await env.RATE_LIMITER_INVITE_LOOKUP.limit({ key: user.userId }); if (!success) return errorResponse(Errors.RATE_LIMITED); - // Look up the user by email from auth worker - const lookupRes = await env.AUTH.fetch("https://auth/lookup", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: body.email }), - }); - - if (!lookupRes.ok) { - if (lookupRes.status === 404) { - return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); - } - return errorResponse(Errors.INTERNAL); + // Look the person up on the identity service (they may never have used + // Annex yet); findUserByEmail mirrors them so the member row has a user. + const invitee = await findUserByEmail(env, String(body.email)); + if (!invitee) { + return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); } - - const lookupData = await lookupRes.json<{ ok: boolean; data?: { userId: string; email: string; name: string } }>(); - if (!lookupData.ok || !lookupData.data) return errorResponse(Errors.INTERNAL); - - const { userId: inviteeId, email: inviteeEmail, name: inviteeName } = lookupData.data; + const { id: inviteeId, email: inviteeEmail, name: inviteeName } = invitee; // Check if already a member (covers the owner case too) const existing = await env.DB.prepare("SELECT id FROM project_members WHERE project_id = ? AND user_id = ?") diff --git a/packages/api/src/routes/organizations.test.ts b/packages/api/src/routes/organizations.test.ts index 328cc2d..77f58ac 100644 --- a/packages/api/src/routes/organizations.test.ts +++ b/packages/api/src/routes/organizations.test.ts @@ -6,6 +6,12 @@ vi.mock("./members", () => ({ loadMemberPlans: vi.fn() })); import { loadMemberPlans } from "./members"; +// Invite-by-email lookups go to the identity service (account/identity.ts); +// the tests drive its result directly. +vi.mock("../account/identity", () => ({ findUserByEmail: vi.fn() })); + +import { findUserByEmail } from "../account/identity"; + const user = { userId: "caller-1", email: "a@example.com" } as unknown as Parameters[2]; function makeEnv(opts?: { lookupStatus?: number; lookupUser?: { userId: string; email: string; name: string }; rateOk?: boolean }) { @@ -17,19 +23,18 @@ function makeEnv(opts?: { lookupStatus?: number; lookupUser?: { userId: string; const run = vi.fn(() => Promise.resolve(runs.shift() ?? { meta: { changes: 1 } })); const bind = vi.fn(() => ({ first, all, run })); const prepare = vi.fn(() => ({ bind })); - const authFetch = vi.fn(async (input: string) => { - // callerDisplayName hits /lookup-by-id; member-invite hits /lookup. - if (String(input).includes("lookup-by-id")) { - return Response.json({ ok: true, data: { name: "Caller Name" } }, { status: 200 }); - } + // Stands in for the identity-service lookup (named for the old auth-worker + // fetch it replaced so the assertions below read the same). + const authFetch = vi.mocked(findUserByEmail); + authFetch.mockImplementation(async () => { const status = opts?.lookupStatus ?? 200; - if (status !== 200) return new Response("", { status }); - return Response.json({ ok: true, data: opts?.lookupUser ?? { userId: "invitee-1", email: "b@example.com", name: "Bob" } }, { status: 200 }); + if (status !== 200) return null; + const u = opts?.lookupUser ?? { userId: "invitee-1", email: "b@example.com", name: "Bob" }; + return { id: u.userId, email: u.email, name: u.name }; }); return { env: { DB: { prepare }, - AUTH: { fetch: authFetch }, RATE_LIMITER_INVITE_LOOKUP: { limit: vi.fn(async () => ({ success: opts?.rateOk ?? true })) }, } as unknown as Parameters[1], run, @@ -75,6 +80,8 @@ describe("handleOrganizations collection", () => { // Real SQLite so the org row + owner membership are checked as one batch. function sqliteEnv() { const { db, sqlite } = createSqliteD1(); + // The owner row's name snapshot comes from the caller's users-mirror row. + sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES ('caller-1', 'a@example.com', 'Caller Name', 't', 0, 0)").run(); const { env } = makeEnv(); return { env: { ...env, DB: db } as typeof env, sqlite }; } diff --git a/packages/api/src/routes/organizations.ts b/packages/api/src/routes/organizations.ts index 7a338bf..ff25110 100644 --- a/packages/api/src/routes/organizations.ts +++ b/packages/api/src/routes/organizations.ts @@ -1,3 +1,4 @@ +import { findUserByEmail } from "../account/identity"; import { okResponse, errorResponse, Errors, ROLE_RANK, type Role, type Session } from "../lib"; import type { Env } from "../index"; import { loadMemberPlans } from "./members"; @@ -34,18 +35,10 @@ export async function getOrgRole(db: D1Database, orgId: string, userId: string): // Mirror projects.ts: resolve the caller's display name from the auth worker, // falling back to their email so a row is always created with *some* name. -async function callerDisplayName(env: Env, request: Request, user: Session): Promise { - const authHeader = request.headers.get("Authorization"); - const lookupRes = await env.AUTH.fetch("https://auth/lookup-by-id", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ userId: user.userId }), - }); - if (lookupRes.ok) { - const data = await lookupRes.json<{ ok: boolean; data?: { name: string } }>(); - if (data.ok && data.data) return data.data.name; - } - return user.email; +async function callerDisplayName(env: Env, user: Session): Promise { + if (user.name) return user.name; + const row = await env.DB.prepare("SELECT name FROM users WHERE id = ?").bind(user.userId).first<{ name: string }>(); + return row?.name ?? user.email; } export async function handleOrganizations( @@ -82,7 +75,7 @@ export async function handleOrganizations( if (!body.name || !body.name.trim()) return errorResponse(Errors.BAD_REQUEST); const name = body.name.trim(); - const ownerName = await callerDisplayName(env, request, user); + const ownerName = await callerDisplayName(env, user); const id = crypto.randomUUID(); const now = new Date().toISOString(); // One batch so a failed member insert can't leave an ownerless org. @@ -256,20 +249,13 @@ async function handleOrgMembers( const { success } = await env.RATE_LIMITER_INVITE_LOOKUP.limit({ key: user.userId }); if (!success) return errorResponse(Errors.RATE_LIMITED); - const lookupRes = await env.AUTH.fetch("https://auth/lookup", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: body.email }), - }); - if (!lookupRes.ok) { - if (lookupRes.status === 404) { - return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); - } - return errorResponse(Errors.INTERNAL); + // Look the person up on the identity service (they may never have used + // Annex yet); findUserByEmail mirrors them so the member row has a user. + const invitee = await findUserByEmail(env, String(body.email)); + if (!invitee) { + return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); } - const lookupData = await lookupRes.json<{ ok: boolean; data?: { userId: string; email: string; name: string } }>(); - if (!lookupData.ok || !lookupData.data) return errorResponse(Errors.INTERNAL); - const { userId: inviteeId, email: inviteeEmail, name: inviteeName } = lookupData.data; + const { id: inviteeId, email: inviteeEmail, name: inviteeName } = invitee; const existing = await env.DB.prepare("SELECT id FROM organization_members WHERE organization_id = ? AND user_id = ?") .bind(orgId, inviteeId).first(); diff --git a/packages/api/src/routes/projects.test.ts b/packages/api/src/routes/projects.test.ts index dfeb422..48d2c7f 100644 --- a/packages/api/src/routes/projects.test.ts +++ b/packages/api/src/routes/projects.test.ts @@ -17,7 +17,7 @@ import { resolveRole } from "../lib/access"; import { releaseCustomDomain } from "../lib/customDomains"; import { ftsUpsertStatements } from "../lib/fts"; -const user = { userId: "user-1", email: "a@example.com" } as unknown as Parameters[2]; +const user = { userId: "user-1", email: "a@example.com", name: "Owner Name" } as unknown as Parameters[2]; function makeEnv() { const firsts: unknown[] = []; @@ -34,12 +34,10 @@ function makeEnv() { const assetsGet = vi.fn(async () => null as unknown); const assetsList = vi.fn(async () => ({ objects: [] as { key: string }[], truncated: false as const, delimitedPrefixes: [] as string[] })); const assetsDelete = vi.fn(async (_keys: string | string[]) => undefined); - const authFetch = vi.fn(async () => Response.json({ ok: true, data: { name: "Owner Name" } }, { status: 200 })); return { env: { DB: { prepare, batch }, ASSETS: { get: assetsGet, put: vi.fn(), delete: assetsDelete, list: assetsList }, - AUTH: { fetch: authFetch }, } as unknown as Parameters[1], run, batch, @@ -48,7 +46,6 @@ function makeEnv() { assetsGet, assetsList, assetsDelete, - authFetch, queueFirst: (v: unknown) => firsts.push(v), queueAll: (v: unknown) => alls.push(v), queueBatch: (v: unknown) => batches.push(v), @@ -222,10 +219,7 @@ describe("handleProjects GET list / POST create", () => { describe("atomicity (real SQLite)", () => { function sqliteEnv() { const { db, sqlite } = createSqliteD1(); - const env = { - DB: db, - AUTH: { fetch: vi.fn(async () => Response.json({ ok: true, data: { name: "Owner Name" } })) }, - } as unknown as Parameters[1]; + const env = { DB: db } as unknown as Parameters[1]; return { env, sqlite }; } const count = (sqlite: ReturnType["sqlite"], sql: string) => @@ -250,22 +244,20 @@ describe("handleProjects GET list / POST create", () => { // Member-insert bind order: (id, project_id, user_id, email, name, role, invited_by, created_at) it("snapshots the owner's display name (not email) into project_members", async () => { - const { env, authFetch, bindCalls } = makeEnv(); + const { env, bindCalls } = makeEnv(); const res = await call(env, "POST", "/projects", { name: "New Site" }); expect(res.status).toBe(201); - // The lookup must carry the caller's userId - an empty body 400s on the - // auth worker and silently falls back to the email (the regression this - // test pins). - const lookupInit = (authFetch.mock.calls[0] as unknown[])[1] as RequestInit | undefined; - expect(JSON.parse(String(lookupInit?.body))).toEqual({ userId: "user-1" }); const memberBind = bindCalls.find(args => args.includes("owner")); expect(memberBind?.[4]).toBe("Owner Name"); }); - it("falls back to the email when the owner-name lookup fails", async () => { - const { env, authFetch, bindCalls } = makeEnv(); - authFetch.mockResolvedValueOnce(new Response("", { status: 500 })); - const res = await call(env, "POST", "/projects", { name: "New Site" }); + it("falls back to the email when the session carries no name", async () => { + const { env, bindCalls } = makeEnv(); + const url = new URL("http://localhost/projects"); + const res = await handleProjects( + new Request(url.toString(), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "New Site" }) }), + env, { ...user, name: undefined }, url, + ); expect(res.status).toBe(201); const memberBind = bindCalls.find(args => args.includes("owner")); expect(memberBind?.[4]).toBe("a@example.com"); diff --git a/packages/api/src/routes/projects.ts b/packages/api/src/routes/projects.ts index 3b4d695..7fa2ccb 100644 --- a/packages/api/src/routes/projects.ts +++ b/packages/api/src/routes/projects.ts @@ -125,18 +125,8 @@ export async function handleProjects( organizationId = body.organizationId; } - // Look up owner's name from auth worker - const authHeader = request.headers.get("Authorization"); - const lookupRes = await env.AUTH.fetch("https://auth/lookup-by-id", { - method: "POST", - headers: { "Content-Type": "application/json", ...(authHeader ? { Authorization: authHeader } : {}) }, - body: JSON.stringify({ userId: user.userId }), - }); - let ownerName = user.email; - if (lookupRes.ok) { - const data = await lookupRes.json<{ ok: boolean; data?: { name: string } }>(); - if (data.ok && data.data) ownerName = data.data.name; - } + // Owner's display name from the users mirror (carried on the session). + const ownerName = user.name || user.email; const id = crypto.randomUUID(); const now = new Date().toISOString(); diff --git a/packages/api/src/routes/reports.test.ts b/packages/api/src/routes/reports.test.ts index e846e7c..62c02a8 100644 --- a/packages/api/src/routes/reports.test.ts +++ b/packages/api/src/routes/reports.test.ts @@ -11,7 +11,7 @@ interface PreparedCall { binds: unknown[]; } -// Handler order: AUTH_DB target-user lookup (.first), then the DB insert +// Handler order: users-mirror target lookup (.first), then the report insert // (.run). Each prepared statement records its SQL + binds. function makeEnv(opts: { targetExists?: boolean; limiterSuccess?: boolean; hasLimiter?: boolean } = {}) { const calls: PreparedCall[] = []; @@ -35,8 +35,10 @@ function makeEnv(opts: { targetExists?: boolean; limiterSuccess?: boolean; hasLi } const limit = vi.fn().mockResolvedValue({ success: opts.limiterSuccess ?? true }); const env = { - AUTH_DB: { prepare: vi.fn((sql: string) => makeStmt(sql, (opts.targetExists ?? true) ? { id: "user-target" } : null)) }, - DB: { prepare: vi.fn((sql: string) => makeStmt(sql, null)) }, + DB: { + prepare: vi.fn((sql: string) => + makeStmt(sql, /FROM users/.test(sql) && (opts.targetExists ?? true) ? { id: "user-target" } : null)), + }, ...(opts.hasLimiter === false ? {} : { RATE_LIMITER_REPORT: { limit } }), } as unknown as Env; return { env, calls, limit }; diff --git a/packages/api/src/routes/reports.ts b/packages/api/src/routes/reports.ts index cfabc06..35ceb7c 100644 --- a/packages/api/src/routes/reports.ts +++ b/packages/api/src/routes/reports.ts @@ -31,8 +31,8 @@ export async function handleUserReport( const note = typeof body.note === "string" ? body.note.trim() : ""; if (!note || note.length > MAX_REPORT_NOTE_LENGTH) return errorResponse(Errors.BAD_REQUEST); - // Target must be a real account (AUTH_DB is read-only by convention). - const target = await env.AUTH_DB.prepare("SELECT id FROM users WHERE id = ?") + // Target must be a real account (one Annex knows: the users mirror). + const target = await env.DB.prepare("SELECT id FROM users WHERE id = ?") .bind(targetUserId).first<{ id: string }>(); if (!target) return errorResponse(Errors.NOT_FOUND); diff --git a/packages/api/src/routes/stripeWebhook.test.ts b/packages/api/src/routes/stripeWebhook.test.ts new file mode 100644 index 0000000..59c0385 --- /dev/null +++ b/packages/api/src/routes/stripeWebhook.test.ts @@ -0,0 +1,392 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleStripeWebhook } from "./stripeWebhook"; + +vi.mock("../account/stripe-client", () => ({ + getStripe: vi.fn(), + getStripeWebhookCryptoProvider: vi.fn().mockReturnValue({}), +})); + +import { getStripe } from "../account/stripe-client"; + +interface MockDB { + prepare: ReturnType; + _runResults: Array<{ meta: { changes: number } } | Error>; + _bindCalls: unknown[][]; + _statements: string[]; +} + +// Returns a sequence-aware D1 mock. Each call to .run() returns the next +// object from `runResults` (default: { meta: { changes: 1 } }); an Error +// entry makes that .run() reject (simulates a transient D1 failure). +// `.first()` always resolves to `firstResult` - used by the idempotency +// dedup check (null/undefined = not yet processed, truthy = duplicate). +function makeDB( + runResults: Array<{ meta: { changes: number } } | Error> = [], + firstResult: unknown = null, +): MockDB { + const _runResults = runResults; + const _bindCalls: unknown[][] = []; + const _statements: string[] = []; + let runIndex = 0; + + const prepare = vi.fn((sql: string) => { + _statements.push(sql); + return { + bind: (...args: unknown[]) => { + _bindCalls.push(args); + return { + run: vi.fn().mockImplementation(() => { + const result = _runResults[runIndex] ?? { meta: { changes: 1 } }; + runIndex += 1; + if (result instanceof Error) return Promise.reject(result); + return Promise.resolve(result); + }), + first: vi.fn().mockImplementation(() => Promise.resolve(firstResult)), + }; + }, + }; + }); + + return { prepare, _runResults, _bindCalls, _statements }; +} + +function makeEnv(db: MockDB) { + return { + DB: db, + STRIPE_SECRET_KEY: "sk_test_xxx", + STRIPE_WEBHOOK_SECRET: "whsec_xxx", + } as unknown as Parameters[1]; +} + +function makeRequest(body: string, sig = "valid-sig") { + return new Request("http://localhost/stripe/webhook", { + method: "POST", + headers: { "stripe-signature": sig, "content-type": "application/json" }, + body, + }); +} + +// subscriptions.retrieve returns the live subscription; by default it matches +// the event payload, `liveSub` overrides it (e.g. a stale event). +function mockConstructEvent(event: unknown, liveSub?: unknown) { + const evObj = (event as { data?: { object?: unknown } } | null)?.data?.object; + vi.mocked(getStripe).mockReturnValue({ + webhooks: { + constructEventAsync: vi.fn().mockResolvedValue(event), + }, + subscriptions: { + retrieve: vi.fn().mockResolvedValue(liveSub ?? evObj), + }, + } as unknown as ReturnType); +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("handleStripeWebhook - signature + idempotency", () => { + it("returns 400 when stripe-signature header is missing", async () => { + const db = makeDB(); + const req = new Request("http://localhost/stripe/webhook", { + method: "POST", + headers: { "content-type": "application/json" }, + body: "{}", + }); + const res = await handleStripeWebhook(req, makeEnv(db)); + expect(res.status).toBe(400); + }); + + it("returns 400 on bad signature", async () => { + vi.mocked(getStripe).mockReturnValue({ + webhooks: { + constructEventAsync: vi.fn().mockRejectedValue(new Error("bad sig")), + }, + } as unknown as ReturnType); + + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(400); + }); + + it("acknowledges duplicate events without processing", async () => { + mockConstructEvent({ id: "evt_1", type: "customer.subscription.updated", data: { object: { id: "sub_1", metadata: {} } } }); + // dedup SELECT returns a row → already processed + const db = makeDB([], { seen: 1 }); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + // Only the dedup lookup should have run - no handler, no marker write + expect(db._statements.length).toBe(1); + expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); + }); +}); + +describe("handleStripeWebhook - checkout.session.completed", () => { + it("links customer + subscription IDs to the user", async () => { + mockConstructEvent({ + id: "evt_2", + type: "checkout.session.completed", + data: { + object: { + id: "cs_1", + client_reference_id: "user-1", + customer: "cus_abc", + subscription: "sub_xyz", + }, + }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + + expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); + expect(db._statements[1]).toContain("INSERT INTO user_billing"); + expect(db._statements[1]).toContain("stripe_customer_id"); + expect(db._statements[1]).toContain("stripe_subscription_id"); + // bind args for the user_billing upsert: userId, customerId, subId + expect(db._bindCalls[1]).toEqual(["user-1", "cus_abc", "sub_xyz"]); + // marker recorded only after the handler succeeded + expect(db._statements[2]).toContain("INSERT OR IGNORE INTO webhook_events"); + }); + + it("acknowledges (200) an event for a user Annex no longer has instead of retrying forever", async () => { + mockConstructEvent({ + id: "evt_gone", + type: "checkout.session.completed", + data: { object: { id: "cs_9", client_reference_id: "deleted-user", customer: "cus_abc", subscription: "sub_xyz" } }, + }); + const db = makeDB([new Error("D1_ERROR: FOREIGN KEY constraint failed: SQLITE_CONSTRAINT")]); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + expect(db._statements[2]).toContain("INSERT OR IGNORE INTO webhook_events"); + }); + + it("still 500s (so Stripe retries) on any other write failure", async () => { + mockConstructEvent({ + id: "evt_blip", + type: "checkout.session.completed", + data: { object: { id: "cs_10", client_reference_id: "user-1", customer: "cus_abc", subscription: "sub_xyz" } }, + }); + const db = makeDB([new Error("D1_ERROR: network blip")]); + expect((await handleStripeWebhook(makeRequest("{}"), makeEnv(db))).status).toBe(500); + }); + + it("ignores events missing client_reference_id", async () => { + mockConstructEvent({ + id: "evt_3", + type: "checkout.session.completed", + data: { object: { id: "cs_2", customer: "cus_abc", subscription: "sub_xyz" } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + // dedup lookup + post-success marker; no user_billing write (no-op) + expect(db._statements.length).toBe(2); + expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); + expect(db._statements[1]).toContain("INSERT OR IGNORE INTO webhook_events"); + }); +}); + +describe("handleStripeWebhook - customer.subscription.created/updated", () => { + const event = { + id: "evt_4", + type: "customer.subscription.created", + data: { + object: { + id: "sub_1", + customer: "cus_1", + status: "active", + metadata: { userId: "user-1" }, + items: { + data: [{ current_period_end: 1_700_000_000 }], + }, + }, + }, + }; + + it("upserts plan, status, period_end, started_at via COALESCE", async () => { + mockConstructEvent(event); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + + expect(db._statements[1]).toContain("INSERT INTO user_billing"); + expect(db._statements[1]).toContain("personal_plan"); + expect(db._statements[1]).toContain("COALESCE(user_billing.personal_plan_started_at"); + + const args = db._bindCalls[1]; + expect(args[0]).toBe("user-1"); // user id (now leads since it's the upsert key) + expect(args[1]).toBe("cus_1"); // customerId + expect(args[2]).toBe("sub_1"); // subscriptionId + expect(args[3]).toBe("ink"); // plan + expect(args[4]).toBe("active"); // status + expect(args[5]).toBe(1_700_000_000_000); // period end (ms) + expect(args[6]).toBeNull(); // cancel_at (null when no cancellation pending) + // args[7] is now (Date.now()) - just check it's a number + expect(typeof args[7]).toBe("number"); + }); + + it("captures cancel_at when subscription is set to cancel at period end", () => { + mockConstructEvent({ + ...event, + data: { + object: { + ...event.data.object, + cancel_at: 1_750_000_000, + cancel_at_period_end: true, + }, + }, + }); + const db = makeDB(); + return handleStripeWebhook(makeRequest("{}"), makeEnv(db)).then(() => { + const args = db._bindCalls[1]; + expect(args[6]).toBe(1_750_000_000_000); // cancel_at in ms (now position 6 - userId leads) + }); + }); + + it("ignores subscription events missing metadata.userId", async () => { + mockConstructEvent({ + ...event, + data: { object: { ...event.data.object, metadata: {} } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + // dedup lookup + post-success marker; no user_billing write (no-op) + expect(db._statements.length).toBe(2); + expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); + expect(db._statements[1]).toContain("INSERT OR IGNORE INTO webhook_events"); + }); + + it("a stale 'active' event whose live subscription is canceled does NOT re-grant Ink", async () => { + // subscription.deleted was processed first; this created/updated arrives late. + mockConstructEvent(event, { ...event.data.object, status: "canceled" }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + expect(db._statements.some(s => s.includes("INSERT INTO user_billing"))).toBe(false); + expect(db._statements[1]).toContain("personal_plan = NULL"); + expect(db._bindCalls[1]).toEqual(["user-1", "sub_1"]); + }); + + it("persists the live status, not the event snapshot", async () => { + mockConstructEvent(event, { ...event.data.object, status: "past_due" }); + const db = makeDB(); + await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(db._bindCalls[1][4]).toBe("past_due"); + }); + + // Price-binding guard: when STRIPE_INK_PRICE_ID is configured, only a + // subscription on that price may grant Ink. + function makeEnvWithInkPrice(db: MockDB, priceId: string) { + return { ...makeEnv(db), STRIPE_INK_PRICE_ID: priceId } as Parameters[1]; + } + + it("grants Ink when a subscription item matches the configured Ink price", async () => { + mockConstructEvent({ + ...event, + data: { object: { ...event.data.object, items: { data: [{ price: { id: "price_ink" }, current_period_end: 1_700_000_000 }] } } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnvWithInkPrice(db, "price_ink")); + expect(res.status).toBe(200); + expect(db._statements[1]).toContain("INSERT INTO user_billing"); + expect(db._bindCalls[1][3]).toBe("ink"); + }); + + it("does NOT grant Ink for a subscription on a different price", async () => { + mockConstructEvent({ + ...event, + data: { object: { ...event.data.object, items: { data: [{ price: { id: "price_other_cheaper" }, current_period_end: 1_700_000_000 }] } } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnvWithInkPrice(db, "price_ink")); + expect(res.status).toBe(200); + // No user_billing write - only dedup lookup + post-success marker. + expect(db._statements.length).toBe(2); + expect(db._statements.some(s => s.includes("INSERT INTO user_billing"))).toBe(false); + }); +}); + +describe("handleStripeWebhook - customer.subscription.deleted", () => { + it("clears plan + sub id, sets status canceled", async () => { + mockConstructEvent({ + id: "evt_5", + type: "customer.subscription.deleted", + data: { object: { id: "sub_1", customer: "cus_1", metadata: { userId: "user-1" } } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + + expect(db._statements[1]).toContain("personal_plan = NULL"); + expect(db._statements[1]).toContain("'canceled'"); + // Guarded on the subscription on record, so a late deletion of an old + // subscription can't cancel a newer one. + expect(db._statements[1]).toContain("(stripe_subscription_id IS NULL OR stripe_subscription_id = ?)"); + expect(db._bindCalls[1]).toEqual(["user-1", "sub_1"]); + }); +}); + +describe("handleStripeWebhook - invoice events", () => { + it("invoice.payment_failed flips status to past_due", async () => { + mockConstructEvent({ + id: "evt_6", + type: "invoice.payment_failed", + data: { object: { id: "in_1", subscription: "sub_1", lines: { data: [] } } }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + + expect(db._statements[1]).toContain("'past_due'"); + expect(db._bindCalls[1]).toEqual(["sub_1"]); + }); + + it("invoice.paid sets status active and refreshes period_end", async () => { + mockConstructEvent({ + id: "evt_7", + type: "invoice.paid", + data: { + object: { + id: "in_2", + subscription: "sub_1", + lines: { data: [{ period: { end: 1_800_000_000 } }] }, + }, + }, + }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + + expect(db._statements[1]).toContain("'active'"); + expect(db._bindCalls[1]).toEqual([1_800_000_000_000, "sub_1"]); + }); +}); + +describe("handleStripeWebhook - idempotency ordering on failure", () => { + const deletedEvent = { + id: "evt_fail", + type: "customer.subscription.deleted", + data: { object: { id: "sub_1", customer: "cus_1", metadata: { userId: "user-1" } } }, + }; + + it("returns 500 and does NOT record the event when the handler throws", async () => { + mockConstructEvent(deletedEvent); + // The handler's UPDATE rejects (transient D1 failure). + const db = makeDB([new Error("d1 unavailable")]); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(500); + // No idempotency marker written → Stripe's redelivery will reprocess. + expect(db._statements.some(s => s.includes("INSERT OR IGNORE INTO webhook_events"))).toBe(false); + }); + + it("records the marker only after the handler succeeds", async () => { + mockConstructEvent({ ...deletedEvent, id: "evt_ok" }); + const db = makeDB(); + const res = await handleStripeWebhook(makeRequest("{}"), makeEnv(db)); + expect(res.status).toBe(200); + expect(db._statements[0]).toContain("SELECT 1 FROM webhook_events"); + // Last statement is the post-success idempotency marker. + expect(db._statements[db._statements.length - 1]).toContain("INSERT OR IGNORE INTO webhook_events"); + }); +}); diff --git a/packages/api/src/routes/stripeWebhook.ts b/packages/api/src/routes/stripeWebhook.ts new file mode 100644 index 0000000..ae789c5 --- /dev/null +++ b/packages/api/src/routes/stripeWebhook.ts @@ -0,0 +1,293 @@ +import type Stripe from "stripe"; +import { Errors, errorResponse } from "../lib"; +import { getStripe, getStripeWebhookCryptoProvider } from "../account/stripe-client"; +import type { BillingEnv as Env } from "./billing"; + +// POST /stripe/webhook +// +// Public endpoint, signature-verified. Bad-signature requests get 400. +// Logical no-ops (event references an unknown user, unsubscribed event +// type, etc.) are acknowledged with 200 - retrying won't help and the +// event is genuinely unprocessable. A *thrown* handler error returns 500 +// so Stripe redelivers; transient failures (a D1 blip) must not be +// silently dropped. +// +// Idempotency: we record event.id in webhook_events only AFTER the +// handler succeeds, and skip early when that row already exists. Stripe +// replays events during outages: a replay after a successful handle is a +// no-op, while a replay after a FAILED handle still reprocesses because +// the marker was never written. +export async function handleStripeWebhook(request: Request, env: Env): Promise { + if (!env.STRIPE_SECRET_KEY || !env.STRIPE_WEBHOOK_SECRET) { + console.error("Stripe webhook reached but STRIPE_SECRET_KEY or STRIPE_WEBHOOK_SECRET is unset"); + return errorResponse(Errors.INTERNAL); + } + + const sig = request.headers.get("stripe-signature"); + if (!sig) return errorResponse(Errors.BAD_REQUEST); + + // MUST read raw body before any .json() - signature is over the bytes. + const rawBody = await request.text(); + + const stripe = getStripe(env.STRIPE_SECRET_KEY); + let event: Stripe.Event; + try { + event = await stripe.webhooks.constructEventAsync( + rawBody, + sig, + env.STRIPE_WEBHOOK_SECRET, + undefined, + getStripeWebhookCryptoProvider(), + ); + } catch (err) { + console.error("Stripe webhook signature verification failed:", err); + return errorResponse(Errors.BAD_REQUEST); + } + + // Idempotency: skip if we've already fully processed this event id. + // The marker is written only after the handler succeeds (below), so a + // failed attempt leaves no row and Stripe's redelivery reprocesses. + const alreadyProcessed = await env.DB.prepare( + "SELECT 1 FROM webhook_events WHERE event_id = ?", + ).bind(event.id).first(); + if (alreadyProcessed) { + return new Response("ok", { status: 200 }); + } + + try { + switch (event.type) { + case "checkout.session.completed": + await handleCheckoutCompleted(env, event.data.object as Stripe.Checkout.Session); + break; + case "customer.subscription.created": + case "customer.subscription.updated": + await handleSubscriptionUpsert(env, event.data.object as Stripe.Subscription); + break; + case "customer.subscription.deleted": + await handleSubscriptionDeleted(env, event.data.object as Stripe.Subscription); + break; + case "invoice.payment_failed": + await handleInvoicePaymentFailed(env, event.data.object as Stripe.Invoice); + break; + case "invoice.paid": + await handleInvoicePaid(env, event.data.object as Stripe.Invoice); + break; + default: + // Unsubscribed event types are fine - Stripe sends what it's + // configured to send. Just acknowledge and move on. + break; + } + } catch (err) { + // Most handler failures are transient (a D1 hiccup, a brief blip). + // We have NOT recorded this event as processed, so 500 and let Stripe + // redeliver - the retry reprocesses cleanly. A deterministic handler + // bug will retry uselessly for Stripe's retry window then give up, + // which is still far better than silently and permanently dropping a + // billing state change. + console.error(`Stripe webhook handler for ${event.type} failed:`, err); + return errorResponse(Errors.INTERNAL); + } + + // Handler succeeded - record the event so any later replay is a no-op. + await env.DB.prepare( + "INSERT OR IGNORE INTO webhook_events (event_id, type, processed_at) VALUES (?, ?, ?)", + ).bind(event.id, event.type, Date.now()).run(); + + return new Response("ok", { status: 200 }); +} + +// checkout.session.completed: links the Stripe customer + subscription +// IDs to our user row. The actual plan flip happens on the subsequent +// customer.subscription.created event. +async function handleCheckoutCompleted(env: Env, sessionObj: Stripe.Checkout.Session): Promise { + const userId = sessionObj.client_reference_id; + if (!userId) { + console.warn("checkout.session.completed missing client_reference_id", sessionObj.id); + return; + } + const customerId = typeof sessionObj.customer === "string" ? sessionObj.customer : sessionObj.customer?.id ?? null; + const subscriptionId = typeof sessionObj.subscription === "string" ? sessionObj.subscription : sessionObj.subscription?.id ?? null; + + if (!customerId) return; + + // The two COALESCE clauses are intentionally asymmetric (preserved from + // pre-split behavior, see migration 0023): + // - stripe_customer_id: prefer the EXISTING value. Once we've linked a + // customer, it should never get overwritten by a later checkout (e.g. a + // duplicate/replayed event), since a different customer id would + // orphan all subsequent invoice lookups. + // - stripe_subscription_id: prefer the INCOMING value. A new checkout + // means a new subscription; the old sub id (if any) is by definition + // stale at this point. + await ignoreUnknownUser(userId, env.DB.prepare( + `INSERT INTO user_billing (user_id, stripe_customer_id, stripe_subscription_id) + VALUES (?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET + stripe_customer_id = COALESCE(user_billing.stripe_customer_id, excluded.stripe_customer_id), + stripe_subscription_id = COALESCE(excluded.stripe_subscription_id, user_billing.stripe_subscription_id)`, + ).bind(userId, customerId, subscriptionId).run()); +} + +// user_billing references the users mirror. An event for a user Annex no +// longer has (their account was deleted) can't be applied and never will be, +// so acknowledge it instead of 500ing into Stripe's retry loop. +async function ignoreUnknownUser(userId: string, write: Promise): Promise { + try { + await write; + } catch (err) { + if (err instanceof Error && err.message.includes("FOREIGN KEY constraint failed")) { + console.warn(`Stripe event for unknown user ${userId}; ignoring`); + return; + } + throw err; + } +} + +// customer.subscription.created/updated: source of truth for plan, +// status, and period end. We resolve the user by metadata.userId +// (stamped during Checkout) so this works even if it arrives before +// checkout.session.completed. +async function handleSubscriptionUpsert(env: Env, eventSub: Stripe.Subscription): Promise { + // Stripe doesn't guarantee delivery order, and a failed delivery is retried + // later - so a stale created/updated (status active) can land AFTER + // subscription.deleted and would re-grant Ink forever. Persist the live + // subscription state, never the event snapshot. A retrieve failure throws, + // which 500s and lets Stripe redeliver. + const sub = await getStripe(env.STRIPE_SECRET_KEY!).subscriptions.retrieve(eventSub.id); + if (sub.status === "canceled" || sub.status === "incomplete_expired") { + await handleSubscriptionDeleted(env, sub); + return; + } + + const userId = sub.metadata?.userId; + if (!userId) { + console.warn("subscription event missing metadata.userId", sub.id); + return; + } + + // Bind the Ink grant to the actual product purchased. Without this, ANY + // priced subscription carrying metadata.userId (a future second product, a + // sub created out-of-band on a different price) would flip the user to Ink. + // Only the configured Ink price grants the plan. (A promo/100%-off code on + // the Ink price itself still counts - that's a legitimate Ink subscription.) + const inkPriceId = env.STRIPE_INK_PRICE_ID; + if (inkPriceId && !sub.items.data.some(item => item.price?.id === inkPriceId)) { + console.warn(`subscription ${sub.id} for user ${userId} is not the Ink price; not granting Ink`); + return; + } + + const customerId = typeof sub.customer === "string" ? sub.customer : sub.customer.id; + // Stripe moved current_period_end from the subscription to per-item in + // newer api versions. Try both - older SDK type defs still expose it + // on Subscription, newer payloads only have it on items. + const periodEnd = + (sub as unknown as { current_period_end?: number }).current_period_end + ?? (sub.items.data[0] as unknown as { current_period_end?: number } | undefined)?.current_period_end + ?? null; + const status = sub.status; + const plan = "ink"; + const now = Date.now(); + + // sub.cancel_at is populated when the user has scheduled a + // cancel-at-period-end via Customer Portal; null when not pending or + // when they've resumed. Status remains 'active' until Stripe actually + // transitions to canceled (which fires subscription.deleted). + const cancelAt = sub.cancel_at ? sub.cancel_at * 1000 : null; + + // Only set personal_plan_started_at if it's not already populated - + // preserves the original supporter date across cancel/resub cycles. + await ignoreUnknownUser(userId, env.DB.prepare( + `INSERT INTO user_billing ( + user_id, stripe_customer_id, stripe_subscription_id, + personal_plan, personal_plan_status, personal_period_end, + personal_plan_cancel_at, personal_plan_started_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET + stripe_customer_id = excluded.stripe_customer_id, + stripe_subscription_id = excluded.stripe_subscription_id, + personal_plan = excluded.personal_plan, + personal_plan_status = excluded.personal_plan_status, + personal_period_end = excluded.personal_period_end, + personal_plan_cancel_at = excluded.personal_plan_cancel_at, + personal_plan_started_at = COALESCE(user_billing.personal_plan_started_at, excluded.personal_plan_started_at)`, + ).bind( + userId, + customerId, + sub.id, + plan, + status, + periodEnd ? periodEnd * 1000 : null, + cancelAt, + now, + ).run()); +} + +// customer.subscription.deleted: clear plan + status. Keep +// stripe_customer_id and personal_plan_started_at so a resubscribe +// preserves the supporter-since date. +async function handleSubscriptionDeleted(env: Env, sub: Stripe.Subscription): Promise { + const userId = sub.metadata?.userId; + if (!userId) return; + + // Only clear the plan when this is the subscription on record (or none is): + // a late deletion of an OLD subscription must not cancel a newer one. + await env.DB.prepare( + `UPDATE user_billing + SET personal_plan = NULL, + personal_plan_status = 'canceled', + personal_period_end = NULL, + personal_plan_cancel_at = NULL, + stripe_subscription_id = NULL + WHERE user_id = ? AND (stripe_subscription_id IS NULL OR stripe_subscription_id = ?)`, + ).bind(userId, sub.id).run(); +} + +// invoice.payment_failed: flip status to past_due. The plan resolver +// keeps perks active during past_due so users get a grace period; the +// frontend banners them to update their payment method. +async function handleInvoicePaymentFailed(env: Env, invoice: Stripe.Invoice): Promise { + const subscriptionId = extractSubscriptionId(invoice); + if (!subscriptionId) return; + + await env.DB.prepare( + `UPDATE user_billing + SET personal_plan_status = 'past_due' + WHERE stripe_subscription_id = ?`, + ).bind(subscriptionId).run(); +} + +// invoice.paid: confirm active status and refresh period_end. This is +// also the renewal heartbeat - fired every billing cycle on success. +async function handleInvoicePaid(env: Env, invoice: Stripe.Invoice): Promise { + const subscriptionId = extractSubscriptionId(invoice); + if (!subscriptionId) return; + + // invoice.lines exposes the period the invoice covers; the latest + // line's period.end is the new period_end. + const lastPeriodEnd = invoice.lines.data + .map(l => l.period?.end ?? 0) + .reduce((a, b) => Math.max(a, b), 0); + + await env.DB.prepare( + `UPDATE user_billing + SET personal_plan_status = 'active', + personal_period_end = ? + WHERE stripe_subscription_id = ?`, + ).bind(lastPeriodEnd ? lastPeriodEnd * 1000 : null, subscriptionId).run(); +} + +// Stripe types put `subscription` in different places across Invoice +// shapes / api versions; this normalizes it to a string id or null. +function extractSubscriptionId(invoice: Stripe.Invoice): string | null { + const direct = (invoice as unknown as { subscription?: string | { id: string } | null }).subscription; + if (typeof direct === "string") return direct; + if (direct && typeof direct === "object" && "id" in direct) return direct.id; + + // Newer api versions may put it on the parent.subscription_details: + const parent = (invoice as unknown as { parent?: { subscription_details?: { subscription?: string | { id: string } } } }).parent; + const fromParent = parent?.subscription_details?.subscription; + if (typeof fromParent === "string") return fromParent; + if (fromParent && typeof fromParent === "object" && "id" in fromParent) return fromParent.id; + + return null; +} diff --git a/packages/api/src/routes/userHandles.test.ts b/packages/api/src/routes/userHandles.test.ts index ed2afcc..bb4c233 100644 --- a/packages/api/src/routes/userHandles.test.ts +++ b/packages/api/src/routes/userHandles.test.ts @@ -1,16 +1,14 @@ import { describe, it, expect } from "vitest"; -import { fileURLToPath } from "node:url"; import { createSqliteD1 } from "../test/sqliteD1"; import { handleUserByHandle } from "./userHandles"; import type { Env } from "../index"; -// AUTH_DB stand-in: real SQLite with every auth migration applied (incl. the -// 0035 handle column + partial unique index). -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../../auth/migrations", import.meta.url)); +// Real SQLite with every main-DB migration applied (users mirror + +// user_preferences with the handle partial unique index). function makeEnv() { - const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); - const user = sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, ?, 'x', datetime('now'))"); + const { db, sqlite } = createSqliteD1(); + const user = sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES (?, ?, ?, datetime('now'), 0, 0)"); user.run("user-1", "a@example.com", "Cubity"); user.run("user-2", "b@example.com", "No Handle"); user.run("user-3", "c@example.com", "Official"); @@ -18,7 +16,7 @@ function makeEnv() { sqlite.prepare("INSERT INTO user_preferences (user_id, bio) VALUES ('user-2', 'hi')").run(); // Reserved name, assignable only by an admin (packages/admin PATCH /:id/handle). sqlite.prepare("INSERT INTO user_preferences (user_id, handle) VALUES ('user-3', 'support')").run(); - return { AUTH_DB: db } as unknown as Env; + return { DB: db } as unknown as Env; } async function resolve(env: Env, raw: string) { diff --git a/packages/api/src/routes/userHandles.ts b/packages/api/src/routes/userHandles.ts index cb74d1e..76017cb 100644 --- a/packages/api/src/routes/userHandles.ts +++ b/packages/api/src/routes/userHandles.ts @@ -1,12 +1,12 @@ import { errorResponse, Errors } from "../lib"; -import { normalizeHandle, handleProblem } from "../../../auth/src/handle"; +import { normalizeHandle, handleProblem } from "../account/handle"; import type { Env } from "../index"; // GET /users/by-handle/:handle - resolve an opt-in profile handle (the // `/@` link) to a user id. Authenticated by the caller (same audience // as GET /users/:userId, which the frontend then loads for the profile body). // -// Reads AUTH_DB directly (read-only). A handle only exists while its owner has +// Reads the users mirror + user_preferences. A handle only exists while its owner has // the profile link switched on, so "not found" covers both "never claimed" // and "turned off". The case-insensitive match comes from storing the handle // pre-normalized; we normalize the lookup the same way. @@ -23,7 +23,7 @@ export async function handleUserByHandle(env: Env, rawHandle: string): Promise { const url = new URL("http://localhost/v1/docs"); - const env = { DB: api.db, AUTH_DB: auth.db } as unknown as Env; + const env = { DB: api.db } as unknown as Env; const res = await handlePublicApi(new Request(url, { headers: { Authorization: `Bearer ${secret}` } }), env, url); expect(res.status).toBe(200); return ((await res.json()) as { data: { id: string }[] }).data.map(d => d.id); @@ -33,10 +30,9 @@ async function listIds(secret: string): Promise { beforeEach(async () => { api = createSqliteD1(); - auth = createSqliteD1(AUTH_MIGRATIONS); seedContentFixture(api.sqlite); for (const u of ["user-1", "editor-1"]) { - auth.sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES (?, ?, ?, 'x', datetime('now'))").run(u, `${u}@example.com`, u); + api.sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES (?, ?, ?, datetime('now'), 0, 0)").run(u, `${u}@example.com`, u); } api.sqlite.prepare( "INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at, accepted) VALUES ('me', 'p1', 'editor-1', 'e@example.com', 'Editor', 'editor', 'owner', datetime('now'), 1)", diff --git a/packages/api/src/routes/v1.key.test.ts b/packages/api/src/routes/v1.key.test.ts index 68fa6e2..a35d079 100644 --- a/packages/api/src/routes/v1.key.test.ts +++ b/packages/api/src/routes/v1.key.test.ts @@ -1,27 +1,22 @@ // GET /v1/key (introspection) and DELETE /v1/key (self-revocation), run -// against real SQLite with every API + auth migration applied, so the actual +// against real SQLite with every main-DB migration applied, so the actual // hash lookup, JOINs and the live-membership floor are exercised end to end. import { describe, it, expect, beforeEach } from "vitest"; -import { fileURLToPath } from "node:url"; import { createSqliteD1, type SqliteD1 } from "../test/sqliteD1"; import { handlePublicApi } from "./v1"; import { hashApiKey } from "../lib/apiKeys"; import type { Env } from "../index"; -const AUTH_MIGRATIONS = fileURLToPath(new URL("../../../auth/migrations", import.meta.url)); - const SECRET = "annx_selfRevokeTestSecret_0123456789abcdefghijk"; const OTHER_SECRET = "annx_otherKeyStaysAlive_0123456789abcdefghijklm"; let api: SqliteD1; -let auth: SqliteD1; let flagEnabled: boolean; function makeEnv(): Env { return { DB: api.db, - AUTH_DB: auth.db, FLAGS: { getBooleanValue: async () => flagEnabled }, } as unknown as Env; } @@ -48,8 +43,7 @@ function revokedAt(id: string): string | null { beforeEach(async () => { flagEnabled = true; api = createSqliteD1(); - auth = createSqliteD1(AUTH_MIGRATIONS); - auth.sqlite.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'u1@example.com', 'User One', 'x', datetime('now'))").run(); + api.sqlite.prepare("INSERT INTO users (id, email, name, created_at, first_seen_at, synced_at) VALUES (?, ?, ?, datetime('now'), 0, 0)").run("u1", "u1@example.com", "User One"); api.sqlite.prepare("INSERT INTO projects (id, name, vanity_slug, owner_id, created_at) VALUES ('p1', 'Handbook', 'handbook', 'u1', datetime('now'))").run(); api.sqlite.prepare( "INSERT INTO project_members (id, project_id, user_id, email, name, role, invited_by, created_at, accepted) VALUES ('m1', 'p1', 'u1', 'u1@example.com', 'User One', 'editor', 'u1', datetime('now'), 1)", @@ -131,7 +125,7 @@ describe("DELETE /v1/key (self-revocation)", () => { it("still works when the owner was removed from the site or suspended", async () => { api.sqlite.prepare("DELETE FROM project_members WHERE id = 'm1'").run(); - auth.sqlite.prepare("UPDATE users SET moderation = -1 WHERE id = 'u1'").run(); + api.sqlite.prepare("UPDATE users SET status = 'disabled' WHERE id = 'u1'").run(); expect((await call("DELETE", "/v1/key", SECRET)).status).toBe(200); expect(revokedAt("k1")).not.toBeNull(); }); diff --git a/packages/api/src/routes/v1.ts b/packages/api/src/routes/v1.ts index f7567c2..d1fff88 100644 --- a/packages/api/src/routes/v1.ts +++ b/packages/api/src/routes/v1.ts @@ -1,3 +1,4 @@ +import { findUserByEmail } from "../account/identity"; import { okResponse, errorResponse, Errors, ROLE_RANK, folderInProject, type Role } from "../lib"; import type { Env } from "../index"; import { resolveAccess } from "../lib/access"; @@ -364,20 +365,13 @@ async function handleV1Members(request: Request, env: Env, auth: ApiKeyAuth, res if (!success) return errorResponse(Errors.RATE_LIMITED); } - const lookupRes = await env.AUTH.fetch("https://auth/lookup", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: body.email }), - }); - if (!lookupRes.ok) { - if (lookupRes.status === 404) { - return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); - } - return errorResponse(Errors.INTERNAL); + // Look the person up on the identity service (they may never have used + // Annex yet); findUserByEmail mirrors them so the member row has a user. + const invitee = await findUserByEmail(env, String(body.email)); + if (!invitee) { + return Response.json({ ok: false, error: "No user found with that email address.", status: 404 }, { status: 404 }); } - const lookupData = await lookupRes.json<{ ok: boolean; data?: { userId: string; email: string; name: string } }>(); - if (!lookupData.ok || !lookupData.data) return errorResponse(Errors.INTERNAL); - const { userId: inviteeId, email: inviteeEmail, name: inviteeName } = lookupData.data; + const { id: inviteeId, email: inviteeEmail, name: inviteeName } = invitee; const existing = await env.DB.prepare("SELECT id FROM project_members WHERE project_id = ? AND user_id = ?") .bind(auth.projectId, inviteeId).first(); diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json index 3263fd8..62b4219 100644 --- a/packages/api/tsconfig.json +++ b/packages/api/tsconfig.json @@ -3,5 +3,5 @@ "compilerOptions": { "types": ["@cloudflare/workers-types", "node"] }, - "include": ["src", "../auth/src/jwt.ts", "../auth/src/session.ts", "../auth/src/lib.ts", "../auth/src/crypto.ts", "../auth/src/plan.ts", "../auth/src/badges.ts", "../auth/src/handle.ts"] + "include": ["src"] } diff --git a/packages/frontend/cloudflare.config.ts b/packages/frontend/cloudflare.config.ts index ae1b6b9..073c50b 100644 --- a/packages/frontend/cloudflare.config.ts +++ b/packages/frontend/cloudflare.config.ts @@ -36,12 +36,6 @@ export default defineConfig({ API: bindings.worker({ worker: "annex-api", }), - // Service binding to the auth worker - used only for Stripe webhook - // forwarding (/stripe/webhook). The auth worker is otherwise reached - // via the api worker's own AUTH binding for authenticated calls. - AUTH: bindings.worker({ - worker: "annex-auth", - }), ASSETS: bindings.assets(), }, }, diff --git a/packages/frontend/worker/index.ts b/packages/frontend/worker/index.ts index ce30f5e..a309e8e 100644 --- a/packages/frontend/worker/index.ts +++ b/packages/frontend/worker/index.ts @@ -7,7 +7,6 @@ import { export interface Env { API: Fetcher; - AUTH: Fetcher; ASSETS: Fetcher; } @@ -365,12 +364,13 @@ export default { try { const url = new URL(request.url); - // Stripe webhook - forwarded to the auth worker via service binding - // verbatim. The auth worker reads the raw body and verifies the - // signature; we must not parse, alter, or strip headers along the - // way or signature verification will fail. + // Stripe webhook - forwarded to the API worker via service binding + // verbatim (billing moved there from the retired annex-auth worker; the + // public URL in the Stripe dashboard is unchanged). The API worker reads + // the raw body and verifies the signature; we must not parse, alter, or + // strip headers along the way or signature verification will fail. if (url.pathname === "/stripe/webhook") { - return await env.AUTH.fetch(new Request("https://auth/stripe/webhook", request)); + return await env.API.fetch(new Request("https://api/stripe/webhook", request)); } // Proxy /api/* to the API worker via Service Binding diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2b64016..73b8bc2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -162,6 +162,9 @@ importers: oauth4webapi: specifier: 3.8.8 version: 3.8.8 + stripe: + specifier: 17.7.0 + version: 17.7.0 y-protocols: specifier: ^1.0.6 version: 1.0.7(yjs@13.6.30) @@ -5339,10 +5342,6 @@ packages: qr.js@0.0.0: resolution: {integrity: sha512-c4iYnWb+k2E+vYpRimHqSu575b1/wKl4XFeJGpFmrJQz5I88v9aY2czh7s0w36srfCM1sXgC/xpoJz5dJfq+OQ==} - qs@6.15.1: - resolution: {integrity: sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==} - engines: {node: '>=0.6'} - qs@6.16.1: resolution: {integrity: sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==} engines: {node: '>=0.6'} @@ -5667,10 +5666,6 @@ packages: shiki@1.29.2: resolution: {integrity: sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg==} - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} - engines: {node: '>= 0.4'} - side-channel-list@1.0.1: resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} @@ -5683,10 +5678,6 @@ packages: resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} engines: {node: '>= 0.4'} - side-channel@1.1.0: - resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} - engines: {node: '>= 0.4'} - side-channel@1.1.1: resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} engines: {node: '>= 0.4'} @@ -11743,10 +11734,6 @@ snapshots: qr.js@0.0.0: {} - qs@6.15.1: - dependencies: - side-channel: 1.1.0 - qs@6.16.1: dependencies: es-define-property: 1.0.1 @@ -12262,11 +12249,6 @@ snapshots: '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.4 - side-channel-list@1.0.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 @@ -12287,14 +12269,6 @@ snapshots: object-inspect: 1.13.4 side-channel-map: 1.0.1 - side-channel@1.1.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - side-channel-list: 1.0.0 - side-channel-map: 1.0.1 - side-channel-weakmap: 1.0.2 - side-channel@1.1.1: dependencies: es-errors: 1.3.0 @@ -12414,7 +12388,7 @@ snapshots: stripe@17.7.0: dependencies: '@types/node': 22.19.15 - qs: 6.15.1 + qs: 6.16.1 style-mod@4.1.3: {} From 3233d73b4ca6eb09f83f796263f5d3e15a3e3c3b Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 22:08:53 -0500 Subject: [PATCH 4/4] feat(frontend): send sign-in and sign-out to auth.cubityfir.st (#24) * feat(frontend): sign in and out through auth.cubityfir.st /login and /register hand off to /api/auth/login (the hosted page links to registration and returns here); /auth/complete redeems the callback's single-use code for the session JWT, which still lives in localStorage. Sign-out revokes the Annex session and continues to the identity service's end-session URL. Local dev keeps the quick-login buttons. Removed the pages and helpers that moved to auth.cubityfir.st (login, register, check/verify email, OAuth authorize, 2FA prompts, passkeys, pending OAuth) and the security parts of account settings (password, email change, TOTP, passkeys, sessions, delete account); settings now links to the identity service's account and security pages, and email and display name are read-only. /oauth/authorize redirects to the identity service, query string included (frontend worker and SPA). Dropped the now-unused zxcvbn, react-qr-code, @simplewebauthn/browser and Turnstile script. * chore(auth): retire annex-auth's OIDC provider after the cutover auth.cubityfir.st is now the cubityfirst-auth worker's Custom Domain. Remove annex-auth's two auth.cubityfir.st zone routes (a deploy that kept them would try to re-add routes on a hostname another Worker owns) and the now-unreachable provider: /oauth/{authorize,token,userinfo,jwks}, /.well-known/openid-configuration, the /admin/oauth/clients management handlers, OIDC_ISSUER/OIDC_AUTHORIZE_URL, RATE_LIMITER_OIDC and the OIDC_PRIVATE_KEY secret. The scheduled sweep stays. Docs, memories and the key/client helper scripts that described Annex as the provider are replaced by a pointer to auth.cubityfir.st. Touches only packages/auth, docs, memories, scripts and CLAUDE.md, so it can be cherry-picked onto main and shipped with the next annex-auth deploy. * feat(admin): admin panel signs in through auth.cubityfir.st; sync account deletions (#25) * feat(admin): sign in to the admin panel through auth.cubityfir.st The admin panel is its own first-party OIDC client (scopes openid profile email roles; sign-in requires the admin role, re-checked live via the identity service). It reuses the API worker's sign-in flow (now a shared AuthFlow: login/callback/exchange/logout) with an 'admin' session kind, and server-side OIDC requests go over the IDENTITY_OIDC service binding. Removed what moved to auth.cubityfir.st: the docs-app handoff, the OAuth clients tab, and account moderation (disable/suspend/re-enable, force password change). Standing shows as read-only from the users mirror, with a live refresh in user details and links to manage the account there. Delayed deletion now deletes Annex data only: scheduling blocks the person from Annex, the cron removes sites/orgs the operator confirmed, Stripe, memberships, billing, preferences and sessions, and marks the schedule completed. The users row and schedule stay, so they remain blocked until the identity account is deleted on auth.cubityfir.st. All admin data now lives in cubedocs-main; no AUTH_DB or AUTH binding. * feat(api): sync account deletions from auth.cubityfir.st An hourly cron polls IdentityService.listDeletedUsers from the newest deletion already recorded in identity_deletions and removes each deleted account's Annex data: the Stripe customer (cancelling Ink), memberships, API keys, doc shares, favourites, avatars and the users mirror row (cascading sessions, billing, preferences and any admin deletion). Sites and organizations they owned are kept with their owner rows and listed in the admin panel's Projects page for an operator to review. Failures (e.g. Stripe) stay pending with last_error and retry hourly. Drops cleanupDeletedAccount, which deleted owned sites and had no caller left after DELETE /me moved to the identity service. * chore(oidc): remove annex-auth, harden the client after review, port e2e to the new sign-in (#26) * chore: remove packages/auth (annex-auth) now that nothing depends on it Identity lives on auth.cubityfir.st and everything Annex-specific moved into the api worker, so the annex-auth worker package goes: root dev/build/deploy/typecheck/test scripts, the auth migrations step, d1-local's "auth" database and e2e's auth-DB calls (account data is in cubedocs-main now). The cubedocs-auth schema survives as a fixture for the one-time import script. Admin + admin-frontend tests join the root `pnpm test`, and `dev:stripe` forwards to the api worker. Adds e2e/signIn.ts (dev quick-login) for porting the e2e suites, which still drive Annex's old registration and login forms. * docs: describe Annex as a client of auth.cubityfir.st CLAUDE.md's auth section, schema notes, admin deletion, worker config and local-dev notes now describe the OIDC client model: Annex sessions and the users mirror in cubedocs-main, the IDENTITY RPC and IDENTITY_OIDC bindings (and why same-zone fetches must use the binding), the deletion sync, and the e2e suites that still need porting. New memories/Identity-Client.md covers the flow, client registration and the cutover steps; .dev.vars.example files show how to point local dev at a local identity worker. Ink-Stripe, Api-Keys, Collab, Worktree-Dev, README and CONTRIBUTING drop the auth worker. * fix(oidc): harden sign-in handoff, deletion and billing paths after review - The single-use handoff code now travels only in an HttpOnly, SameSite=Strict cookie (never in a URL), so a crafted /auth/complete link can't sign anyone in (login CSRF). - A recorded or persisted identity deletion wins over the standing cache, the mirror fallback and any in-flight mirror refresh (sessions, API keys, collab); deleted owners' kept member rows are scrubbed. - Admin deletion: the live admin role is required at scheduling and re-checked before execution; the point of no return is tied to the Stripe customer the preflight saw. - Stripe webhook: billing upserts are guarded against tombstones; a blocked event deletes its customer, an unknown user is retried, never cleaned up without evidence. - Invite-by-email no longer falls back to the mirror outside local dev; Stripe customer email follows identity email changes seen by the standing check. - Admin sign-in lands on its deep link; deletion-sync paging can't skip or stall on same-millisecond deletions; import script arg parsing. - Cutover doc: freeze window, Stripe replay, clients disabled until deletions are reconciled against a final export. * fix(oidc): use the registered docs client and its exact post-logout URI Sets OIDC_CLIENT_ID to the client registered at auth.cubityfir.st (oidc_7369d6d5736d2bea35f1ab47). The provider matches post-logout redirect URIs byte for byte and the registration is the bare origin, so the default no longer appends a trailing slash (verified against the live provider: the bare origin is accepted, the slashed form is refused). Adds scripts/oidc-check.mjs: a dev-machine end-to-end check of the registration (real sign-in, code exchange, the worker's id_token checks, claims printed; secret read from the environment, never printed). * fix(oidc): per-attempt handoff cookie and Stripe email sync on every mirror write Each sign-in now gets its own handoff cookie (annex_handoff_), named by a non-secret attempt id the completion page passes back, so two sign-ins finishing at once in one browser each redeem their own session. refreshMirror reads the previous email in the same batch and updates the linked Stripe customer when it changes, so whichever path writes a new address first (sign-in, standing check, invite lookup, admin) keeps receipts in step. * fix(oidc): per-sign-in login-state cookie; reconcile accounts added after the identity import The login-state cookie is now annex_oidc_, so sign-ins started in two tabs before either callback don't overwrite or clear each other's state. The cutover runbook now reconciles additions as well as deletions: accounts registered on the old Annex after the identity service's import must be added there with their original ids before the clients are enabled, or their Annex data is stranded under an id nobody can sign in as. * docs(oidc): freeze old Annex sign-ups before the cutover export * fix(api): keep the deletion-sync cron constant out of the worker entry module workerd loads every named export of the main module as an entrypoint, so exporting the cron string from src/index.ts stopped annex-api from starting. Moved it to lib/identityDeletions.ts, with a test that the entry module exports only handlers and classes. * feat(admin): localhost-only dev quick-login for the admin panel POST /api/dev/quick-login on the admin worker mints an admin dev user and an admin session, gated like the api worker's (DEV_QUICK_LOGIN=true AND a localhost APP_ORIGIN), so the admin e2e suite runs without a local identity service. * test(e2e): sign in with the dev quick login instead of Annex's old forms Every suite now signs in through e2e/signIn.ts (devSignIn); the admin suite uses the admin worker's quick login. Drops the Turnstile mocks and the 2FA, change-email and change-password suites, whose features moved to auth.cubityfir.st. * test(e2e): scope the admin smoke test to this run's user and audit entry * chore(admin): use the registered auth.cubityfir.st client id for the admin panel --- CLAUDE.md | 75 +- CONTRIBUTING.md | 5 +- README.md | 29 +- docs/oauth/CONSUMER_PROMPT.md | 86 - docs/oauth/README.md | 206 +-- e2e/d1Local.ts | 6 +- e2e/global-teardown.ts | 18 +- e2e/signIn.ts | 28 + e2e/tests/2fa.spec.ts | 405 ----- e2e/tests/admin.spec.ts | 111 +- e2e/tests/app.spec.ts | 44 +- e2e/tests/audio-permission-lock.spec.ts | 33 +- e2e/tests/avatar-upload.spec.ts | 37 +- e2e/tests/big-doc.spec.ts | 31 +- e2e/tests/change-email.spec.ts | 176 -- e2e/tests/change-password.spec.ts | 199 --- e2e/tests/collab.spec.ts | 37 +- e2e/tests/excalidraw.spec.ts | 31 +- e2e/tests/export.spec.ts | 31 +- e2e/tests/file-permission-lock.spec.ts | 33 +- e2e/tests/file-settings.spec.ts | 33 +- e2e/tests/image-paste.spec.ts | 31 +- e2e/tests/ink-features.spec.ts | 37 +- e2e/tests/invites.spec.ts | 53 +- e2e/tests/limited-permissions.spec.ts | 51 +- e2e/tests/markdown.spec.ts | 36 +- e2e/tests/orgs.spec.ts | 43 +- e2e/tests/profile-card.spec.ts | 37 +- e2e/tests/publishing.spec.ts | 31 +- e2e/tests/scroll-to-heading.spec.ts | 37 +- memories/Api-Keys.md | 12 +- memories/Collab.md | 2 +- memories/Identity-Client.md | 148 ++ memories/Ink-Stripe.md | 20 +- memories/Oidc-Provider.md | 72 - memories/Worktree-Dev.md | 4 +- package.json | 14 +- packages/admin/.dev.vars.example | 23 + packages/admin/cloudflare.config.ts | 72 +- packages/admin/frontend/src/App.test.tsx | 36 +- packages/admin/frontend/src/App.tsx | 39 +- .../projects/OrphanedOwnershipCard.tsx | 89 + .../users/BulkDeleteUsersDialog.test.tsx | 2 +- .../users/BulkDeleteUsersDialog.tsx | 14 +- .../users/BulkDisableUsersDialog.tsx | 114 -- .../src/components/users/UserDetailsPanel.tsx | 57 +- .../frontend/src/components/users/UserRow.tsx | 334 +--- packages/admin/frontend/src/lib/api.test.ts | 12 +- packages/admin/frontend/src/lib/api.ts | 209 +-- .../admin/frontend/src/lib/handoff.test.ts | 54 - packages/admin/frontend/src/lib/handoff.ts | 42 - .../admin/frontend/src/lib/moderation.test.ts | 26 - packages/admin/frontend/src/lib/moderation.ts | 26 +- .../admin/frontend/src/lib/signIn.test.ts | 38 + packages/admin/frontend/src/lib/signIn.ts | 65 + .../src/pages/AuthCallbackPage.test.tsx | 72 +- .../frontend/src/pages/AuthCallbackPage.tsx | 83 +- .../admin/frontend/src/pages/LoginPage.tsx | 9 +- .../src/pages/OAuthClientsPage.test.tsx | 44 - .../frontend/src/pages/OAuthClientsPage.tsx | 603 ------- .../admin/frontend/src/pages/ProjectsPage.tsx | 6 + .../admin/frontend/src/pages/UsersPage.tsx | 69 +- packages/admin/src/audit.test.ts | 10 +- packages/admin/src/audit.ts | 4 +- packages/admin/src/auth.test.ts | 17 +- packages/admin/src/auth.ts | 35 +- packages/admin/src/index.test.ts | 139 +- packages/admin/src/index.ts | 102 +- .../admin/src/lib/userDeletion.sqlite.test.ts | 342 ++-- packages/admin/src/lib/userDeletion.test.ts | 128 +- packages/admin/src/lib/userDeletion.ts | 102 +- packages/admin/src/routes/audit.test.ts | 7 +- packages/admin/src/routes/audit.ts | 4 +- packages/admin/src/routes/oauth.test.ts | 124 -- packages/admin/src/routes/oauth.ts | 108 -- .../src/routes/projects.orphaned.test.ts | 33 + packages/admin/src/routes/projects.ts | 48 +- packages/admin/src/routes/reports.test.ts | 50 +- packages/admin/src/routes/reports.ts | 2 +- packages/admin/src/routes/users.test.ts | 344 ++-- packages/admin/src/routes/users.ts | 397 ++--- packages/admin/tsconfig.json | 2 +- packages/admin/wrangler.config.ts | 2 +- packages/api/.dev.vars.example | 29 + packages/api/cloudflare.config.ts | 15 +- packages/api/src/account/identity.test.ts | 76 + packages/api/src/account/identity.ts | 77 +- packages/api/src/account/session.ts | 3 +- packages/api/src/collab/DocCollabRoom.ts | 5 +- packages/api/src/entrypoint.test.ts | 14 + packages/api/src/index.ts | 14 +- packages/api/src/lib/apiKeys.ts | 3 +- .../api/src/lib/identityDeletions.test.ts | 173 ++ packages/api/src/lib/identityDeletions.ts | 155 ++ packages/api/src/lib/projectDelete.test.ts | 44 +- packages/api/src/lib/projectDelete.ts | 60 +- packages/api/src/routes/auth.test.ts | 107 +- packages/api/src/routes/auth.ts | 174 +- packages/api/src/routes/stripeWebhook.test.ts | 57 +- packages/api/src/routes/stripeWebhook.ts | 47 +- packages/api/wrangler.config.ts | 2 +- packages/auth/cloudflare.config.ts | 133 -- packages/auth/migrations/0001_init.sql | 7 - .../auth/migrations/0002_add_disabled.sql | 1 - packages/auth/migrations/0003_add_totp.sql | 1 - .../auth/migrations/0004_add_webauthn.sql | 17 - .../auth/migrations/0005_add_backup_codes.sql | 8 - .../0006_add_force_password_change.sql | 1 - .../0007_add_user_moderation_events.sql | 13 - .../auth/migrations/0008_add_is_admin.sql | 1 - .../migrations/0009_add_admin_handoffs.sql | 11 - .../0010_add_email_verification.sql | 15 - .../auth/migrations/0011_add_timezone.sql | 1 - .../auth/migrations/0012_add_sessions.sql | 26 - .../migrations/0013_add_change_token_id.sql | 7 - .../migrations/0014_add_stripe_columns.sql | 26 - .../0015_add_personal_plan_cancel_at.sql | 7 - .../0016_add_granted_plan_started_at.sql | 10 - packages/auth/migrations/0017_add_badges.sql | 3 - .../0018_add_ink_cosmetic_prefs.sql | 9 - .../auth/migrations/0019_add_user_bio.sql | 5 - .../migrations/0020_add_reading_fonts.sql | 8 - packages/auth/migrations/0021_add_ui_font.sql | 6 - .../0022_add_personal_crit_sparkles.sql | 9 - .../migrations/0023_split_user_billing.sql | 55 - .../0024_split_user_preferences.sql | 49 - .../auth/migrations/0025_add_theme_prefs.sql | 11 - .../migrations/0026_add_admin_audit_log.sql | 23 - .../0027_add_webauthn_user_index.sql | 6 - .../migrations/0028_add_oauth_clients.sql | 49 - .../migrations/0029_add_totp_replay_guard.sql | 7 - .../0030_add_webauthn_transports.sql | 12 - .../0031_add_users_created_at_index.sql | 4 - .../auth/migrations/0032_add_email_change.sql | 3 - .../0033_index_webauthn_challenge_expiry.sql | 4 - .../migrations/0034_add_user_deletions.sql | 38 - .../auth/migrations/0035_add_user_handle.sql | 18 - .../auth/migrations/0036_perf_indexes.sql | 23 - packages/auth/package.json | 27 - packages/auth/schema.sql | 20 - packages/auth/src/admin-handoff.test.ts | 79 - packages/auth/src/admin-handoff.ts | 86 - packages/auth/src/auth-session.ts | 13 - packages/auth/src/badges.ts | 19 - packages/auth/src/cleanup.sqlite.test.ts | 243 --- packages/auth/src/cleanup.ts | 35 - packages/auth/src/crypto.ts | 10 - packages/auth/src/email.ts | 128 -- packages/auth/src/fonts.test.ts | 23 - packages/auth/src/fonts.ts | 11 - packages/auth/src/handle.test.ts | 35 - packages/auth/src/handle.ts | 41 - packages/auth/src/index.test.ts | 23 - packages/auth/src/index.ts | 342 ---- packages/auth/src/jwt.test.ts | 112 -- packages/auth/src/jwt.ts | 75 - packages/auth/src/lib.test.ts | 42 - packages/auth/src/lib.ts | 94 - packages/auth/src/mfa-enrollment.test.ts | 82 - packages/auth/src/mfa.test.ts | 104 -- packages/auth/src/mfa.ts | 185 -- packages/auth/src/oidc.test.ts | 257 --- packages/auth/src/oidc.ts | 329 ---- packages/auth/src/password.test.ts | 94 - packages/auth/src/password.ts | 88 - packages/auth/src/plan.test.ts | 205 --- packages/auth/src/plan.ts | 115 -- .../src/routes/admin-handoff-exchange.test.ts | 120 -- .../auth/src/routes/admin-handoff-exchange.ts | 78 - .../auth/src/routes/admin-handoff-start.ts | 51 - packages/auth/src/routes/billing.test.ts | 128 -- packages/auth/src/routes/billing.ts | 84 - .../src/routes/change-email-cancel.test.ts | 61 - .../auth/src/routes/change-email-cancel.ts | 16 - .../src/routes/change-email-resend.test.ts | 123 -- .../auth/src/routes/change-email-resend.ts | 50 - packages/auth/src/routes/change-email.test.ts | 279 --- packages/auth/src/routes/change-email.ts | 106 -- .../auth/src/routes/change-password.test.ts | 139 -- packages/auth/src/routes/change-password.ts | 63 - .../auth/src/routes/delete-account.test.ts | 156 -- packages/auth/src/routes/delete-account.ts | 77 - packages/auth/src/routes/dev-quick-login.ts | 45 - .../src/routes/force-change-password.test.ts | 108 -- .../auth/src/routes/force-change-password.ts | 64 - packages/auth/src/routes/login.test.ts | 252 --- packages/auth/src/routes/login.ts | 239 --- packages/auth/src/routes/lookup-by-id.ts | 47 - packages/auth/src/routes/lookup.ts | 15 - .../auth/src/routes/oauth-authorize.test.ts | 149 -- packages/auth/src/routes/oauth-authorize.ts | 136 -- packages/auth/src/routes/oauth-clients.ts | 211 --- .../auth/src/routes/oauth-discovery.test.ts | 32 - packages/auth/src/routes/oauth-discovery.ts | 26 - packages/auth/src/routes/oauth-token.test.ts | 166 -- packages/auth/src/routes/oauth-token.ts | 204 --- .../auth/src/routes/oauth-userinfo.test.ts | 134 -- packages/auth/src/routes/oauth-userinfo.ts | 74 - .../src/routes/passkey-auth-finish.test.ts | 116 -- .../auth/src/routes/passkey-auth-finish.ts | 42 - .../auth/src/routes/passkey-auth-start.ts | 11 - packages/auth/src/routes/register.test.ts | 82 - packages/auth/src/routes/register.ts | 88 - .../auth/src/routes/sessions-list.test.ts | 73 - packages/auth/src/routes/sessions-list.ts | 12 - .../auth/src/routes/sessions-logout.test.ts | 59 - packages/auth/src/routes/sessions-logout.ts | 17 - .../src/routes/sessions-revoke-others.test.ts | 50 - .../auth/src/routes/sessions-revoke-others.ts | 17 - .../auth/src/routes/sessions-revoke.test.ts | 69 - packages/auth/src/routes/sessions-revoke.ts | 23 - .../auth/src/routes/stripe-webhook.test.ts | 370 ---- packages/auth/src/routes/stripe-webhook.ts | 278 --- .../routes/totp-backup-codes-generate.test.ts | 82 - .../src/routes/totp-backup-codes-generate.ts | 66 - packages/auth/src/routes/totp-disable.test.ts | 89 - packages/auth/src/routes/totp-disable.ts | 41 - packages/auth/src/routes/totp-enable.test.ts | 107 -- packages/auth/src/routes/totp-enable.ts | 51 - packages/auth/src/routes/totp-setup.test.ts | 60 - packages/auth/src/routes/totp-setup.ts | 19 - packages/auth/src/routes/totp-status.test.ts | 58 - packages/auth/src/routes/totp-status.ts | 15 - packages/auth/src/routes/update-bio.test.ts | 118 -- packages/auth/src/routes/update-bio.ts | 69 - .../auth/src/routes/update-handle.test.ts | 159 -- packages/auth/src/routes/update-handle.ts | 85 - .../auth/src/routes/update-ink-prefs.test.ts | 122 -- packages/auth/src/routes/update-ink-prefs.ts | 92 - packages/auth/src/routes/update-name.test.ts | 85 - packages/auth/src/routes/update-name.ts | 23 - .../src/routes/update-reading-font.test.ts | 119 -- .../auth/src/routes/update-reading-font.ts | 64 - packages/auth/src/routes/update-theme.test.ts | 99 -- packages/auth/src/routes/update-theme.ts | 33 - .../auth/src/routes/update-timezone.test.ts | 78 - packages/auth/src/routes/update-timezone.ts | 26 - .../src/routes/verify-email-resend.test.ts | 71 - .../auth/src/routes/verify-email-resend.ts | 25 - packages/auth/src/routes/verify-email.test.ts | 204 --- packages/auth/src/routes/verify-email.ts | 80 - packages/auth/src/routes/verify.ts | 16 - .../src/routes/webauthn-auth-finish.test.ts | 79 - .../auth/src/routes/webauthn-auth-finish.ts | 64 - .../src/routes/webauthn-auth-start.test.ts | 73 - .../auth/src/routes/webauthn-auth-start.ts | 19 - .../webauthn-credentials-delete.test.ts | 76 - .../src/routes/webauthn-credentials-delete.ts | 34 - .../routes/webauthn-credentials-list.test.ts | 59 - .../src/routes/webauthn-credentials-list.ts | 14 - .../src/routes/webauthn-register-finish.ts | 76 - .../src/routes/webauthn-register-start.ts | 22 - packages/auth/src/session.ts | 171 -- packages/auth/src/sessions.ts | 165 -- packages/auth/src/stripe-client.ts | 37 - packages/auth/src/theme.test.ts | 41 - packages/auth/src/theme.ts | 20 - packages/auth/src/totp.test.ts | 153 -- packages/auth/src/totp.ts | 87 - packages/auth/src/turnstile.ts | 20 - packages/auth/src/verification.test.ts | 51 - packages/auth/src/verification.ts | 55 - packages/auth/src/webauthn-assertion.test.ts | 129 -- packages/auth/src/webauthn.test.ts | 64 - packages/auth/src/webauthn.ts | 284 --- packages/auth/tsconfig.json | 8 - packages/auth/wrangler.config.ts | 14 - packages/frontend/.env.production | 1 - packages/frontend/cloudflare.config.ts | 3 + packages/frontend/index.html | 1 - packages/frontend/package.json | 6 +- packages/frontend/src/App.tsx | 19 +- .../frontend/src/components/Turnstile.tsx | 140 -- .../frontend/src/components/UserAvatar.tsx | 2 +- .../src/components/UserProfileCard.tsx | 15 +- packages/frontend/src/hooks/use2FA.tsx | 314 ---- packages/frontend/src/layouts/DocsLayout.tsx | 37 +- packages/frontend/src/lib/acknowledgements.ts | 3 - packages/frontend/src/lib/demoServer.test.ts | 31 +- packages/frontend/src/lib/demoServer.ts | 51 +- packages/frontend/src/lib/fonts.ts | 2 +- packages/frontend/src/lib/handle.test.ts | 2 +- packages/frontend/src/lib/handle.ts | 2 +- .../frontend/src/lib/pendingOAuth.test.ts | 56 - packages/frontend/src/lib/pendingOAuth.ts | 53 - packages/frontend/src/lib/signIn.test.ts | 59 + packages/frontend/src/lib/signIn.ts | 80 + packages/frontend/src/lib/theme.ts | 4 +- packages/frontend/src/lib/webauthn.ts | 41 - .../src/pages/AuthCompletePage.test.tsx | 58 + .../frontend/src/pages/AuthCompletePage.tsx | 81 + .../src/pages/CheckEmailPage.test.tsx | 74 - .../frontend/src/pages/CheckEmailPage.tsx | 103 -- .../frontend/src/pages/LoginPage.test.tsx | 103 -- packages/frontend/src/pages/LoginPage.tsx | 876 ---------- .../src/pages/OAuthAuthorizePage.test.tsx | 182 -- .../frontend/src/pages/OAuthAuthorizePage.tsx | 222 --- packages/frontend/src/pages/RegisterPage.tsx | 188 -- packages/frontend/src/pages/SignInPage.tsx | 128 ++ .../frontend/src/pages/UserSettingsPage.tsx | 1528 +---------------- .../src/pages/VerifyEmailPage.test.tsx | 97 -- .../frontend/src/pages/VerifyEmailPage.tsx | 196 --- packages/frontend/worker/customHost.test.ts | 16 +- packages/frontend/worker/index.ts | 18 +- pnpm-lock.yaml | 221 --- scripts/d1-local.mjs | 18 +- scripts/gen-oidc-key.mjs | 57 - scripts/import-auth-data.mjs | 2 +- scripts/migrate.mjs | 12 - scripts/oidc-check.mjs | 70 + scripts/register-oauth-client.mjs | 106 -- 311 files changed, 3334 insertions(+), 21674 deletions(-) delete mode 100644 docs/oauth/CONSUMER_PROMPT.md create mode 100644 e2e/signIn.ts delete mode 100644 e2e/tests/2fa.spec.ts delete mode 100644 e2e/tests/change-email.spec.ts delete mode 100644 e2e/tests/change-password.spec.ts create mode 100644 memories/Identity-Client.md delete mode 100644 memories/Oidc-Provider.md create mode 100644 packages/admin/.dev.vars.example create mode 100644 packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx delete mode 100644 packages/admin/frontend/src/components/users/BulkDisableUsersDialog.tsx delete mode 100644 packages/admin/frontend/src/lib/handoff.test.ts delete mode 100644 packages/admin/frontend/src/lib/handoff.ts create mode 100644 packages/admin/frontend/src/lib/signIn.test.ts create mode 100644 packages/admin/frontend/src/lib/signIn.ts delete mode 100644 packages/admin/frontend/src/pages/OAuthClientsPage.test.tsx delete mode 100644 packages/admin/frontend/src/pages/OAuthClientsPage.tsx delete mode 100644 packages/admin/src/routes/oauth.test.ts delete mode 100644 packages/admin/src/routes/oauth.ts create mode 100644 packages/admin/src/routes/projects.orphaned.test.ts create mode 100644 packages/api/.dev.vars.example create mode 100644 packages/api/src/account/identity.test.ts create mode 100644 packages/api/src/entrypoint.test.ts create mode 100644 packages/api/src/lib/identityDeletions.test.ts create mode 100644 packages/api/src/lib/identityDeletions.ts delete mode 100644 packages/auth/cloudflare.config.ts delete mode 100644 packages/auth/migrations/0001_init.sql delete mode 100644 packages/auth/migrations/0002_add_disabled.sql delete mode 100644 packages/auth/migrations/0003_add_totp.sql delete mode 100644 packages/auth/migrations/0004_add_webauthn.sql delete mode 100644 packages/auth/migrations/0005_add_backup_codes.sql delete mode 100644 packages/auth/migrations/0006_add_force_password_change.sql delete mode 100644 packages/auth/migrations/0007_add_user_moderation_events.sql delete mode 100644 packages/auth/migrations/0008_add_is_admin.sql delete mode 100644 packages/auth/migrations/0009_add_admin_handoffs.sql delete mode 100644 packages/auth/migrations/0010_add_email_verification.sql delete mode 100644 packages/auth/migrations/0011_add_timezone.sql delete mode 100644 packages/auth/migrations/0012_add_sessions.sql delete mode 100644 packages/auth/migrations/0013_add_change_token_id.sql delete mode 100644 packages/auth/migrations/0014_add_stripe_columns.sql delete mode 100644 packages/auth/migrations/0015_add_personal_plan_cancel_at.sql delete mode 100644 packages/auth/migrations/0016_add_granted_plan_started_at.sql delete mode 100644 packages/auth/migrations/0017_add_badges.sql delete mode 100644 packages/auth/migrations/0018_add_ink_cosmetic_prefs.sql delete mode 100644 packages/auth/migrations/0019_add_user_bio.sql delete mode 100644 packages/auth/migrations/0020_add_reading_fonts.sql delete mode 100644 packages/auth/migrations/0021_add_ui_font.sql delete mode 100644 packages/auth/migrations/0022_add_personal_crit_sparkles.sql delete mode 100644 packages/auth/migrations/0023_split_user_billing.sql delete mode 100644 packages/auth/migrations/0024_split_user_preferences.sql delete mode 100644 packages/auth/migrations/0025_add_theme_prefs.sql delete mode 100644 packages/auth/migrations/0026_add_admin_audit_log.sql delete mode 100644 packages/auth/migrations/0027_add_webauthn_user_index.sql delete mode 100644 packages/auth/migrations/0028_add_oauth_clients.sql delete mode 100644 packages/auth/migrations/0029_add_totp_replay_guard.sql delete mode 100644 packages/auth/migrations/0030_add_webauthn_transports.sql delete mode 100644 packages/auth/migrations/0031_add_users_created_at_index.sql delete mode 100644 packages/auth/migrations/0032_add_email_change.sql delete mode 100644 packages/auth/migrations/0033_index_webauthn_challenge_expiry.sql delete mode 100644 packages/auth/migrations/0034_add_user_deletions.sql delete mode 100644 packages/auth/migrations/0035_add_user_handle.sql delete mode 100644 packages/auth/migrations/0036_perf_indexes.sql delete mode 100644 packages/auth/package.json delete mode 100644 packages/auth/schema.sql delete mode 100644 packages/auth/src/admin-handoff.test.ts delete mode 100644 packages/auth/src/admin-handoff.ts delete mode 100644 packages/auth/src/auth-session.ts delete mode 100644 packages/auth/src/badges.ts delete mode 100644 packages/auth/src/cleanup.sqlite.test.ts delete mode 100644 packages/auth/src/cleanup.ts delete mode 100644 packages/auth/src/crypto.ts delete mode 100644 packages/auth/src/email.ts delete mode 100644 packages/auth/src/fonts.test.ts delete mode 100644 packages/auth/src/fonts.ts delete mode 100644 packages/auth/src/handle.test.ts delete mode 100644 packages/auth/src/handle.ts delete mode 100644 packages/auth/src/index.test.ts delete mode 100644 packages/auth/src/index.ts delete mode 100644 packages/auth/src/jwt.test.ts delete mode 100644 packages/auth/src/jwt.ts delete mode 100644 packages/auth/src/lib.test.ts delete mode 100644 packages/auth/src/lib.ts delete mode 100644 packages/auth/src/mfa-enrollment.test.ts delete mode 100644 packages/auth/src/mfa.test.ts delete mode 100644 packages/auth/src/mfa.ts delete mode 100644 packages/auth/src/oidc.test.ts delete mode 100644 packages/auth/src/oidc.ts delete mode 100644 packages/auth/src/password.test.ts delete mode 100644 packages/auth/src/password.ts delete mode 100644 packages/auth/src/plan.test.ts delete mode 100644 packages/auth/src/plan.ts delete mode 100644 packages/auth/src/routes/admin-handoff-exchange.test.ts delete mode 100644 packages/auth/src/routes/admin-handoff-exchange.ts delete mode 100644 packages/auth/src/routes/admin-handoff-start.ts delete mode 100644 packages/auth/src/routes/billing.test.ts delete mode 100644 packages/auth/src/routes/billing.ts delete mode 100644 packages/auth/src/routes/change-email-cancel.test.ts delete mode 100644 packages/auth/src/routes/change-email-cancel.ts delete mode 100644 packages/auth/src/routes/change-email-resend.test.ts delete mode 100644 packages/auth/src/routes/change-email-resend.ts delete mode 100644 packages/auth/src/routes/change-email.test.ts delete mode 100644 packages/auth/src/routes/change-email.ts delete mode 100644 packages/auth/src/routes/change-password.test.ts delete mode 100644 packages/auth/src/routes/change-password.ts delete mode 100644 packages/auth/src/routes/delete-account.test.ts delete mode 100644 packages/auth/src/routes/delete-account.ts delete mode 100644 packages/auth/src/routes/dev-quick-login.ts delete mode 100644 packages/auth/src/routes/force-change-password.test.ts delete mode 100644 packages/auth/src/routes/force-change-password.ts delete mode 100644 packages/auth/src/routes/login.test.ts delete mode 100644 packages/auth/src/routes/login.ts delete mode 100644 packages/auth/src/routes/lookup-by-id.ts delete mode 100644 packages/auth/src/routes/lookup.ts delete mode 100644 packages/auth/src/routes/oauth-authorize.test.ts delete mode 100644 packages/auth/src/routes/oauth-authorize.ts delete mode 100644 packages/auth/src/routes/oauth-clients.ts delete mode 100644 packages/auth/src/routes/oauth-discovery.test.ts delete mode 100644 packages/auth/src/routes/oauth-discovery.ts delete mode 100644 packages/auth/src/routes/oauth-token.test.ts delete mode 100644 packages/auth/src/routes/oauth-token.ts delete mode 100644 packages/auth/src/routes/oauth-userinfo.test.ts delete mode 100644 packages/auth/src/routes/oauth-userinfo.ts delete mode 100644 packages/auth/src/routes/passkey-auth-finish.test.ts delete mode 100644 packages/auth/src/routes/passkey-auth-finish.ts delete mode 100644 packages/auth/src/routes/passkey-auth-start.ts delete mode 100644 packages/auth/src/routes/register.test.ts delete mode 100644 packages/auth/src/routes/register.ts delete mode 100644 packages/auth/src/routes/sessions-list.test.ts delete mode 100644 packages/auth/src/routes/sessions-list.ts delete mode 100644 packages/auth/src/routes/sessions-logout.test.ts delete mode 100644 packages/auth/src/routes/sessions-logout.ts delete mode 100644 packages/auth/src/routes/sessions-revoke-others.test.ts delete mode 100644 packages/auth/src/routes/sessions-revoke-others.ts delete mode 100644 packages/auth/src/routes/sessions-revoke.test.ts delete mode 100644 packages/auth/src/routes/sessions-revoke.ts delete mode 100644 packages/auth/src/routes/stripe-webhook.test.ts delete mode 100644 packages/auth/src/routes/stripe-webhook.ts delete mode 100644 packages/auth/src/routes/totp-backup-codes-generate.test.ts delete mode 100644 packages/auth/src/routes/totp-backup-codes-generate.ts delete mode 100644 packages/auth/src/routes/totp-disable.test.ts delete mode 100644 packages/auth/src/routes/totp-disable.ts delete mode 100644 packages/auth/src/routes/totp-enable.test.ts delete mode 100644 packages/auth/src/routes/totp-enable.ts delete mode 100644 packages/auth/src/routes/totp-setup.test.ts delete mode 100644 packages/auth/src/routes/totp-setup.ts delete mode 100644 packages/auth/src/routes/totp-status.test.ts delete mode 100644 packages/auth/src/routes/totp-status.ts delete mode 100644 packages/auth/src/routes/update-bio.test.ts delete mode 100644 packages/auth/src/routes/update-bio.ts delete mode 100644 packages/auth/src/routes/update-handle.test.ts delete mode 100644 packages/auth/src/routes/update-handle.ts delete mode 100644 packages/auth/src/routes/update-ink-prefs.test.ts delete mode 100644 packages/auth/src/routes/update-ink-prefs.ts delete mode 100644 packages/auth/src/routes/update-name.test.ts delete mode 100644 packages/auth/src/routes/update-name.ts delete mode 100644 packages/auth/src/routes/update-reading-font.test.ts delete mode 100644 packages/auth/src/routes/update-reading-font.ts delete mode 100644 packages/auth/src/routes/update-theme.test.ts delete mode 100644 packages/auth/src/routes/update-theme.ts delete mode 100644 packages/auth/src/routes/update-timezone.test.ts delete mode 100644 packages/auth/src/routes/update-timezone.ts delete mode 100644 packages/auth/src/routes/verify-email-resend.test.ts delete mode 100644 packages/auth/src/routes/verify-email-resend.ts delete mode 100644 packages/auth/src/routes/verify-email.test.ts delete mode 100644 packages/auth/src/routes/verify-email.ts delete mode 100644 packages/auth/src/routes/verify.ts delete mode 100644 packages/auth/src/routes/webauthn-auth-finish.test.ts delete mode 100644 packages/auth/src/routes/webauthn-auth-finish.ts delete mode 100644 packages/auth/src/routes/webauthn-auth-start.test.ts delete mode 100644 packages/auth/src/routes/webauthn-auth-start.ts delete mode 100644 packages/auth/src/routes/webauthn-credentials-delete.test.ts delete mode 100644 packages/auth/src/routes/webauthn-credentials-delete.ts delete mode 100644 packages/auth/src/routes/webauthn-credentials-list.test.ts delete mode 100644 packages/auth/src/routes/webauthn-credentials-list.ts delete mode 100644 packages/auth/src/routes/webauthn-register-finish.ts delete mode 100644 packages/auth/src/routes/webauthn-register-start.ts delete mode 100644 packages/auth/src/session.ts delete mode 100644 packages/auth/src/sessions.ts delete mode 100644 packages/auth/src/stripe-client.ts delete mode 100644 packages/auth/src/theme.test.ts delete mode 100644 packages/auth/src/theme.ts delete mode 100644 packages/auth/src/totp.test.ts delete mode 100644 packages/auth/src/totp.ts delete mode 100644 packages/auth/src/turnstile.ts delete mode 100644 packages/auth/src/verification.test.ts delete mode 100644 packages/auth/src/verification.ts delete mode 100644 packages/auth/src/webauthn-assertion.test.ts delete mode 100644 packages/auth/src/webauthn.test.ts delete mode 100644 packages/auth/src/webauthn.ts delete mode 100644 packages/auth/tsconfig.json delete mode 100644 packages/auth/wrangler.config.ts delete mode 100644 packages/frontend/.env.production delete mode 100644 packages/frontend/src/components/Turnstile.tsx delete mode 100644 packages/frontend/src/hooks/use2FA.tsx delete mode 100644 packages/frontend/src/lib/pendingOAuth.test.ts delete mode 100644 packages/frontend/src/lib/pendingOAuth.ts create mode 100644 packages/frontend/src/lib/signIn.test.ts create mode 100644 packages/frontend/src/lib/signIn.ts delete mode 100644 packages/frontend/src/lib/webauthn.ts create mode 100644 packages/frontend/src/pages/AuthCompletePage.test.tsx create mode 100644 packages/frontend/src/pages/AuthCompletePage.tsx delete mode 100644 packages/frontend/src/pages/CheckEmailPage.test.tsx delete mode 100644 packages/frontend/src/pages/CheckEmailPage.tsx delete mode 100644 packages/frontend/src/pages/LoginPage.test.tsx delete mode 100644 packages/frontend/src/pages/LoginPage.tsx delete mode 100644 packages/frontend/src/pages/OAuthAuthorizePage.test.tsx delete mode 100644 packages/frontend/src/pages/OAuthAuthorizePage.tsx delete mode 100644 packages/frontend/src/pages/RegisterPage.tsx create mode 100644 packages/frontend/src/pages/SignInPage.tsx delete mode 100644 packages/frontend/src/pages/VerifyEmailPage.test.tsx delete mode 100644 packages/frontend/src/pages/VerifyEmailPage.tsx delete mode 100644 scripts/gen-oidc-key.mjs create mode 100644 scripts/oidc-check.mjs delete mode 100644 scripts/register-oauth-client.mjs diff --git a/CLAUDE.md b/CLAUDE.md index f91a8cd..1c74390 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 7ce73fb..4e674a0 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 923c9eb..7eac196 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 5a6b5f1..0000000 --- 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 1cd406d..0951283 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 51b3dbc..2e99192 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 cd31c22..c37657a 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 0000000..66deb53 --- /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 eab11f0..0000000 --- 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 a9d1840..fb4afb9 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 4baaa4e..1159ec9 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 f8da063..a91f349 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 9fd2b00..1bb161d 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 b5e15f0..1afecd6 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 d247587..0000000 --- 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 8103031..0000000 --- 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 04e746c..f40958b 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 e94834b..0a4e829 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 c8937ec..48bcf55 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 a199c2d..6383201 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 bc1e378..6c29f11 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 cf8a57e..12c702d 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 75baee6..be053f6 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 23e2809..3ea93d0 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 b7a0381..2bd3eb0 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 6b7273e..41f77db 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 1f6d980..c4f0f9f 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 6e407cd..f06768b 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 57127c5..2cacc94 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 cedc045..f98149f 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 6b04eff..8bff2a7 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 9689848..3c703a8 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 0000000..75c35b4 --- /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 898b6e4..03804d9 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 d1840e1..0000000 --- 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 43d7de2..5b7799a 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 502a1a3..c57386c 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 0000000..aeb504c --- /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 8495fa5..28d9b14 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 91c2f18..ec20332 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 0a86c38..d5b78b6 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 0000000..ef61e7e --- /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 7a1eaaf..bc05b82 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 e8a0e76..7492a3f 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 efc799c..0000000 --- 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.`} - - - -
- -