From d00a8b6d03f5386f3812a2bda55918952f9e7421 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:32:47 +0000 Subject: [PATCH 1/3] 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. --- 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 -- .../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 +- .../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 | 2 +- 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 | 1526 +---------------- .../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 | 35 - 34 files changed, 545 insertions(+), 4270 deletions(-) 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 diff --git a/packages/frontend/.env.production b/packages/frontend/.env.production deleted file mode 100644 index 8e3dca0b..00000000 --- a/packages/frontend/.env.production +++ /dev/null @@ -1 +0,0 @@ -VITE_TURNSTILE_SITE_KEY=0x4AAAAAACrP1w2n0fI7-cJz diff --git a/packages/frontend/cloudflare.config.ts b/packages/frontend/cloudflare.config.ts index 073c50b1..73b47a46 100644 --- a/packages/frontend/cloudflare.config.ts +++ b/packages/frontend/cloudflare.config.ts @@ -37,6 +37,9 @@ export default defineConfig({ worker: "annex-api", }), ASSETS: bindings.assets(), + // Identity service public origin: /oauth/authorize redirects here (the + // authorization endpoint moved off this app origin). + IDENTITY_ORIGIN: bindings.text("https://auth.cubityfir.st"), }, }, }); diff --git a/packages/frontend/index.html b/packages/frontend/index.html index d6fd6be0..46f3f6ca 100644 --- a/packages/frontend/index.html +++ b/packages/frontend/index.html @@ -23,7 +23,6 @@ -
diff --git a/packages/frontend/package.json b/packages/frontend/package.json index 96049edf..1035c50a 100644 --- a/packages/frontend/package.json +++ b/packages/frontend/package.json @@ -32,7 +32,6 @@ "@radix-ui/react-separator": "^1.1.0", "@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-tooltip": "^1.1.0", - "@simplewebauthn/browser": "^9.0.0", "@tailwindcss/typography": "^0.5.19", "class-variance-authority": "^0.7.0", "clsx": "^2.1.0", @@ -51,7 +50,6 @@ "react-dom": "^19.0.0", "react-force-graph-2d": "^1.29.1", "react-markdown": "^10.1.0", - "react-qr-code": "^2.0.15", "react-resizable-panels": "^4", "react-router-dom": "^6.26.0", "remark-breaks": "^4.0.0", @@ -64,8 +62,7 @@ "world-atlas": "^2.0.2", "y-codemirror.next": "^0.3.5", "y-protocols": "^1.0.6", - "yjs": "^13.6.0", - "zxcvbn": "^4.4.2" + "yjs": "^13.6.0" }, "devDependencies": { "@cloudflare/workers-types": "^4.0.0", @@ -80,7 +77,6 @@ "@types/react-dom": "^19.0.0", "@types/topojson-client": "^3.1.5", "@types/topojson-specification": "^1.0.5", - "@types/zxcvbn": "^4.4.5", "@vitejs/plugin-react": "^4.3.0", "cf": "1.0.0-beta.26", "jsdom": "^25.0.0", diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx index 92293c2e..cab9869e 100644 --- a/packages/frontend/src/App.tsx +++ b/packages/frontend/src/App.tsx @@ -3,12 +3,10 @@ import { Routes, Route, Navigate, useLocation, useParams, type Location } from " import { applyThemeToRoot, pathUsesUserTheme, DEFAULT_THEME_PREFS } from "@/lib/theme"; import { DocsLayout } from "./layouts/DocsLayout"; import { LandingPage } from "./pages/LandingPage"; -import { LoginPage } from "./pages/LoginPage"; -import { OAuthAuthorizePage } from "./pages/OAuthAuthorizePage"; -import { RegisterPage } from "./pages/RegisterPage"; -import { CheckEmailPage } from "./pages/CheckEmailPage"; +import { SignInPage } from "./pages/SignInPage"; +import { AuthCompletePage, OAuthAuthorizeRedirect } from "./pages/AuthCompletePage"; import { DemoPage } from "./pages/DemoPage"; -import { VerifyEmailPage } from "./pages/VerifyEmailPage"; +import { IDENTITY_ORIGIN } from "./lib/signIn"; import { DashboardPage } from "./pages/DashboardPage"; import { ProjectPage } from "./pages/ProjectPage"; import { DocPage } from "./pages/DocPage"; @@ -69,12 +67,13 @@ export function App() { } /> - } /> - } /> - } /> - } /> + {/* Accounts live on auth.cubityfir.st: /login and /register hand off + to it, and /auth/complete finishes the round trip. */} + } /> + } /> + } /> + } /> } /> - } /> }> } /> } /> diff --git a/packages/frontend/src/components/Turnstile.tsx b/packages/frontend/src/components/Turnstile.tsx deleted file mode 100644 index fb16e804..00000000 --- a/packages/frontend/src/components/Turnstile.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"; -import { AlertTriangle } from "lucide-react"; -import { Button } from "@/components/ui/button"; - -const TURNSTILE_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js"; -// How long to wait for the challenge script before telling the user it failed -// (it never arrives when a content blocker eats it). -const LOAD_TIMEOUT_MS = 8000; - -declare global { - interface Window { - turnstile: { - render: ( - container: HTMLElement, - options: { - sitekey: string; - callback: (token: string) => void; - "expired-callback"?: () => void; - "error-callback"?: () => void; - theme?: "light" | "dark" | "auto"; - size?: "normal" | "flexible" | "compact"; - }, - ) => string; - reset: (widgetId: string) => void; - remove: (widgetId: string) => void; - }; - } -} - -interface TurnstileProps { - onVerify: (token: string) => void; - onExpire?: () => void; -} - -export interface TurnstileHandle { - reset: () => void; -} - -export const Turnstile = forwardRef(function Turnstile( - { onVerify, onExpire }, - ref, -) { - const containerRef = useRef(null); - const widgetIdRef = useRef(null); - const onVerifyRef = useRef(onVerify); - const onExpireRef = useRef(onExpire); - onVerifyRef.current = onVerify; - onExpireRef.current = onExpire; - const [failed, setFailed] = useState(false); - const [attempt, setAttempt] = useState(0); - - // Turnstile tokens are single-use at siteverify, so a failed submit must - // re-run the challenge. reset() replays it and fires the callback with a - // fresh token. - useImperativeHandle(ref, () => ({ - reset() { - if (widgetIdRef.current) { - window.turnstile.reset(widgetIdRef.current); - } - }, - }), []); - - useEffect(() => { - const sitekey = import.meta.env.VITE_TURNSTILE_SITE_KEY as string; - let intervalId: ReturnType | null = null; - const startedAt = Date.now(); - - // render() throws on a bad/missing sitekey; never let that blank the page. - function render() { - if (!containerRef.current) return; - try { - widgetIdRef.current = window.turnstile.render(containerRef.current, { - sitekey, - callback: (token) => onVerifyRef.current(token), - "expired-callback": () => onExpireRef.current?.(), - "error-callback": () => onExpireRef.current?.(), - theme: "dark", - size: "flexible", - }); - } catch (err) { - console.error("Turnstile failed to render", err); - setFailed(true); - } - } - - // A retry after the script was blocked asks for it again. - if (attempt > 0 && !window.turnstile) { - const script = document.createElement("script"); - script.src = TURNSTILE_SRC; - script.async = true; - document.head.appendChild(script); - } - - if (window.turnstile) { - render(); - } else { - intervalId = setInterval(() => { - if (window.turnstile) { - clearInterval(intervalId!); - intervalId = null; - render(); - } else if (Date.now() - startedAt > LOAD_TIMEOUT_MS) { - clearInterval(intervalId!); - intervalId = null; - setFailed(true); - } - }, 100); - } - - return () => { - if (intervalId !== null) clearInterval(intervalId); - if (widgetIdRef.current) { - window.turnstile.remove(widgetIdRef.current); - widgetIdRef.current = null; - } - }; - }, [attempt]); - - if (failed) { - return ( -
-
- ); - } - - return
; -}); diff --git a/packages/frontend/src/components/UserProfileCard.tsx b/packages/frontend/src/components/UserProfileCard.tsx index 4ea4b9db..af611dc1 100644 --- a/packages/frontend/src/components/UserProfileCard.tsx +++ b/packages/frontend/src/components/UserProfileCard.tsx @@ -1,4 +1,5 @@ import { useState, useEffect } from "react"; +import { signOut } from "@/lib/signIn"; import { ROLE_BADGE_CLASSES } from "@/lib/roleStyles"; import { useNavigate, useLocation } from "react-router-dom"; import { @@ -341,7 +342,7 @@ export function UserProfileCard({ userId, name, children, open: controlledOpen, - )} - {totp && ( - - )} - {totp && ( - - )} -
- ) : mode === "totp" ? ( -
-
- - { setCode(v); setFieldError(null); }} - autoComplete="one-time-code" - autoFocus - > - - - - - - - - - - {fieldError &&

{fieldError}

} -
-
- ) : mode === "webauthn" ? ( -
- {webauthnStatus === "waiting" && !fieldError ? ( -

- Touch your security key when it flashes… -

- ) : ( - <> - {fieldError &&

{fieldError}

} - - - )} -
- ) : ( -
-
- - { setCode(e.target.value); setFieldError(null); }} - placeholder="XXXXX-XXXXX" - autoFocus - autoComplete="off" - spellCheck={false} - /> - {fieldError &&

{fieldError}

} -
-
- )} - - - - {mode !== "pick" && (totp || webauthn) && ( - - )} - {(mode === "totp" || mode === "backup") && ( - - )} - - - - ); - - // `active` lets a parent dialog know the 2FA dialog is stacked on top of it. - // The two are sibling Radix modals, so when this one opens and takes focus, - // the parent would otherwise treat that as an outside interaction, dismiss - // itself (resetting its form), and the resulting focus shuffle can knock - // this dialog down too. Parents guard onOpenChange / onInteractOutside / - // onFocusOutside with it. - return { runWithTwoFA, twoFADialog, busy, active: open }; -} diff --git a/packages/frontend/src/layouts/DocsLayout.tsx b/packages/frontend/src/layouts/DocsLayout.tsx index 31275bfd..18ad8d0a 100644 --- a/packages/frontend/src/layouts/DocsLayout.tsx +++ b/packages/frontend/src/layouts/DocsLayout.tsx @@ -16,6 +16,7 @@ import { Kbd } from "@/components/ui/kbd"; import { clearToken, getToken } from "@/lib/auth"; import { isDemoMode, exitDemoMode } from "@/lib/demo"; import { apiFetch, apiFetchJson } from "@/lib/apiFetch"; +import { signOut as signOutEverywhere } from "@/lib/signIn"; import { type FontChoice, DEFAULT_READING_FONT, DEFAULT_EDITING_FONT, DEFAULT_UI_FONT, resolveFontChoice, readFontPrefsCookie, writeFontPrefsCookie, applyFontVarsToRoot } from "@/lib/fonts"; import { type ThemeMode, resolveThemeMode, readThemePrefsCookie, writeThemePrefsCookie, applyThemeToRoot } from "@/lib/theme"; import { @@ -383,7 +384,6 @@ export function DocsLayout() { const [customThemingEnabled, setCustomThemingEnabled] = useState(false); // True only when the email-verification Flagship flag is on for this user // AND their email is unverified - drives the "verify your email" banner. - const [emailUnverified, setEmailUnverified] = useState(false); // Same cookie-seed-then-/api/me-override pattern as the fonts above. const [themeMode, setThemeMode] = useState(() => readThemePrefsCookie().mode); const [themeCustomColor, setThemeCustomColor] = useState(() => readThemePrefsCookie().customColor); @@ -445,7 +445,7 @@ export function DocsLayout() { useEffect(() => { if (!getToken()) return; - apiFetchJson<{ name: string; userId: string; email?: string | null; emailVerified: boolean; emailVerificationEnabled: boolean; personalPlan: "free" | "ink"; personalPlanStyle: string | null; personalPresenceColor: string | null; personalCritSparkles: boolean; readingFont: string | null; editingFont: string | null; uiFont: string | null; isAdmin: boolean; themeMode: string | null; themeCustomColor: string | null; customThemingEnabled: boolean }>("/api/me") + apiFetchJson<{ name: string; userId: string; email?: string | null; personalPlan: "free" | "ink"; personalPlanStyle: string | null; personalPresenceColor: string | null; personalCritSparkles: boolean; readingFont: string | null; editingFont: string | null; uiFont: string | null; isAdmin: boolean; themeMode: string | null; themeCustomColor: string | null; customThemingEnabled: boolean }>("/api/me") .then(result => { if (result.ok && result.data) { setUserName(result.data.name); @@ -460,7 +460,6 @@ export function DocsLayout() { setUiFont(resolveFontChoice(result.data.uiFont, DEFAULT_UI_FONT)); setIsAdmin(result.data.isAdmin ?? false); setCustomThemingEnabled(result.data.customThemingEnabled ?? false); - setEmailUnverified(result.data.emailVerificationEnabled === true && result.data.emailVerified === false); setThemeMode(resolveThemeMode(result.data.themeMode)); setThemeCustomColor(result.data.themeCustomColor ?? null); } @@ -773,21 +772,9 @@ export function DocsLayout() { // Pages that don't publish their own breadcrumbs still get a titled top bar, // so every app route shares the same header (and the sidebar's header rule // lines up with something on the right). - async function signOut() { - // Best-effort: revoke the server-side session so the JWT is dead even if it - // gets exfiltrated from localStorage post-logout. We proceed with the local - // clear regardless of the network result. - if (getToken()) { - try { - await apiFetch("/api/me/sessions/logout", { - method: "POST", - headers: { "Content-Type": "application/json" }, - }); - } catch { /* ignore */ } - } - clearToken(); - navigate("/login"); - } + // Revokes the Annex session and signs out of auth.cubityfir.st too + // (lib/signIn.ts); the local token is cleared regardless. + const signOut = signOutEverywhere; const fallbackCrumbs = ((): BreadcrumbItem[] => { const path = location.pathname; @@ -829,18 +816,6 @@ export function DocsLayout() { )} - {emailUnverified && location.pathname !== "/settings" && ( -
- Your email address hasn't been verified. - -
- )}
{/* Backdrop - mobile only: closes sidebar when tapping the content area */} {sidebarOpen && ( @@ -1069,7 +1044,7 @@ export function DocsLayout() { navigate("/settings")}> Account settings - navigate("/settings#two-factor")}> + navigate("/settings#security")}> Security & sessions diff --git a/packages/frontend/src/lib/acknowledgements.ts b/packages/frontend/src/lib/acknowledgements.ts index 46ed91dc..c96ca030 100644 --- a/packages/frontend/src/lib/acknowledgements.ts +++ b/packages/frontend/src/lib/acknowledgements.ts @@ -30,20 +30,17 @@ export const ACKNOWLEDGEMENTS: Acknowledgement[] = [ { name: "react-day-picker", license: "MIT", url: "https://react-day-picker.js.org" }, { name: "react-colorful", license: "MIT", url: "https://github.com/omgovich/react-colorful" }, { name: "react-resizable-panels", license: "MIT", url: "https://github.com/bvaughn/react-resizable-panels" }, - { name: "react-qr-code", license: "MIT", url: "https://github.com/rosskhanas/react-qr-code" }, { name: "react-force-graph-2d", license: "MIT", url: "https://github.com/vasturiano/react-force-graph" }, { name: "class-variance-authority", license: "Apache-2.0", url: "https://cva.style" }, { name: "tailwind-merge", license: "MIT", url: "https://github.com/dcastil/tailwind-merge" }, { name: "clsx", license: "MIT", url: "https://github.com/lukeed/clsx" }, { name: "Tailwind CSS", license: "MIT", url: "https://tailwindcss.com" }, { name: "@tailwindcss/typography", license: "MIT", url: "https://github.com/tailwindlabs/tailwindcss-typography" }, - { name: "@simplewebauthn/browser", license: "MIT", url: "https://simplewebauthn.dev" }, { name: "date-fns", license: "MIT", url: "https://date-fns.org" }, { name: "culori", license: "MIT", url: "https://culorijs.org" }, { name: "d3-geo", license: "ISC", url: "https://github.com/d3/d3-geo" }, { name: "topojson-client", license: "ISC", url: "https://github.com/topojson/topojson-client" }, { name: "world-atlas", license: "ISC", url: "https://github.com/topojson/world-atlas" }, { name: "gifuct-js", license: "MIT", url: "https://github.com/matt-way/gifuct-js" }, - { name: "zxcvbn", license: "MIT", url: "https://github.com/dropbox/zxcvbn" }, { name: "Vite", license: "MIT", url: "https://vite.dev" }, ]; diff --git a/packages/frontend/src/lib/demoServer.test.ts b/packages/frontend/src/lib/demoServer.test.ts index fca2e141..18b855e4 100644 --- a/packages/frontend/src/lib/demoServer.test.ts +++ b/packages/frontend/src/lib/demoServer.test.ts @@ -405,28 +405,27 @@ describe("demo server graph", () => { }); describe("demo server user prefs", () => { - it("persists name, timezone, bio and fonts through /me and reflects them in reads", async () => { - const renamed = await patch("/me", { name: "Demo Renamed" }); - expect(renamed.data.name).toBe("Demo Renamed"); + it("persists timezone, bio and fonts through /me and reflects them in reads", async () => { await patch("/me", { timezone: "Europe/London" }); await patch("/me/bio", { bio: "Hello from the demo" }); await patch("/me/reading-font", { readingFont: "serif", uiFont: null }); const me = await api("/me"); - expect(me.data.name).toBe("Demo Renamed"); expect(me.data.timezone).toBe("Europe/London"); expect(me.data.bio).toBe("Hello from the demo"); expect(me.data.readingFont).toBe("serif"); - expect(me.data.emailVerified).toBe(true); - // The one demo member row follows the rename. - const members = await api("/projects/demo-site/members"); - expect(members.data[0].name).toBe("Demo Renamed"); - await patch("/me", { name: "Demo User", timezone: null }); + await patch("/me", { timezone: null }); await patch("/me/bio", { bio: null }); await patch("/me/reading-font", { readingFont: null }); }); + it("refuses a name change like the real API (names live on the identity service)", async () => { + const before = (await api("/me")).data.name; + expect((await patch("/me", { name: "Demo Renamed" })).error).toBe("name_managed_by_identity"); + expect((await api("/me")).data.name).toBe(before); + }); + it("supports the opt-in /@handle profile link", async () => { expect((await api("/users/by-handle/demo-person")).status).toBe(404); @@ -444,21 +443,9 @@ describe("demo server user prefs", () => { expect((await api("/users/by-handle/demo-person")).status).toBe(404); }); - it("lists this browser as the one current session and refuses revoking", async () => { - const res = await api("/me/sessions"); - expect(res.ok).toBe(true); - expect(res.data.sessions).toHaveLength(1); - const [session] = res.data.sessions; - expect(session.current).toBe(true); - expect(typeof session.clientLabel).toBe("string"); - expect(session.createdAt).toBeLessThanOrEqual(Date.now()); - expect((await post("/me/sessions/revoke-others")).error).toBe("Session management is disabled in the demo."); - }); - - it("refuses avatar changes and account deletion with readable messages", async () => { + it("refuses avatar changes with a readable message", async () => { expect((await post("/avatar?variant=default")).error).toBe("Avatar changes are disabled in the demo."); expect((await del("/avatar?variant=default")).error).toBe("Avatar changes are disabled in the demo."); - expect((await del("/me")).error).toBe("Account deletion is disabled in the demo."); }); }); diff --git a/packages/frontend/src/lib/demoServer.ts b/packages/frontend/src/lib/demoServer.ts index 05d33cac..cef4b753 100644 --- a/packages/frontend/src/lib/demoServer.ts +++ b/packages/frontend/src/lib/demoServer.ts @@ -724,14 +724,10 @@ function searchStore(s: Store, q: string | null, tag: string | null) { // --------------------------------------------------------------------------- // Anonymous auth/public endpoints keep hitting the real network even while the -// demo flag is set - e.g. someone opening /login mid-demo should still be able -// to sign in for real (setToken exits demo mode). +// demo flag is set - e.g. someone signing in mid-demo still completes the real +// /api/auth/* round trip (setToken exits demo mode). const PASSTHROUGH_PREFIXES = [ - "/api/login", - "/api/register", - "/api/webauthn/", - "/api/verify-email", - "/api/force-change-password", + "/api/auth/", "/api/public/", "/api/admin/", "/api/dev/", @@ -742,25 +738,6 @@ const PASSTHROUGH_PREFIXES = [ // data - every demo entity id starts with "demo-" (seeded ids and nextId ids // alike), which real ids (UUIDs) never do. Those requests are answered from // the in-memory store so publishing is browsable inside the demo. -/** Session row for this browser, shaped like the real GET /me/sessions entry. */ -function demoCurrentSession() { - const ua = typeof navigator !== "undefined" ? navigator.userAgent : ""; - const deviceKind = /iPad|Tablet/i.test(ua) ? "tablet" : /Mobi|iPhone|Android/i.test(ua) ? "phone" : "laptop"; - 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|Macintosh/.test(ua) ? (/iPhone|iPad/.test(ua) ? "iOS" : "macOS") : /Android/.test(ua) ? "Android" : /Linux/.test(ua) ? "Linux" : null; - const now = Date.now(); - return { - id: "demo-session-current", - createdAt: now - 20 * 60_000, - lastUsedAt: now, - expiresAt: now + 30 * 24 * 60 * 60_000, - deviceKind, - clientLabel: os ? `${browser} on ${os}` : browser, - ip: null, - current: true, - }; -} - function isDemoPublicRequest(url: URL): boolean { if (!url.pathname.startsWith("/api/public/")) return false; return url.pathname.includes("/demo-") || (url.searchParams.get("projectId")?.startsWith("demo-") ?? false); @@ -776,8 +753,6 @@ async function route(method: string, url: URL, input: RequestInfo | URL, init?: name: s.userName, userId: DEMO_USER_ID, email: DEMO_USER_EMAIL, - emailVerified: true, - emailVerificationEnabled: false, timezone: s.userTimezone, bio: s.userBio, handle: s.userHandle, @@ -800,15 +775,10 @@ async function route(method: string, url: URL, input: RequestInfo | URL, init?: } if (seg[0] === "me" && seg.length === 1 && method === "PATCH") { const body = await readJsonBody(input, init); - if (typeof body.name === "string" && body.name.trim()) s.userName = body.name.trim(); + // Like the real API: the name is managed on the identity service. + if ("name" in body) return json({ ok: false, error: "name_managed_by_identity" }, 400); if ("timezone" in body) s.userTimezone = typeof body.timezone === "string" ? body.timezone : null; - return ok({ name: s.userName, timezone: s.userTimezone }); - } - if (seg[0] === "me" && seg.length === 1 && method === "DELETE") { - return blocked("Account deletion is disabled in the demo."); - } - if (seg[0] === "me" && seg[1] === "email") { - return blocked("Email changes are disabled in the demo."); + return ok({ timezone: s.userTimezone }); } if (seg[0] === "me" && seg[1] === "bio" && method === "PATCH") { const body = await readJsonBody(input, init); @@ -832,15 +802,6 @@ async function route(method: string, url: URL, input: RequestInfo | URL, init?: if ("uiFont" in body) s.uiFont = typeof body.uiFont === "string" ? body.uiFont : null; return ok(); } - if (seg[0] === "me" && seg[1] === "sessions" && seg[2] === "logout" && method === "POST") return ok(); - // The demo visitor is "signed in" on exactly one device - this one - so the - // Active sessions list always shows the current session, never an empty state. - if (seg[0] === "me" && seg[1] === "sessions" && seg.length === 2 && method === "GET") { - return ok({ sessions: [demoCurrentSession()] }); - } - if (seg[0] === "me" && seg[1] === "sessions" && (seg[2] === "revoke" || seg[2] === "revoke-others") && method === "POST") { - return blocked("Session management is disabled in the demo."); - } if (seg[0] === "avatar") return blocked("Avatar changes are disabled in the demo."); if (seg[0] === "billing") return blocked("Billing is disabled in the demo."); if (seg[0] === "users" && seg[2] === "report" && method === "POST") { diff --git a/packages/frontend/src/lib/pendingOAuth.test.ts b/packages/frontend/src/lib/pendingOAuth.test.ts deleted file mode 100644 index 0319f1e0..00000000 --- a/packages/frontend/src/lib/pendingOAuth.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"; -import { storePendingOAuthNext, consumePendingOAuthNext, clearPendingOAuthNext } from "./pendingOAuth"; - -const KEY = "pendingOAuthNext"; -const AUTHORIZE_PATH = "/oauth/authorize?client_id=app1&redirect_uri=https%3A%2F%2Fapp.example%2Fcb&code_challenge=abc"; - -beforeEach(() => { - window.localStorage.clear(); -}); -afterEach(() => { - vi.useRealTimers(); -}); - -describe("pendingOAuth", () => { - it("round-trips an authorize path through store/consume", () => { - storePendingOAuthNext(AUTHORIZE_PATH); - expect(consumePendingOAuthNext()).toBe(AUTHORIZE_PATH); - }); - - it("consume is single-use", () => { - storePendingOAuthNext(AUTHORIZE_PATH); - consumePendingOAuthNext(); - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("refuses to store anything but an /oauth/authorize path", () => { - storePendingOAuthNext("/dashboard"); - storePendingOAuthNext("https://evil.example/oauth/authorize"); - expect(window.localStorage.getItem(KEY)).toBeNull(); - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("rejects a tampered stash pointing outside /oauth/authorize", () => { - window.localStorage.setItem(KEY, JSON.stringify({ next: "//evil.example/", expiresAt: Date.now() + 60_000 })); - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("expires after an hour", () => { - vi.useFakeTimers(); - storePendingOAuthNext(AUTHORIZE_PATH); - vi.advanceTimersByTime(60 * 60 * 1000 + 1); - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("tolerates garbage in the storage slot", () => { - window.localStorage.setItem(KEY, "not json {"); - expect(consumePendingOAuthNext()).toBeNull(); - expect(window.localStorage.getItem(KEY)).toBeNull(); - }); - - it("clear removes the stash", () => { - storePendingOAuthNext(AUTHORIZE_PATH); - clearPendingOAuthNext(); - expect(consumePendingOAuthNext()).toBeNull(); - }); -}); diff --git a/packages/frontend/src/lib/pendingOAuth.ts b/packages/frontend/src/lib/pendingOAuth.ts deleted file mode 100644 index 68b6811c..00000000 --- a/packages/frontend/src/lib/pendingOAuth.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Resumes an interrupted "Sign in with Annex" flow across the signup path. -// -// When OAuthAuthorizePage bounces an unauthenticated visitor to /login, the -// ?next= param survives a straight sign-in but dies the moment the user -// detours through Sign up → check-email → the verification link (a fresh tab -// with no query context). Stashing the authorize URL in localStorage lets the -// first session mint - wherever it happens in the same browser profile - send -// the user back to complete the OAuth handshake. -// -// The stash is single-use (consume clears it) and expires after an hour: by -// then the connected service has almost certainly abandoned its pending -// request, and landing on the dashboard beats a surprise redirect days later. - -const PENDING_OAUTH_KEY = "pendingOAuthNext"; -const TTL_MS = 60 * 60 * 1000; - -function getStorage(): Storage | null { - try { - return window.localStorage; - } catch { - return null; - } -} - -// Only the authorize page's own URL is ever stashed; enforcing that on both -// write and read keeps a tampered value from redirecting anywhere else. -function isAuthorizePath(path: string): boolean { - return path.startsWith("/oauth/authorize"); -} - -export function storePendingOAuthNext(path: string): void { - if (!isAuthorizePath(path)) return; - getStorage()?.setItem(PENDING_OAUTH_KEY, JSON.stringify({ next: path, expiresAt: Date.now() + TTL_MS })); -} - -export function consumePendingOAuthNext(): string | null { - const storage = getStorage(); - const raw = storage?.getItem(PENDING_OAUTH_KEY); - if (!storage || !raw) return null; - storage.removeItem(PENDING_OAUTH_KEY); - try { - const parsed = JSON.parse(raw) as { next?: unknown; expiresAt?: unknown }; - if (typeof parsed.next !== "string" || !isAuthorizePath(parsed.next)) return null; - if (typeof parsed.expiresAt !== "number" || parsed.expiresAt < Date.now()) return null; - return parsed.next; - } catch { - return null; - } -} - -export function clearPendingOAuthNext(): void { - getStorage()?.removeItem(PENDING_OAUTH_KEY); -} diff --git a/packages/frontend/src/lib/signIn.test.ts b/packages/frontend/src/lib/signIn.test.ts new file mode 100644 index 00000000..f1bb6b8c --- /dev/null +++ b/packages/frontend/src/lib/signIn.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { safeReturnTo, signInUrl, signInErrorMessage, signOut } from "./signIn"; + +describe("safeReturnTo", () => { + it("keeps same-origin app paths", () => { + expect(safeReturnTo("/projects/p1?x=1#h")).toBe("/projects/p1?x=1#h"); + }); + it("rejects anything that could leave the app", () => { + for (const bad of ["https://evil.test", "//evil.test", "/\\evil.test", "javascript:alert(1)", "", null, undefined]) { + expect(safeReturnTo(bad)).toBeNull(); + } + }); +}); + +describe("signInUrl", () => { + it("builds the API login URL with a safe return path", () => { + expect(signInUrl("/projects/p1")).toBe("/api/auth/login?return_to=%2Fprojects%2Fp1"); + expect(signInUrl("https://evil.test")).toBe("/api/auth/login"); + expect(signInUrl(null, { prompt: "login" })).toBe("/api/auth/login?prompt=login"); + }); +}); + +describe("signInErrorMessage", () => { + it("has specific copy for the codes the callback can return, and a generic fallback", () => { + expect(signInErrorMessage("access_denied")).toMatch(/cancelled/); + expect(signInErrorMessage("account_disabled")).toMatch(/disabled/); + expect(signInErrorMessage("login_expired")).toMatch(/try again/); + expect(signInErrorMessage("whatever")).toMatch(/didn't complete/); + }); +}); + +describe("signOut", () => { + const assign = vi.fn(); + beforeEach(() => { + localStorage.setItem("token", "jwt"); + vi.stubGlobal("location", { ...window.location, assign }); + }); + afterEach(() => { + vi.unstubAllGlobals(); + assign.mockReset(); + localStorage.clear(); + }); + + it("revokes the session, clears the token and goes to the identity service's end-session URL", async () => { + const fetchMock = vi.fn(async () => Response.json({ ok: true, data: { logoutUrl: "https://auth.example/oauth/logout?id_token_hint=x" } })); + vi.stubGlobal("fetch", fetchMock); + await signOut(); + expect(fetchMock).toHaveBeenCalledWith("/api/auth/logout", expect.objectContaining({ method: "POST", headers: { Authorization: "Bearer jwt" } })); + expect(localStorage.getItem("token")).toBeNull(); + expect(assign).toHaveBeenCalledWith("https://auth.example/oauth/logout?id_token_hint=x"); + }); + + it("still clears the local session when the API can't be reached", async () => { + vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("offline"); })); + await signOut(); + expect(localStorage.getItem("token")).toBeNull(); + expect(assign).toHaveBeenCalledWith("/"); + }); +}); diff --git a/packages/frontend/src/lib/signIn.ts b/packages/frontend/src/lib/signIn.ts new file mode 100644 index 00000000..0893e973 --- /dev/null +++ b/packages/frontend/src/lib/signIn.ts @@ -0,0 +1,80 @@ +// Sign in / out through auth.cubityfir.st (Annex is an OIDC client). +// +// Sign-in is a top-level navigation to /api/auth/login, which redirects to the +// identity service; it comes back via /api/auth/callback to /auth/complete +// (AuthCompletePage), which redeems a single-use code for Annex's session JWT. + +import { clearToken, getToken } from "./auth"; +import { isDemoMode } from "./demo"; + +// Public origin of the identity service, for links to its account pages and +// the /oauth/authorize redirect shim. Overridable for local dev. +export const IDENTITY_ORIGIN: string = + (import.meta.env.VITE_IDENTITY_ORIGIN as string | undefined)?.replace(/\/+$/, "") || "https://auth.cubityfir.st"; + +export const IDENTITY_ACCOUNT_URL = `${IDENTITY_ORIGIN}/account`; +export const IDENTITY_SECURITY_URL = `${IDENTITY_ORIGIN}/account/security`; + +// Same-origin app paths only: "/x", never "//host", "/\host" or a scheme. +export function safeReturnTo(raw: string | null | undefined): string | null { + if (!raw || !raw.startsWith("/") || raw.startsWith("//") || raw.includes("\\")) return null; + return raw; +} + +export function signInUrl(returnTo?: string | null, opts: { prompt?: "login" } = {}): string { + const params = new URLSearchParams(); + const safe = safeReturnTo(returnTo); + if (safe) params.set("return_to", safe); + if (opts.prompt) params.set("prompt", opts.prompt); + const qs = params.toString(); + return `/api/auth/login${qs ? `?${qs}` : ""}`; +} + +export function startSignIn(returnTo?: string | null, opts: { prompt?: "login" } = {}): void { + window.location.assign(signInUrl(returnTo, opts)); +} + +// Revokes the Annex session, then sends the browser to the identity service's +// end-session endpoint (which signs the user out there too and comes back to +// the landing page). Best-effort: the local token is cleared regardless. +export async function signOut(): Promise { + // Leaving the demo sandbox is local only (clearToken exits demo mode). + if (isDemoMode()) { + clearToken(); + window.location.assign("/"); + return; + } + const token = getToken(); + let target = "/"; + if (token) { + try { + const res = await fetch("/api/auth/logout", { method: "POST", headers: { Authorization: `Bearer ${token}` } }); + const json = (await res.json()) as { ok?: boolean; data?: { logoutUrl?: string } }; + if (json.ok && json.data?.logoutUrl) target = json.data.logoutUrl; + } catch { + // Offline or the API is down: still clear the local session. + } + } + clearToken(); + window.location.assign(target); +} + +// Human copy for the error codes /api/auth/callback can hand back. +export function signInErrorMessage(code: string | null): string { + const contact = "Please email docs@cubityfir.st for further details."; + switch (code) { + case "access_denied": + return "Sign-in was cancelled."; + case "login_expired": + case "invalid_code": + return "That sign-in took too long or was already used. Please try again."; + case "account_disabled": + return `Your Annex account has been disabled. ${contact}`; + case "account_deleted": + return "This account has been deleted."; + case "identity_unavailable": + return "The sign-in service is unavailable right now. Please try again in a moment."; + default: + return "Sign-in didn't complete. Please try again."; + } +} diff --git a/packages/frontend/src/lib/theme.ts b/packages/frontend/src/lib/theme.ts index 24039a03..50366622 100644 --- a/packages/frontend/src/lib/theme.ts +++ b/packages/frontend/src/lib/theme.ts @@ -41,7 +41,7 @@ export function resolveThemeMode(value: string | null | undefined, fallback: The // (dark) brand look - the per-user theme is an in-app preference and must not // leak onto these. Everything else (the DocsLayout app, public docs, etc.) // uses the saved theme. Exact-match paths: none of these have sub-routes. -const UNTHEMED_PATHS = new Set(["/", "/login", "/register"]); +const UNTHEMED_PATHS = new Set(["/", "/login", "/register", "/auth/complete"]); export function pathUsesUserTheme(pathname: string): boolean { return !UNTHEMED_PATHS.has(pathname); diff --git a/packages/frontend/src/lib/webauthn.ts b/packages/frontend/src/lib/webauthn.ts deleted file mode 100644 index a9aef631..00000000 --- a/packages/frontend/src/lib/webauthn.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { startAuthentication } from "@simplewebauthn/browser"; - -type AuthOptions = Record & { - allowCredentials?: Array>; -}; - -// Mobile platforms (Android Credential Manager, iOS AutoFill) aggregate every -// passkey provider - incl. a synced password manager like Bitwarden - into the -// modal `navigator.credentials.get()`, and actually *need* the -// allowCredentials[].transports hint (["internal","hybrid"]) to surface synced -// passkeys, so we leave the options untouched there. -function isMobilePlatform(): boolean { - if (typeof navigator === "undefined") return false; - return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent); -} - -// Desktop Chrome honors allowCredentials[].transports literally: an "internal" -// hint routes the request straight to the platform authenticator (Windows Hello -// / Touch ID) and "hybrid" to "use a phone", so a synced password-manager passkey -// (Bitwarden) is never offered - the user only sees the local-hardware / USB / -// NFC / "use another device" fallback. Dropping the hint lets the browser surface -// the full provider chooser (incl. an OS-registered Bitwarden provider). -function stripTransports(options: AuthOptions): AuthOptions { - if (!Array.isArray(options.allowCredentials)) return options; - return { - ...options, - allowCredentials: options.allowCredentials.map((cred) => { - const next = { ...cred }; - delete next.transports; - return next; - }), - }; -} - -// Wrapper around @simplewebauthn/browser's startAuthentication that relaxes the -// transport hints on desktop only - see stripTransports / isMobilePlatform. -export function startWebauthnAuth(options: AuthOptions) { - const opts = isMobilePlatform() ? options : stripTransports(options); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return startAuthentication(opts as any); -} diff --git a/packages/frontend/src/pages/AuthCompletePage.test.tsx b/packages/frontend/src/pages/AuthCompletePage.test.tsx new file mode 100644 index 00000000..b8898adc --- /dev/null +++ b/packages/frontend/src/pages/AuthCompletePage.test.tsx @@ -0,0 +1,58 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { AuthCompletePage } from "./AuthCompletePage"; + +function renderAt(hash: string) { + window.history.replaceState(null, "", `/auth/complete${hash}`); + return render( + + + } /> + PROJECT P1
} /> + DASHBOARD} /> +
+ , + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); + localStorage.clear(); +}); + +describe("AuthCompletePage", () => { + it("redeems the code once, stores the session and goes to the return path", async () => { + const fetchMock = vi.fn(async () => Response.json({ ok: true, data: { token: "session-jwt" } })); + vi.stubGlobal("fetch", fetchMock); + renderAt("#code=abc123&return_to=%2Fprojects%2Fp1"); + expect(await screen.findByText("PROJECT P1")).toBeInTheDocument(); + expect(localStorage.getItem("token")).toBe("session-jwt"); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(JSON.parse(String((fetchMock.mock.calls[0] as unknown[])[1] && ((fetchMock.mock.calls[0] as unknown[])[1] as RequestInit).body))).toEqual({ code: "abc123" }); + // The code doesn't linger in the address bar. + expect(window.location.hash).toBe(""); + }); + + it("ignores an off-site return path", async () => { + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ok: true, data: { token: "t" } }))); + renderAt("#code=abc123&return_to=https%3A%2F%2Fevil.test"); + expect(await screen.findByText("DASHBOARD")).toBeInTheDocument(); + }); + + it("explains a callback error and offers a retry", async () => { + const fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + renderAt("#error=access_denied"); + expect(await screen.findByText(/sign-in was cancelled/i)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: /try again/i })).toBeInTheDocument(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("explains a code that was already used or expired", async () => { + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ok: false, error: "invalid_code" }, { status: 400 }))); + renderAt("#code=used"); + await waitFor(() => expect(screen.getByText(/took too long or was already used/i)).toBeInTheDocument()); + expect(localStorage.getItem("token")).toBeNull(); + }); +}); diff --git a/packages/frontend/src/pages/AuthCompletePage.tsx b/packages/frontend/src/pages/AuthCompletePage.tsx new file mode 100644 index 00000000..b24f63bd --- /dev/null +++ b/packages/frontend/src/pages/AuthCompletePage.tsx @@ -0,0 +1,81 @@ +import { useEffect, useRef, useState } from "react"; +import { useNavigate } from "react-router-dom"; +import { AuthForm } from "@/components/AuthForm"; +import { setToken } from "@/lib/auth"; +import { safeReturnTo, signInErrorMessage, startSignIn } from "@/lib/signIn"; + +// /auth/complete - where /api/auth/callback sends the browser. The outcome is +// in the URL fragment (never sent to servers or in Referer headers): +// #code=&return_to=/path -> redeem for the session JWT +// #error= -> explain and offer a retry +export function AuthCompletePage() { + const navigate = useNavigate(); + const [error, setError] = useState(null); + const [returnTo, setReturnTo] = useState("/dashboard"); + const started = useRef(false); + + useEffect(() => { + // StrictMode runs effects twice in dev; the code is single use. + if (started.current) return; + started.current = true; + + const fragment = new URLSearchParams(window.location.hash.slice(1)); + // Drop the code from the address bar and history straight away. + window.history.replaceState(null, "", window.location.pathname); + const next = safeReturnTo(fragment.get("return_to")) ?? "/dashboard"; + setReturnTo(next); + + const code = fragment.get("code"); + if (!code) { + setError(signInErrorMessage(fragment.get("error"))); + return; + } + (async () => { + try { + const res = await fetch("/api/auth/exchange", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ code }), + }); + const json = (await res.json()) as { ok: boolean; data?: { token: string }; error?: string }; + if (!json.ok || !json.data) { + setError(signInErrorMessage(json.error ?? "invalid_code")); + return; + } + setToken(json.data.token); + navigate(next, { replace: true }); + } catch { + setError(signInErrorMessage("identity_unavailable")); + } + })(); + }, [navigate]); + + return ( + } + title="Annex" + subtitle={error ? "Couldn't sign you in" : "Signing you in…"} + submitLabel="Try again" + hideSubmit={!error} + error={error} + onSubmit={e => { + e.preventDefault(); + startSignIn(returnTo); + }} + footer={Back to the home page} + > + {null} + + ); +} + +// /oauth/authorize - the authorization endpoint moved to the identity service. +// Kept as a redirect (query string included) for services that hard-coded the +// old URL. The frontend worker does the same redirect server-side in +// production; this covers the SPA route (local dev, client-side navigation). +export function OAuthAuthorizeRedirect({ origin }: { origin: string }) { + useEffect(() => { + window.location.replace(`${origin}/oauth/authorize${window.location.search}`); + }, [origin]); + return null; +} diff --git a/packages/frontend/src/pages/CheckEmailPage.test.tsx b/packages/frontend/src/pages/CheckEmailPage.test.tsx deleted file mode 100644 index 456bc454..00000000 --- a/packages/frontend/src/pages/CheckEmailPage.test.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, it, expect, vi, afterEach } from "vitest"; -import { render, screen } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { MemoryRouter, Routes, Route } from "react-router-dom"; -vi.mock("@/components/DotGrid", () => ({ DotGrid: () => null })); - -import { CheckEmailPage } from "./CheckEmailPage"; - -function renderWith(state: { email?: string } | null) { - return render( - - - } /> - - , - ); -} - -afterEach(() => { - vi.restoreAllMocks(); - sessionStorage.clear(); -}); - -describe("CheckEmailPage", () => { - it("renders the heading and the address it sent to", () => { - renderWith({ email: "user@example.com" }); - expect(screen.getByRole("heading", { name: /check your email/i })).toBeInTheDocument(); - expect(screen.getByText("user@example.com")).toBeInTheDocument(); - expect(screen.getByText(/we sent a link to/i)).toBeInTheDocument(); - }); - - it("still names the address after a reload drops the router state", () => { - renderWith({ email: "user@example.com" }).unmount(); - renderWith(null); - expect(screen.getByText("user@example.com")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: /resend verification email/i })).toBeInTheDocument(); - }); - - it("shows a generic message and no resend button when no email is provided", () => { - renderWith(null); - expect(screen.getByText(/we sent you a verification link/i)).toBeInTheDocument(); - expect(screen.queryByRole("button", { name: /resend/i })).not.toBeInTheDocument(); - }); - - it("resends the verification email and confirms it was sent", async () => { - const fetchMock = vi.fn().mockResolvedValue({ json: () => Promise.resolve({ ok: true }) }); - vi.stubGlobal("fetch", fetchMock); - renderWith({ email: "user@example.com" }); - - await userEvent.click(screen.getByRole("button", { name: /resend verification email/i })); - - expect(await screen.findByText(/verification email resent/i)).toBeInTheDocument(); - expect(fetchMock).toHaveBeenCalledWith( - "/api/verify-email/resend", - expect.objectContaining({ method: "POST", body: JSON.stringify({ email: "user@example.com" }) }), - ); - // After a successful resend the button is cooled down. - expect(screen.getByRole("button", { name: /email sent/i })).toBeDisabled(); - }); - - it("shows an error when the resend request fails", async () => { - vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline"))); - renderWith({ email: "user@example.com" }); - - await userEvent.click(screen.getByRole("button", { name: /resend verification email/i })); - - expect(await screen.findByText(/failed to resend email/i)).toBeInTheDocument(); - }); - - it("links back to sign in", () => { - renderWith({ email: "user@example.com" }); - expect(screen.getByRole("link", { name: /back to sign in/i })).toHaveAttribute("href", "/login"); - }); -}); diff --git a/packages/frontend/src/pages/CheckEmailPage.tsx b/packages/frontend/src/pages/CheckEmailPage.tsx deleted file mode 100644 index ed574be7..00000000 --- a/packages/frontend/src/pages/CheckEmailPage.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { useEffect, useState } from "react"; -import { useLocation } from "react-router-dom"; -import { ArrowLeft } from "lucide-react"; -import { AuthShell, AUTH_BUTTON_CLASS } from "@/components/AuthForm"; -import { Alert, AlertDescription } from "@/components/ui/alert"; -import { Button } from "@/components/ui/button"; - -const EMAIL_KEY = "annex:check-email"; - -function readStoredEmail(): string | undefined { - try { return sessionStorage.getItem(EMAIL_KEY) ?? undefined; } catch { return undefined; } -} - -export function CheckEmailPage() { - const location = useLocation(); - // Register hands the address over in router state; remember it for the tab - // so a reload still names it (and keeps the resend button). - const stateEmail = (location.state as { email?: string } | null)?.email; - const email = stateEmail ?? readStoredEmail(); - useEffect(() => { - if (!stateEmail) return; - try { sessionStorage.setItem(EMAIL_KEY, stateEmail); } catch { /* storage blocked */ } - }, [stateEmail]); - - const [resendState, setResendState] = useState<"idle" | "sending" | "sent" | "error">("idle"); - const [cooldown, setCooldown] = useState(false); - - async function handleResend() { - if (!email || cooldown) return; - setResendState("sending"); - try { - await fetch("/api/verify-email/resend", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email }), - }); - setResendState("sent"); - setCooldown(true); - setTimeout(() => setCooldown(false), 30_000); - } catch { - setResendState("error"); - } - } - - return ( - -
- {/* Same heading block as AuthForm's wordmark screens (login, - register): left-aligned, wordmark then the step as the

. */} -
- - Annex - -

Check your email

-

- {email - ? <>We sent a link to {email}. - : "We sent you a verification link."} - {" "}Click it within 24 hours to activate your account. -

-
- -
-

Didn’t get it?

-

- {email - ? "Check your spam folder, or send a fresh link below." - : "Check your spam folder. Signing in with an unverified account also lets you request a fresh link."} -

-
- - {resendState === "sent" && ( - - Verification email resent. Check your inbox. - - )} - {resendState === "error" && ( - - Failed to resend email. Please try again. - - )} - -
- {email && ( - - )} - -
-

-
- ); -} diff --git a/packages/frontend/src/pages/LoginPage.test.tsx b/packages/frontend/src/pages/LoginPage.test.tsx deleted file mode 100644 index 9a46bf1d..00000000 --- a/packages/frontend/src/pages/LoginPage.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { MemoryRouter, Routes, Route } from "react-router-dom"; -import { LoginPage } from "./LoginPage"; -import { consumePendingOAuthNext, storePendingOAuthNext } from "@/lib/pendingOAuth"; - -// The real Turnstile needs the CF challenge script and DotGrid needs a 2d -// canvas + ResizeObserver - neither exists in jsdom. The Turnstile mock -// verifies on the next tick: LoginPage clears the token in its own -// mount/step effect, which runs after child effects, so a same-tick verify -// would be wiped. -vi.mock("@/components/Turnstile", async () => { - const React = await import("react"); - return { - Turnstile: React.forwardRef(function TurnstileMock( - { onVerify }: { onVerify: (token: string) => void }, - _ref: unknown, - ) { - React.useEffect(() => { - const t = setTimeout(() => onVerify("ts-token"), 0); - return () => clearTimeout(t); - }, [onVerify]); - return null; - }), - }; -}); -vi.mock("@/components/DotGrid", () => ({ DotGrid: () => null })); - -const AUTHORIZE_PATH = "/oauth/authorize?client_id=app1&redirect_uri=https%3A%2F%2Fapp.example%2Fcb&code_challenge=abc"; - -function renderAt(path: string) { - return render( - - - } /> - DASHBOARD} /> - OAUTH_AUTHORIZE} /> - - , - ); -} - -function mockLoginSuccess() { - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - status: 200, - json: () => Promise.resolve({ ok: true, data: { token: "jwt-1" } }), - }), - ); -} - -async function signIn() { - await userEvent.type(screen.getByLabelText(/email/i), "user@example.com"); - await userEvent.type(screen.getByLabelText(/password/i), "hunter2hunter2"); - const submit = screen.getByRole("button", { name: "Sign in" }); - await waitFor(() => expect(submit).toBeEnabled()); - await userEvent.click(submit); -} - -beforeEach(() => { - window.localStorage.clear(); -}); -afterEach(() => { - vi.restoreAllMocks(); - vi.unstubAllGlobals(); -}); - -describe("LoginPage", () => { - it("lands on the dashboard after sign-in with no next or stash", async () => { - mockLoginSuccess(); - renderAt("/login"); - await signIn(); - await waitFor(() => expect(screen.getByText("DASHBOARD")).toBeInTheDocument()); - expect(window.localStorage.getItem("token")).toBe("jwt-1"); - }); - - it("resumes a stashed OAuth authorize flow after sign-in", async () => { - storePendingOAuthNext(AUTHORIZE_PATH); - mockLoginSuccess(); - renderAt("/login"); - await signIn(); - await waitFor(() => expect(screen.getByText("OAUTH_AUTHORIZE")).toBeInTheDocument()); - }); - - it("prefers an explicit ?next= but still consumes the stash", async () => { - storePendingOAuthNext(AUTHORIZE_PATH); - mockLoginSuccess(); - renderAt("/login?next=%2Fdashboard"); - await signIn(); - await waitFor(() => expect(screen.getByText("DASHBOARD")).toBeInTheDocument()); - // consumed on sign-in so it can't redirect a later session - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("resumes a stashed OAuth flow for an already-signed-in visitor", async () => { - window.localStorage.setItem("token", "jwt-existing"); - storePendingOAuthNext(AUTHORIZE_PATH); - renderAt("/login"); - await waitFor(() => expect(screen.getByText("OAUTH_AUTHORIZE")).toBeInTheDocument()); - }); -}); diff --git a/packages/frontend/src/pages/LoginPage.tsx b/packages/frontend/src/pages/LoginPage.tsx deleted file mode 100644 index 30d532ab..00000000 --- a/packages/frontend/src/pages/LoginPage.tsx +++ /dev/null @@ -1,876 +0,0 @@ -import { Fragment, useCallback, useEffect, useRef, useState } from "react"; -import { useNavigate, useLocation } from "react-router-dom"; -import { ArrowLeft, KeyRound, Smartphone, Hash } from "lucide-react"; -import { startWebauthnAuth } from "@/lib/webauthn"; -import { Input } from "@/components/ui/input"; -import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"; -import { Label } from "@/components/ui/label"; -import { Button } from "@/components/ui/button"; -import { Alert, AlertDescription } from "@/components/ui/alert"; -import { AuthForm, PasswordInput, AUTH_INPUT_CLASS, AUTH_BUTTON_CLASS } from "@/components/AuthForm"; -import { Turnstile, type TurnstileHandle } from "@/components/Turnstile"; -import { clearToken, getToken, setToken } from "@/lib/auth"; -import { consumePendingOAuthNext } from "@/lib/pendingOAuth"; - -type LoginStep = "credentials" | "totp" | "webauthn" | "method_picker" | "force_password_change" | "email_unverified"; - -function moderationMessage(error?: string, until?: number): string { - const contact = "Please email docs@cubityfir.st for further details."; - if (error === "account_suspended" && until) { - const date = new Date(until * 1000).toLocaleDateString(undefined, { dateStyle: "long" }); - return `Your account has been temporarily suspended until ${date}. ${contact}`; - } - return `Your account has been disabled. ${contact}`; -} - -function normalizeAdminReturnTo(returnTo: string | null): string | null { - if (!returnTo) return null; - - try { - return new URL(returnTo).toString(); - } catch { - return null; - } -} - -// Maps the `reason` query param set by apiFetch when it forces a sign-out -// to a human-readable message rendered above the credential form. -function reasonNoticeFor(reason: string | null): string | null { - if (reason === "disabled") return "Your account has been disabled. Please email docs@cubityfir.st for further details."; - if (reason === "suspended") return "Your account is currently suspended. Please email docs@cubityfir.st for further details."; - if (reason === "expired") return "Your session has ended. Please sign in again."; - return null; -} - -function adminHandoffErrorMessage(error?: string): string { - if (error === "not_admin") { - return "This Annex account is signed in, but it does not have admin access."; - } - - return "Could not continue to the admin panel. Please try again."; -} - -// Same "← Back to sign in" ghost action as CheckEmailPage, so every auth step -// exits the same way (it was a bare text link here, indented off the form edge). -function BackToSignIn({ onClick }: { onClick: () => void }) { - return ( - - ); -} - -const annexWordmark = Annex; - -// Accept only same-origin relative paths. Rejects protocol-relative (`//evil`), -// schemed (`https://…`), and anything that doesn't start with a single slash. -function safeNextPath(raw: string | null): string | null { - if (!raw) return null; - if (!raw.startsWith("/")) return null; - if (raw.startsWith("//")) return null; - return raw; -} - -export function LoginPage() { - const navigate = useNavigate(); - const location = useLocation(); - const searchParams = new URLSearchParams(location.search); - // Prefer the ?next= param set by apiFetch when it forced a sign-out; fall - // back to React Router state (set by direct navigations to /login); then a - // stashed OAuth authorize URL (survives the signup detour, where ?next= is - // lost); finally default to /dashboard. - const nextParam = safeNextPath(searchParams.get("next")); - const fromState = (location.state as { from?: string } | null)?.from; - const resolveDestination = useCallback(() => { - // Consume the stash even when ?next= already covers it, so an abandoned - // OAuth attempt can't redirect a later unrelated sign-in. - const pendingOAuth = consumePendingOAuthNext(); - return nextParam ?? fromState ?? pendingOAuth ?? "/dashboard"; - }, [nextParam, fromState]); - const adminReturnTo = normalizeAdminReturnTo(searchParams.get("returnTo")); - const logoutRequested = searchParams.get("logout") === "1"; - const reasonParam = searchParams.get("reason"); - const reasonNotice = reasonNoticeFor(reasonParam); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [turnstileToken, setTurnstileToken] = useState(null); - const turnstileRef = useRef(null); - const [error, setError] = useState(null); - const [loading, setLoading] = useState(false); - - const [step, setStep] = useState("credentials"); - const [pendingUserId, setPendingUserId] = useState(null); - const [totpCode, setTotpCode] = useState(""); - const [usingBackupCode, setUsingBackupCode] = useState(false); - const [backupCode, setBackupCode] = useState(""); - // Short-lived (5-minute) single-purpose token returned alongside - // totp_required / two_factor_required. The 2FA continuation submits this - // instead of re-sending the email/password/turnstile credentials. - const [preAuthToken, setPreAuthToken] = useState(null); - const [changeToken, setChangeToken] = useState(null); - const [newPassword, setNewPassword] = useState(""); - const [confirmPassword, setConfirmPassword] = useState(""); - const [resendState, setResendState] = useState<"idle" | "sending" | "sent" | "error">("idle"); - const existingSessionHandledRef = useRef(false); - const logoutHandledRef = useRef(false); - const handleTurnstileVerify = useCallback((token: string) => setTurnstileToken(token), []); - const handleTurnstileExpire = useCallback(() => setTurnstileToken(null), []); - - const startAdminHandoff = useCallback(async (token: string): Promise => { - if (!adminReturnTo) return false; - - setLoading(true); - setError(null); - - try { - const response = await fetch("/api/admin/handoff/start", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - body: JSON.stringify({ returnTo: adminReturnTo }), - }); - - const json = await response.json() as { - ok: boolean; - data?: { redirectTo?: string }; - error?: string; - }; - - if (json.ok && json.data?.redirectTo) { - window.location.assign(json.data.redirectTo); - return true; - } - - setError(adminHandoffErrorMessage(json.error)); - return false; - } catch { - setError("Could not continue to the admin panel. Please try again."); - return false; - } finally { - setLoading(false); - } - }, [adminReturnTo]); - - const completeAuthentication = useCallback(async (token: string) => { - setToken(token); - - if (adminReturnTo) { - const redirected = await startAdminHandoff(token); - if (redirected) return; - } - - navigate(resolveDestination(), { replace: true }); - }, [adminReturnTo, resolveDestination, navigate, startAdminHandoff]); - - useEffect(() => { - if (logoutRequested && !logoutHandledRef.current) { - logoutHandledRef.current = true; - clearToken(); - } - - if (existingSessionHandledRef.current) return; - - const token = getToken(); - if (!token) return; - - existingSessionHandledRef.current = true; - - if (adminReturnTo) { - void startAdminHandoff(token); - } else { - navigate(resolveDestination(), { replace: true }); - } - }, [adminReturnTo, resolveDestination, logoutRequested, navigate, startAdminHandoff]); - - // Each step that mounts a Turnstile widget needs a fresh token. The previous step's - // token (if any) was already consumed server-side, so clear it to force a re-solve - // and keep the submit button disabled until the new challenge completes. - useEffect(() => { - setTurnstileToken(null); - }, [step]); - - // Auto-submit the authenticator code once all six digits are entered so the - // user doesn't have to reach for Verify. The ref remembers the last code we - // auto-submitted: a failure that leaves the code in place (network error, - // rate limit) must not re-fire when `loading` flips back to false, or this - // effect would loop resubmitting forever - the user retries via Verify. - // Editing the code below six digits re-arms it. - const autoSubmittedCodeRef = useRef(null); - useEffect(() => { - if (totpCode.length < 6) { - autoSubmittedCodeRef.current = null; - return; - } - if (step === "totp" && !usingBackupCode && !loading - && autoSubmittedCodeRef.current !== totpCode) { - autoSubmittedCodeRef.current = totpCode; - void handleSubmit(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [step, usingBackupCode, totpCode, loading]); - - const runWebauthnFlow = useCallback(async function runWebauthnFlow(userId: string) { - setLoading(true); - setError(null); - try { - const startRes = await fetch("/api/webauthn/auth/start", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userId }), - }); - const startJson = await startRes.json() as { - ok: boolean; - data?: { options: Record; challengeId: string }; - }; - if (!startJson.ok || !startJson.data) { - setError("Failed to start security key authentication."); - return; - } - - const { options, challengeId } = startJson.data; - let assertion; - try { - assertion = await startWebauthnAuth(options); - } catch { - setError("Security key authentication was cancelled or failed. Please try again."); - return; - } - - const finishRes = await fetch("/api/webauthn/auth/finish", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - userId, - challengeId, - response: assertion, - email, - }), - }); - const finishJson = await finishRes.json() as { - ok: boolean; - data?: { token: string }; - error?: string; - until?: number; - changeToken?: string; - }; - - if (finishJson.ok && finishJson.data) { - await completeAuthentication(finishJson.data.token); - } else if (finishJson.error === "password_change_required" && finishJson.changeToken) { - setChangeToken(finishJson.changeToken); - setStep("force_password_change"); - } else if (finishRes.status === 403) { - setError(moderationMessage(finishJson.error, finishJson.until)); - } else { - setError("Security key verification failed. Please try again."); - } - } catch { - setError("Could not connect to the server. Please try again."); - } finally { - setLoading(false); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [email, navigate]); - - // Usernameless passkey sign-in: no email or password typed. The browser - // offers the passkeys it holds for this site and the server resolves the - // account from the one chosen. A user-verifying passkey is a full login on - // its own, so there's no 2FA step after it (same as webauthn_required). - async function handlePasskeySignIn() { - if (loading) return; - setLoading(true); - setError(null); - try { - const startRes = await fetch("/api/webauthn/auth/passkey/start", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: "{}", - }); - const startJson = await startRes.json() as { - ok: boolean; - data?: { options: Record; challengeId: string }; - }; - if (!startJson.ok || !startJson.data) { - setError(startRes.status === 429 - ? "Too many attempts. Please wait a moment and try again." - : "Failed to start passkey sign-in."); - return; - } - - const { options, challengeId } = startJson.data; - let assertion; - try { - assertion = await startWebauthnAuth(options); - } catch { - setError("No passkey was used. Try again, or sign in with your email and password."); - return; - } - - const finishRes = await fetch("/api/webauthn/auth/passkey/finish", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ challengeId, response: assertion }), - }); - const finishJson = await finishRes.json() as { - ok: boolean; - data?: { token: string }; - error?: string; - until?: number; - changeToken?: string; - email?: string; - }; - - if (finishJson.ok && finishJson.data) { - await completeAuthentication(finishJson.data.token); - } else if (finishJson.error === "password_change_required" && finishJson.changeToken) { - setChangeToken(finishJson.changeToken); - setStep("force_password_change"); - } else if (finishJson.error === "email_not_verified") { - if (finishJson.email) setEmail(finishJson.email); - setStep("email_unverified"); - } else if (finishRes.status === 403) { - setError(moderationMessage(finishJson.error, finishJson.until)); - } else { - setError("That passkey isn't registered to an Annex account. Sign in with your email and password, then add it in Settings."); - } - } catch { - setError("Could not connect to the server. Please try again."); - } finally { - setLoading(false); - } - } - - async function handleResendVerification() { - if (!email || resendState === "sending") return; - setResendState("sending"); - try { - await fetch("/api/verify-email/resend", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email }), - }); - setResendState("sent"); - } catch { - setResendState("error"); - } - } - - // Re-run the credentials-step Turnstile challenge after a failed submit. - // The token is single-use at siteverify, so re-sending the consumed one is - // rejected as BAD_REQUEST; reset() fetches a fresh token and re-disables the - // submit button until it arrives. - function resetTurnstile() { - turnstileRef.current?.reset(); - setTurnstileToken(null); - } - - async function handleSubmit(e?: React.FormEvent) { - e?.preventDefault(); - if (loading) return; - setError(null); - - const isTotpStep = step === "totp"; - if (!isTotpStep && !turnstileToken) { - setError("Please complete the security challenge."); - return; - } - - setLoading(true); - try { - // Credentials step sends the full credentials; the 2FA continuation - // sends only the short-lived pre-auth token plus the code. - const body = isTotpStep - ? { preAuthToken, ...(usingBackupCode ? { backupCode } : { totpCode }) } - : { email, password, turnstileToken }; - - const res = await fetch("/api/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); - const json = await res.json() as { - ok: boolean; - data?: { token: string }; - error?: string; - until?: number; - userId?: string; - methods?: string[]; - changeToken?: string; - preAuthToken?: string; - }; - - if (json.ok && json.data) { - await completeAuthentication(json.data.token); - } else if (json.error === "password_change_required" && json.changeToken) { - setChangeToken(json.changeToken); - setStep("force_password_change"); - } else if (json.error === "totp_required") { - // The password is no longer needed - the continuation uses preAuthToken. - setPreAuthToken(json.preAuthToken ?? null); - setPassword(""); - setStep("totp"); - } else if (json.error === "webauthn_required" && json.userId) { - setPendingUserId(json.userId); - setStep("webauthn"); - setLoading(false); - runWebauthnFlow(json.userId); - return; - } else if (json.error === "two_factor_required" && json.userId) { - setPendingUserId(json.userId); - setPreAuthToken(json.preAuthToken ?? null); - setPassword(""); - setStep("method_picker"); - } else if (json.error === "email_not_verified") { - setStep("email_unverified"); - } else if (json.error === "pre_auth_expired") { - handleBack(); - setError("Your sign-in attempt expired. Please sign in again."); - } else if (json.error === "invalid_backup_code") { - setError("Invalid or already-used backup code."); - setBackupCode(""); - } else if (json.error === "invalid_totp") { - setError("Invalid authenticator code. Please try again."); - setTotpCode(""); - } else if (res.status === 403) { - setError(moderationMessage(json.error, json.until)); - if (!isTotpStep) resetTurnstile(); - } else { - setError("Invalid email or password."); - if (!isTotpStep) resetTurnstile(); - } - } catch { - setError("Could not connect to the server. Please try again."); - if (!isTotpStep) resetTurnstile(); - } finally { - setLoading(false); - } - } - - function handleBack() { - setStep("credentials"); - setTotpCode(""); - setBackupCode(""); - setUsingBackupCode(false); - setPendingUserId(null); - setChangeToken(null); - setNewPassword(""); - setConfirmPassword(""); - // Returning to credentials discards the in-progress attempt: the password - // and pre-auth token must be re-established by signing in again. - setPassword(""); - setPreAuthToken(null); - setError(null); - } - - async function handleForceChangeSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - if (newPassword !== confirmPassword) { - setError("Passwords do not match."); - return; - } - if (!changeToken) return; - setLoading(true); - try { - const res = await fetch("/api/force-change-password", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ changeToken, newPassword }), - }); - const json = await res.json() as { - ok: boolean; - data?: { token: string }; - error?: string; - }; - if (json.ok && json.data) { - await completeAuthentication(json.data.token); - } else if (json.error === "password_too_weak") { - setError("Password is too weak. Please choose a stronger password."); - } else { - setError("Failed to change password. Please try signing in again."); - } - } catch { - setError("Could not connect to the server. Please try again."); - } finally { - setLoading(false); - } - } - - if (step === "email_unverified") { - return ( - e.preventDefault()} - hideSubmit - footer={ - - } - > -

- Your email address hasn't been verified yet. Check your inbox for the verification link, or request a new one. -

- {resendState === "sent" ? ( - - Verification email sent. Check your inbox. - - ) : ( - - )} -
- ); - } - - if (step === "force_password_change") { - return ( - -

- Your administrator requires you to change your password before continuing. -

-
- - setNewPassword(e.target.value)} - autoComplete="new-password" - required - autoFocus - /> -
-
- - setConfirmPassword(e.target.value)} - autoComplete="new-password" - required - /> -
-
- ); - } - - if (step === "totp") { - return ( - - } - > - {usingBackupCode ? ( -
- - setBackupCode(e.target.value.toUpperCase())} - maxLength={11} - autoFocus - autoComplete="off" - /> -

Enter one of your backup codes.

-
- ) : ( -
- - - - - - - - - - - -

Enter the 6-digit code from your authenticator app.

-
- )} - -
- ); - } - - if (step === "method_picker") { - return ( - e.preventDefault()} - hideSubmit - footer={ - - } - > -

- Your account has two-factor authentication enabled. Choose how to verify: -

-
- - - -
-
- ); - } - - if (step === "webauthn") { - return ( - e.preventDefault()} - hideSubmit - footer={ - - } - > - {/* While waiting, a live status line; after a failure the error Alert - above already says what happened, so don't repeat it - just offer - the two ways forward at full width like every other auth action. */} - {loading ? ( -

- Touch your security key when it flashes… -

- ) : ( -
- {!error && ( -

Security key verification failed or was cancelled.

- )} - - {/* Accounts with more than one factor arrive via the method picker - (which issues a preAuthToken) - let them switch instead of - retrying a key they may not have with them. */} - {preAuthToken && ( - - )} -
- )} -
- ); - } - - async function handleDevLogin(variant: "standard-free" | "standard-ink" | "admin-free" | "admin-ink") { - setLoading(true); - setError(null); - try { - const res = await fetch("/api/dev/quick-login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ variant }), - }); - const json = await res.json() as { ok: boolean; data?: { token: string } }; - if (json.ok && json.data) { - await completeAuthentication(json.data.token); - } else { - setError("Dev quick login failed."); - } - } catch { - setError("Could not connect to the server."); - } finally { - setLoading(false); - } - } - - return ( - - {reasonNotice} - - ) : null} - alternate={ - - } - footer={ - adminReturnTo ? "Your admin session will continue after sign-in." : ( - <> - Don't have an account?{" "} - - Sign up - - - ) - } - devPanel={import.meta.env.DEV ? ( -
- {( - [ - { label: "Standard", free: "standard-free", ink: "standard-ink" }, - { label: "Admin", free: "admin-free", ink: "admin-ink" }, - ] as const - ).map(({ label, free, ink }) => ( - - {label} - - - - ))} -
- ) : undefined} - > -
- - setEmail(e.target.value)} - autoComplete="username" - required - /> -
-
- {/* There's no self-serve reset yet, so point at the same support inbox - the moderation notices use rather than leave no way back in. */} -
- - - Forgot password? - -
- setPassword(e.target.value)} - autoComplete="current-password" - required - /> -
- {/* Left-align the challenge widget to the form edge like every other field. */} -
- -
-
- ); -} diff --git a/packages/frontend/src/pages/OAuthAuthorizePage.test.tsx b/packages/frontend/src/pages/OAuthAuthorizePage.test.tsx deleted file mode 100644 index 585360f4..00000000 --- a/packages/frontend/src/pages/OAuthAuthorizePage.test.tsx +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { MemoryRouter, Routes, Route } from "react-router-dom"; -import { OAuthAuthorizePage } from "./OAuthAuthorizePage"; -import { consumePendingOAuthNext, storePendingOAuthNext } from "@/lib/pendingOAuth"; - -const VALID_QUERY = - "?client_id=app1&redirect_uri=https%3A%2F%2Fapp.example%2Fcb&code_challenge=abc&code_challenge_method=S256&scope=openid+email&state=xyz"; - -function renderAt(path: string) { - return render( - - - } /> - - , - ); -} - -let assignMock: ReturnType; - -beforeEach(() => { - window.localStorage.clear(); - assignMock = vi.fn(); - // jsdom's real navigation isn't implemented; replace assign with a spy so we - // can assert the page-driven redirects (login bounce + final redirectTo). - Object.defineProperty(window, "location", { - value: { assign: assignMock, href: "http://localhost/", origin: "http://localhost", pathname: "/", search: "" }, - writable: true, - configurable: true, - }); -}); -afterEach(() => { - vi.restoreAllMocks(); -}); - -describe("OAuthAuthorizePage", () => { - it("shows an error when required OIDC params are missing", async () => { - window.localStorage.setItem("token", "jwt"); - renderAt("/oauth/authorize?client_id=app1"); // no redirect_uri / code_challenge - expect(await screen.findByText(/sign-in request was incomplete/i)).toBeInTheDocument(); - }); - - it("bounces to login when there is no session token", () => { - renderAt(`/oauth/authorize${VALID_QUERY}`); - expect(assignMock).toHaveBeenCalledWith(expect.stringMatching(/^\/login\?next=/)); - }); - - it("stashes the authorize URL before bouncing so a signup detour can resume", () => { - renderAt(`/oauth/authorize${VALID_QUERY}`); - expect(consumePendingOAuthNext()).toBe(`/oauth/authorize${VALID_QUERY}`); - }); - - it("renders the consent screen with the client name and scopes", async () => { - window.localStorage.setItem("token", "jwt"); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - status: 200, - json: () => - Promise.resolve({ - ok: true, - data: { - consentRequired: true, - client: { name: "Demo App" }, - scope: "openid email", - email: "user@example.com", - }, - }), - }), - ); - renderAt(`/oauth/authorize${VALID_QUERY}`); - - expect(await screen.findByText("Demo App")).toBeInTheDocument(); - expect(screen.getByText("user@example.com")).toBeInTheDocument(); - expect(screen.getByText(/confirm your identity/i)).toBeInTheDocument(); - expect(screen.getByText(/your email address/i)).toBeInTheDocument(); - expect(screen.getByRole("button", { name: /allow/i })).toBeInTheDocument(); - }); - - it("approves consent and follows the returned redirect", async () => { - window.localStorage.setItem("token", "jwt"); - const fetchMock = vi - .fn() - .mockResolvedValueOnce({ - status: 200, - json: () => - Promise.resolve({ - ok: true, - data: { consentRequired: true, client: { name: "Demo App" }, scope: "openid", email: "u@e.com" }, - }), - }) - .mockResolvedValueOnce({ - status: 200, - json: () => Promise.resolve({ ok: true, data: { redirectTo: "https://app.example/cb?code=zzz" } }), - }); - vi.stubGlobal("fetch", fetchMock); - renderAt(`/oauth/authorize${VALID_QUERY}`); - - await userEvent.click(await screen.findByRole("button", { name: /allow/i })); - - await waitFor(() => expect(assignMock).toHaveBeenCalledWith("https://app.example/cb?code=zzz")); - expect(fetchMock).toHaveBeenLastCalledWith( - "/api/oauth/authorize", - expect.objectContaining({ body: expect.stringContaining('"approved":true') }), - ); - }); - - it("clears a leftover stash when the flow completes with a redirect", async () => { - window.localStorage.setItem("token", "jwt"); - storePendingOAuthNext(`/oauth/authorize${VALID_QUERY}`); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - status: 200, - json: () => Promise.resolve({ ok: true, data: { redirectTo: "https://app.example/cb?code=zzz" } }), - }), - ); - renderAt(`/oauth/authorize${VALID_QUERY}`); - - await waitFor(() => expect(assignMock).toHaveBeenCalledWith("https://app.example/cb?code=zzz")); - expect(consumePendingOAuthNext()).toBeNull(); - }); - - it("denies consent and follows the returned redirect", async () => { - window.localStorage.setItem("token", "jwt"); - const fetchMock = vi - .fn() - .mockResolvedValueOnce({ - status: 200, - json: () => - Promise.resolve({ - ok: true, - data: { consentRequired: true, client: { name: "Demo App" }, scope: "openid", email: "u@e.com" }, - }), - }) - .mockResolvedValueOnce({ - status: 200, - json: () => Promise.resolve({ ok: true, data: { redirectTo: "https://app.example/cb?error=access_denied" } }), - }); - vi.stubGlobal("fetch", fetchMock); - renderAt(`/oauth/authorize${VALID_QUERY}`); - - await userEvent.click(await screen.findByRole("button", { name: /cancel/i })); - - await waitFor(() => expect(assignMock).toHaveBeenCalledWith("https://app.example/cb?error=access_denied")); - expect(fetchMock).toHaveBeenLastCalledWith( - "/api/oauth/authorize", - expect.objectContaining({ body: expect.stringContaining('"denied":true') }), - ); - }); - - it("maps a known server error code to a friendly message", async () => { - window.localStorage.setItem("token", "jwt"); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - status: 200, - json: () => Promise.resolve({ ok: false, error: "invalid_client" }), - }), - ); - renderAt(`/oauth/authorize${VALID_QUERY}`); - expect(await screen.findByText(/isn't recognised/i)).toBeInTheDocument(); - }); - - it("re-authenticates on a 401 response", async () => { - window.localStorage.setItem("token", "jwt"); - vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ status: 401, json: () => Promise.resolve({}) })); - renderAt(`/oauth/authorize${VALID_QUERY}`); - - await waitFor(() => expect(assignMock).toHaveBeenCalledWith(expect.stringMatching(/^\/login\?next=/))); - expect(window.localStorage.getItem("token")).toBeNull(); - }); - - it("shows a connection error when the request throws", async () => { - window.localStorage.setItem("token", "jwt"); - vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline"))); - renderAt(`/oauth/authorize${VALID_QUERY}`); - expect(await screen.findByText(/couldn't reach annex/i)).toBeInTheDocument(); - }); -}); diff --git a/packages/frontend/src/pages/OAuthAuthorizePage.tsx b/packages/frontend/src/pages/OAuthAuthorizePage.tsx deleted file mode 100644 index e03ff1c8..00000000 --- a/packages/frontend/src/pages/OAuthAuthorizePage.tsx +++ /dev/null @@ -1,222 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from "react"; -import { useLocation } from "react-router-dom"; -import { ShieldCheck } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { clearToken, getToken } from "@/lib/auth"; -import { clearPendingOAuthNext, storePendingOAuthNext } from "@/lib/pendingOAuth"; - -// Browser-facing OIDC authorization endpoint (the `authorization_endpoint` in -// discovery). A connected service's OIDC library redirects the browser here -// with the standard query params; this page orchestrates the Annex login (if -// needed), an optional consent gate, and the redirect back to the service with -// a single-use `code`. All validation + code minting happens server-side at -// /api/oauth/authorize - this page never constructs the redirect itself. - -interface OidcParams { - client_id: string; - redirect_uri: string; - response_type: string; - scope: string; - state?: string; - nonce?: string; - code_challenge: string; - code_challenge_method: string; -} - -interface ConsentInfo { - clientName: string; - scope: string; - email: string; -} - -const SCOPE_LABELS: Record = { - openid: "Confirm your identity", - profile: "Your display name and profile photo", - email: "Your email address", -}; - -const ERROR_MESSAGES: Record = { - invalid_client: "This app isn't recognised. The link may be misconfigured.", - invalid_redirect_uri: "This app's return address isn't allowed. The link may be misconfigured.", - missing_params: "The sign-in request was incomplete. Please return to the app and try again.", -}; - -function readParams(search: string): OidcParams | null { - const p = new URLSearchParams(search); - const client_id = p.get("client_id"); - const redirect_uri = p.get("redirect_uri"); - const code_challenge = p.get("code_challenge"); - if (!client_id || !redirect_uri || !code_challenge) return null; - return { - client_id, - redirect_uri, - response_type: p.get("response_type") ?? "code", - scope: p.get("scope") ?? "openid", - state: p.get("state") ?? undefined, - nonce: p.get("nonce") ?? undefined, - code_challenge, - code_challenge_method: p.get("code_challenge_method") ?? "", - }; -} - -export function OAuthAuthorizePage() { - const location = useLocation(); - const params = readParams(location.search); - const [status, setStatus] = useState<"loading" | "consent" | "error">("loading"); - const [error, setError] = useState(null); - const [consent, setConsent] = useState(null); - const startedRef = useRef(false); - - // POST the OIDC request to the backend. `decision` carries the consent - // outcome on the second call. A `redirectTo` in the response is followed - // verbatim (it always points at the validated redirect_uri). - const submit = useCallback( - async (decision?: { approved?: boolean; denied?: boolean }) => { - if (!params) { - setError(ERROR_MESSAGES.missing_params); - setStatus("error"); - return; - } - try { - const res = await fetch("/api/oauth/authorize", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${getToken()}`, - }, - body: JSON.stringify({ ...params, ...decision }), - }); - - // Token missing/expired → re-authenticate, then return here. The - // stash covers the detour through signup, where ?next= gets lost. - if (res.status === 401) { - clearToken(); - const next = location.pathname + location.search; - storePendingOAuthNext(next); - window.location.assign(`/login?next=${encodeURIComponent(next)}`); - return; - } - - const json = (await res.json()) as { - ok: boolean; - error?: string; - data?: { - redirectTo?: string; - consentRequired?: boolean; - client?: { name: string }; - scope?: string; - email?: string; - }; - }; - - if (!json.ok) { - setError(ERROR_MESSAGES[json.error ?? ""] ?? "This sign-in request couldn't be completed."); - setStatus("error"); - return; - } - - if (json.data?.redirectTo) { - // Flow completed - a leftover stash must not redirect a later sign-in. - clearPendingOAuthNext(); - window.location.assign(json.data.redirectTo); - return; - } - - if (json.data?.consentRequired) { - setConsent({ - clientName: json.data.client?.name ?? "An app", - scope: json.data.scope ?? params.scope, - email: json.data.email ?? "", - }); - setStatus("consent"); - return; - } - - setError("This sign-in request couldn't be completed."); - setStatus("error"); - } catch { - setError("Couldn't reach Annex to complete sign-in. Please try again."); - setStatus("error"); - } - }, - [params, location.pathname, location.search], - ); - - useEffect(() => { - if (startedRef.current) return; - startedRef.current = true; - - if (!params) { - setError(ERROR_MESSAGES.missing_params); - setStatus("error"); - return; - } - - // No Annex session yet → bounce through login and come straight back. - // The stash survives the signup detour (register → verify-email), where - // the ?next= query is lost. - if (!getToken()) { - const next = location.pathname + location.search; - storePendingOAuthNext(next); - window.location.assign(`/login?next=${encodeURIComponent(next)}`); - return; - } - - void submit(); - }, [params, location.pathname, location.search, submit]); - - return ( -
- - - - Sign in with Annex - - - {status === "loading" && ( -

Completing sign-in…

- )} - - {status === "consent" && consent && ( - <> -

- {consent.clientName} wants to sign you - in{consent.email ? <> as {consent.email} : null}. -

-
    - {consent.scope.split(/\s+/).filter(Boolean).map((s) => ( -
  • - - {SCOPE_LABELS[s] ?? s} -
  • - ))} -
-
- - -
- - )} - - {status === "error" && ( - <> -
- {error} -
- {/* The redirect_uri is unvalidated here, so we can't send the user - back to the service - but never leave them on a dead end. */} - - - )} -
-
-
- ); -} diff --git a/packages/frontend/src/pages/RegisterPage.tsx b/packages/frontend/src/pages/RegisterPage.tsx deleted file mode 100644 index 3b359c18..00000000 --- a/packages/frontend/src/pages/RegisterPage.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import { useCallback, useEffect, useState } from "react"; -import { useNavigate } from "react-router-dom"; -import zxcvbn from "zxcvbn"; -import { Check } from "lucide-react"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { AuthForm, PasswordInput, AUTH_INPUT_CLASS } from "@/components/AuthForm"; -import { Turnstile } from "@/components/Turnstile"; -import { getToken, setToken } from "@/lib/auth"; -import { consumePendingOAuthNext } from "@/lib/pendingOAuth"; - -const annexWordmark = Annex; - -const STRENGTH_LABELS = ["Very weak", "Weak", "Fair", "Strong", "Very strong"]; -// Scores below the server's bar (3 = "Strong") warm from red to amber; both -// passing scores share one green, so the meter itself says "good enough". -const STRENGTH_COLORS = [ - "bg-red-500", - "bg-orange-500", - "bg-amber-500", - "bg-emerald-500", - "bg-emerald-500", -]; -const MIN_SCORE = 3; - -export function RegisterPage() { - const navigate = useNavigate(); - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - const [password, setPassword] = useState(""); - const [turnstileToken, setTurnstileToken] = useState(null); - const [error, setError] = useState(null); - const [loading, setLoading] = useState(false); - - const handleTurnstileVerify = useCallback((token: string) => setTurnstileToken(token), []); - const handleTurnstileExpire = useCallback(() => setTurnstileToken(null), []); - - const strength = password ? zxcvbn(password) : null; - const score = strength?.score ?? -1; - - useEffect(() => { - if (getToken()) { - navigate("/dashboard", { replace: true }); - } - }, [navigate]); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(null); - if (score < MIN_SCORE) { - setError("Please choose a stronger password."); - return; - } - if (!turnstileToken) { - setError("Please complete the security challenge."); - return; - } - setLoading(true); - try { - const res = await fetch("/api/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name, email, password, turnstileToken }), - }); - const json = await res.json() as { ok: boolean; data?: { email: string; verificationSent: boolean; token?: string }; error?: string }; - if (json.ok && json.data) { - if (json.data.verificationSent) { - navigate("/check-email", { replace: true, state: { email: json.data.email } }); - } else if (json.data.token) { - setToken(json.data.token); - // Resume a "Sign in with Annex" flow interrupted by signup. - navigate(consumePendingOAuthNext() ?? "/dashboard", { replace: true }); - } else { - navigate("/login", { replace: true }); - } - } else { - setError( - res.status === 409 - ? "An account with that email already exists." - : res.status === 403 && json.error - ? json.error - : "Registration failed. Please try again.", - ); - } - } catch { - setError("Could not connect to the server. Please try again."); - } finally { - setLoading(false); - } - } - - return ( - - Already have an account?{" "} - - Sign in - - - } - > -
- - setName(e.target.value)} - required - /> -
-
- - setEmail(e.target.value)} - required - /> -
-
- - setPassword(e.target.value)} - aria-describedby="password-hint" - required - /> - {/* The real rule (auth worker routes/register.ts): zxcvbn score >= 3, - i.e. "Strong" on the meter below. There is no fixed length/character - rule, so don't invent one here. */} -

- Must rate “Strong” or better on the strength meter. A phrase of a few unrelated words works well. -

- {password && ( -
-
- {[0, 1, 2, 3, 4].map(i => ( - -

- {STRENGTH_LABELS[score]} - {score >= MIN_SCORE ? ( - - - ) : ( - · needs to reach Strong - )} -

-
- )} -
- {/* Left-align the challenge widget to the form edge like every other field. */} -
- -
- - ); -} diff --git a/packages/frontend/src/pages/SignInPage.tsx b/packages/frontend/src/pages/SignInPage.tsx new file mode 100644 index 00000000..1bc9f87f --- /dev/null +++ b/packages/frontend/src/pages/SignInPage.tsx @@ -0,0 +1,128 @@ +import { Fragment, useEffect, useMemo, useState } from "react"; +import { useLocation, useNavigate } from "react-router-dom"; +import { Button } from "@/components/ui/button"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { AuthForm, AUTH_BUTTON_CLASS } from "@/components/AuthForm"; +import { getToken, setToken } from "@/lib/auth"; +import { IDENTITY_ORIGIN, safeReturnTo, startSignIn } from "@/lib/signIn"; + +// /login and /register. Accounts live on auth.cubityfir.st now, so both just +// hand off to the hosted sign-in page (which links to registration and comes +// back here afterwards). The page itself only shows when there's something +// to say first: a forced sign-out reason, or the local-dev quick logins. + +function reasonNotice(reason: string | null): string | null { + const contact = "Please email docs@cubityfir.st for further details."; + if (reason === "disabled") return `Your account has been disabled. ${contact}`; + if (reason === "suspended") return `Your account is currently suspended. ${contact}`; + if (reason === "expired") return "Your session has ended. Please sign in again."; + return null; +} + +const annexWordmark = Annex; + +type DevVariant = "standard-free" | "standard-ink" | "admin-free" | "admin-ink"; + +export function SignInPage({ mode = "signin" }: { mode?: "signin" | "register" }) { + const location = useLocation(); + const navigate = useNavigate(); + const params = new URLSearchParams(location.search); + const reason = params.get("reason"); + const notice = reasonNotice(reason); + const returnTo = useMemo( + () => safeReturnTo(params.get("next")) ?? safeReturnTo((location.state as { from?: string } | null)?.from) ?? "/dashboard", + // eslint-disable-next-line react-hooks/exhaustive-deps + [location.search, location.state], + ); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + // Hand straight off to the identity service unless there's a notice to + // read first or this is a dev build (where the quick logins live). A + // disabled/suspended user would otherwise loop straight back here. + const stayOnPage = Boolean(notice && reason !== "expired") || import.meta.env.DEV; + useEffect(() => { + if (getToken()) { + navigate(returnTo, { replace: true }); + return; + } + if (!stayOnPage) startSignIn(returnTo); + }, [navigate, returnTo, stayOnPage]); + + async function handleDevLogin(variant: DevVariant) { + setLoading(true); + setError(null); + try { + const res = await fetch("/api/dev/quick-login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ variant }), + }); + const json = (await res.json()) as { ok: boolean; data?: { token: string } }; + if (json.ok && json.data) { + setToken(json.data.token); + navigate(returnTo, { replace: true }); + } else { + setError("Dev quick login failed (is DEV_QUICK_LOGIN=true set for the api worker?)."); + } + } catch { + setError("Could not connect to the server."); + } finally { + setLoading(false); + } + } + + const host = new URL(IDENTITY_ORIGIN).host; + + return ( + { + e.preventDefault(); + setLoading(true); + startSignIn(returnTo); + }} + header={notice ? ( + + {notice} + + ) : null} + footer={ + <> + Annex accounts are managed at{" "} + + {host} + + {mode === "register" ? ". Create one there and you'll come straight back." : "."} + + } + devPanel={import.meta.env.DEV ? ( +
+ {( + [ + { label: "Standard", free: "standard-free", ink: "standard-ink" }, + { label: "Admin", free: "admin-free", ink: "admin-ink" }, + ] as const + ).map(({ label, free, ink }) => ( + + {label} + + + + ))} +
+ ) : undefined} + > +

+ {mode === "register" + ? "You'll create your account on the sign-in page, then come back here." + : "You'll sign in on the secure sign-in page, then come back here."} +

+
+ ); +} diff --git a/packages/frontend/src/pages/UserSettingsPage.tsx b/packages/frontend/src/pages/UserSettingsPage.tsx index b2e46cb1..13a6a3d8 100644 --- a/packages/frontend/src/pages/UserSettingsPage.tsx +++ b/packages/frontend/src/pages/UserSettingsPage.tsx @@ -1,11 +1,7 @@ import { useState, useEffect, useRef, type ReactNode } from "react"; -import { useNavigate, useOutletContext, Link } from "react-router-dom"; +import { useOutletContext, Link } from "react-router-dom"; import type { DocsLayoutContext } from "@/layouts/DocsLayout"; -import zxcvbn from "zxcvbn"; -import QRCode from "react-qr-code"; -import { startRegistration } from "@simplewebauthn/browser"; import { Button } from "@/components/ui/button"; -import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, @@ -17,19 +13,18 @@ import { AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Input } from "@/components/ui/input"; -import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"; import { Label } from "@/components/ui/label"; import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { Separator } from "@/components/ui/separator"; import { useToast } from "@/hooks/use-toast"; -import { use2FA } from "@/hooks/use2FA"; -import { getToken, clearToken } from "@/lib/auth"; +import { getToken } from "@/lib/auth"; +import { IDENTITY_ACCOUNT_URL, IDENTITY_SECURITY_URL } from "@/lib/signIn"; import { UserAvatar } from "@/components/UserAvatar"; import { AvatarCropDialog } from "@/components/AvatarCropDialog"; import { InlineSaveControls, SavedIndicator, useSavedFlash } from "@/components/InlineSaveControls"; import { InkSparkle } from "@/components/InkSparkle"; -import { LockOpen, LockKeyhole, Key, Trash2, Loader2, Copy, CheckCircle2, AlertCircle, Camera, Smartphone, Tablet, Laptop, Monitor, Upload, Sparkles, ChevronDown, Globe, X, Search, Plus, Sun, Moon, Mail, RotateCcw, Check, Star } from "lucide-react"; +import { LockKeyhole, Trash2, Loader2, Copy, AlertCircle, Camera, Upload, Sparkles, ChevronDown, Globe, X, Search, Plus, Sun, Moon, RotateCcw, Check, Star, ExternalLink } from "lucide-react"; import { Textarea } from "@/components/ui/textarea"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { ColorPicker } from "@/components/ui/color-picker"; @@ -80,74 +75,6 @@ const USER_SETTINGS_GROUPS: SettingsGroupDef[] = [ { id: "danger", label: "Danger zone" }, ]; -const STRENGTH_LABELS = ["Very weak", "Weak", "Fair", "Strong", "Very strong"]; -const STRENGTH_COLORS = [ - "bg-red-500", - "bg-orange-500", - "bg-yellow-500", - "bg-blue-500", - "bg-green-500", -]; - -interface WebAuthnCredential { - id: string; - name: string; - created_at: string; -} - -type DeviceKind = "phone" | "tablet" | "laptop" | "desktop"; - -interface ActiveSession { - id: string; - createdAt: number; - lastUsedAt: number; - expiresAt: number; - deviceKind: DeviceKind | null; - clientLabel: string | null; - ip: string | null; - current: boolean; -} - -function DeviceIcon({ kind }: { kind: DeviceKind | null }) { - const Icon = kind === "phone" ? Smartphone : kind === "tablet" ? Tablet : kind === "laptop" ? Laptop : Monitor; - return ( -
- -
- ); -} - -function formatRelative(timestampMs: number): string { - const diffMs = Date.now() - timestampMs; - const minutes = Math.round(diffMs / 60_000); - if (minutes < 1) return "just now"; - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.round(minutes / 60); - if (hours < 24) return `${hours}h ago`; - const days = Math.round(hours / 24); - if (days < 30) return `${days}d ago`; - return new Date(timestampMs).toLocaleDateString(); -} - -// Labelled status chip for the security headings - colour plus words, so an -// unconfigured method reads as "not set up" rather than as an error. -function SecurityStatus({ ok, on, off, title }: { ok: boolean; on: string; off: string; title: string }) { - return ( - - {ok ? - ); -} - // Header row of a security row card: title + status pill + description on the // left, the outline action(s) right-aligned (stacked below on narrow screens), // matching the Account/Danger zone row geometry. @@ -167,37 +94,22 @@ function SecurityRowHeader({ title, status, description, action }: { title: stri } export function UserSettingsPage() { - const navigate = useNavigate(); const { updateInkAppearance, readingFont, editingFont, uiFont, updateFontAppearance, currentUser, theme, customColor, customThemingEnabled, updateTheme } = useOutletContext(); const [fontPrefsBusy, setFontPrefsBusy] = useState(false); const [themePrefsBusy, setThemePrefsBusy] = useState(false); const [userId, setUserId] = useState(""); const [name, setName] = useState(""); - const [currentName, setCurrentName] = useState(""); const [email, setEmail] = useState(""); - const [emailVerified, setEmailVerified] = useState(null); - const [emailVerificationEnabled, setEmailVerificationEnabled] = useState(false); - const [resendingVerification, setResendingVerification] = useState(false); - // Seconds until the verification email can be re-sent again (0 = ready). - // Same 30s convention as CheckEmailPage's resend button. - const [resendCooldown, setResendCooldown] = useState(0); - const [saving, setSaving] = useState(false); - - // Change email state. `pendingEmail` is a confirm-first change awaiting the - // link sent to the new address (only set while the verification flag is on). - const [pendingEmail, setPendingEmail] = useState(null); - const [changeEmailOpen, setChangeEmailOpen] = useState(false); - const [newEmail, setNewEmail] = useState(""); - const [emailCurrentPassword, setEmailCurrentPassword] = useState(""); - const [emailSaving, setEmailSaving] = useState(false); - const [emailChangeResending, setEmailChangeResending] = useState(false); - const [emailChangeCancelling, setEmailChangeCancelling] = useState(false); + // The identity service's account pages (from GET /me; build-time defaults + // until it loads). + const [accountUrl, setAccountUrl] = useState(IDENTITY_ACCOUNT_URL); + const [securityUrl, setSecurityUrl] = useState(IDENTITY_SECURITY_URL); + const identityHost = new URL(accountUrl).host; const [timezone, setTimezone] = useState(null); const [timezonePrivate, setTimezonePrivate] = useState(false); const [timezoneSaving, setTimezoneSaving] = useState(false); const [timezoneSaved, flashTimezoneSaved] = useSavedFlash(); - const [nameSaved, flashNameSaved] = useSavedFlash(); const [bioSaved, flashBioSaved] = useSavedFlash(); const [avatarKey, setAvatarKey] = useState(0); @@ -213,53 +125,6 @@ export function UserSettingsPage() { const changePhotoButtonRef = useRef(null); const { toast } = useToast(); - // TOTP state - const [totpEnabled, setTotpEnabled] = useState(false); - const [totpLoading, setTotpLoading] = useState(true); - - // TOTP setup flow state - const [setupStep, setSetupStep] = useState<"idle" | "qr" | "verify">("idle"); - const [pendingSecret, setPendingSecret] = useState(null); - const [pendingUri, setPendingUri] = useState(null); - const [setupCode, setSetupCode] = useState(""); - const [setupLoading, setSetupLoading] = useState(false); - const [securityEnrollmentPassword, setSecurityEnrollmentPassword] = useState(""); - - // WebAuthn state - const [webauthnCredentials, setWebauthnCredentials] = useState([]); - const [webauthnLoading, setWebauthnLoading] = useState(true); - const [addingKey, setAddingKey] = useState(false); - const [newKeyName, setNewKeyName] = useState(""); - const [registerLoading, setRegisterLoading] = useState(false); - const [processingKeyId, setProcessingKeyId] = useState(null); - - // Backup codes state - const [backupCodesOpen, setBackupCodesOpen] = useState(false); - const [backupCodes, setBackupCodes] = useState([]); - const [backupCodesLoading, setBackupCodesLoading] = useState(false); - const [confirmBackupCodesOpen, setConfirmBackupCodesOpen] = useState(false); - - // Delete account state - const [deleteAccountOpen, setDeleteAccountOpen] = useState(false); - const [deleteCurrentPassword, setDeleteCurrentPassword] = useState(""); - const [deletingAccount, setDeletingAccount] = useState(false); - const [ownedSitesOpen, setOwnedSitesOpen] = useState(false); - const [ownedSites, setOwnedSites] = useState>([]); - const [ownedOrgs, setOwnedOrgs] = useState>([]); - - // Change password state - const [changePasswordOpen, setChangePasswordOpen] = useState(false); - const [currentPassword, setCurrentPassword] = useState(""); - const [newPassword, setNewPassword] = useState(""); - const [confirmPassword, setConfirmPassword] = useState(""); - const [passwordSaving, setPasswordSaving] = useState(false); - - // Active sessions state - const [sessions, setSessions] = useState([]); - const [sessionsLoading, setSessionsLoading] = useState(true); - const [sessionRevokingId, setSessionRevokingId] = useState(null); - const [revokingOthers, setRevokingOthers] = useState(false); - // Annex Ink billing state. personalPlanStatus === "granted" means a comp // grant (no Stripe linkage); we hide the Manage button in that case. // personalPlanCancelAt is non-null when the user has scheduled a @@ -309,24 +174,17 @@ export function UserSettingsPage() { const [favouriteNoteExpanded, setFavouriteNoteExpanded] = useState>({}); const FAV_NOTE_MAX = 140; - const { runWithTwoFA, twoFADialog, busy: twoFABusy, active: twoFAActive } = use2FA({ - totp: totpEnabled, - webauthn: webauthnCredentials.length > 0, - }); - useEffect(() => { const token = getToken(); if (!token) return; fetch("/api/me", { headers: { Authorization: `Bearer ${token}` } }) - .then(r => r.json() as Promise<{ ok: boolean; data?: { name: string; email: string; emailVerified: boolean; emailVerificationEnabled: boolean; pendingEmail: string | null; userId: string; timezone: string | null; bio: string | null; handle?: string | null; handleLocked?: boolean; personalPlan: "free" | "ink"; personalPlanSince: number | null; personalPlanStatus: string | null; personalPlanCancelAt: number | null; personalPlanStyle: string | null; personalPresenceColor: string | null; personalCritSparkles: boolean } }>) + .then(r => r.json() as Promise<{ ok: boolean; data?: { name: string; email: string; accountUrl?: string; securityUrl?: string; userId: string; timezone: string | null; bio: string | null; handle?: string | null; handleLocked?: boolean; personalPlan: "free" | "ink"; personalPlanSince: number | null; personalPlanStatus: string | null; personalPlanCancelAt: number | null; personalPlanStyle: string | null; personalPresenceColor: string | null; personalCritSparkles: boolean } }>) .then(json => { if (json.ok && json.data) { - setCurrentName(json.data.name); setName(json.data.name); setEmail(json.data.email); - setEmailVerified(json.data.emailVerified); - setEmailVerificationEnabled(json.data.emailVerificationEnabled); - setPendingEmail(json.data.pendingEmail ?? null); + if (json.data.accountUrl) setAccountUrl(json.data.accountUrl); + if (json.data.securityUrl) setSecurityUrl(json.data.securityUrl); setUserId(json.data.userId); setTimezone(json.data.timezone); setTimezonePrivate(json.data.timezone === null); @@ -358,37 +216,6 @@ export function UserSettingsPage() { .catch(() => {}) .finally(() => setFavouritesLoading(false)); - fetch("/api/me/totp/status", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({}), - }) - .then(r => r.json() as Promise<{ ok: boolean; data?: { enabled: boolean } }>) - .then(json => { - if (json.ok && json.data) setTotpEnabled(json.data.enabled); - }) - .catch(() => {}) - .finally(() => setTotpLoading(false)); - - fetch("/api/me/webauthn/credentials", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({}), - }) - .then(r => r.json() as Promise<{ ok: boolean; data?: { credentials: WebAuthnCredential[] } }>) - .then(json => { - if (json.ok && json.data) setWebauthnCredentials(json.data.credentials); - }) - .catch(() => {}) - .finally(() => setWebauthnLoading(false)); - - fetch("/api/me/sessions", { headers: { Authorization: `Bearer ${token}` } }) - .then(r => r.json() as Promise<{ ok: boolean; data?: { sessions: ActiveSession[] } }>) - .then(json => { - if (json.ok && json.data) setSessions(json.data.sessions); - }) - .catch(() => {}) - .finally(() => setSessionsLoading(false)); }, []); function handleAvatarChange(e: React.ChangeEvent) { @@ -437,58 +264,6 @@ export function UserSettingsPage() { } } - // Tick the resend cooldown down once a second while it's running. - useEffect(() => { - if (resendCooldown <= 0) return; - const t = setTimeout(() => setResendCooldown(c => c - 1), 1000); - return () => clearTimeout(t); - }, [resendCooldown]); - - async function handleResendVerification() { - if (!email || resendCooldown > 0) return; - setResendingVerification(true); - try { - const token = getToken(); - await fetch("/api/verify-email/resend", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ email }), - }); - toast({ title: "Verification email sent" }); - setResendCooldown(30); - } catch { - toast({ title: "Could not send verification email", variant: "destructive" }); - } finally { - setResendingVerification(false); - } - } - - async function handleSaveName(e: React.FormEvent) { - e.preventDefault(); - if (!name.trim() || name.trim() === currentName) return; - setSaving(true); - try { - const token = getToken(); - const res = await fetch("/api/me", { - method: "PATCH", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ name: name.trim() }), - }); - const json = await res.json() as { ok: boolean; data?: { name: string } }; - if (json.ok && json.data) { - setCurrentName(json.data.name); - setName(json.data.name); - flashNameSaved(); - } else { - toast({ title: "Failed to update name", variant: "destructive" }); - } - } catch { - toast({ title: "Could not connect to the server", variant: "destructive" }); - } finally { - setSaving(false); - } - } - async function saveTimezone(newTimezone: string | null) { setTimezoneSaving(true); try { @@ -511,492 +286,6 @@ export function UserSettingsPage() { } } - async function handleSetupStart() { - setSetupLoading(true); - try { - const token = getToken(); - const res = await fetch("/api/me/totp/setup", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({}), - }); - const json = await res.json() as { ok: boolean; data?: { secret: string; uri: string } }; - if (json.ok && json.data) { - setPendingSecret(json.data.secret); - setPendingUri(json.data.uri); - setSetupStep("qr"); - } else { - toast({ title: "Failed to start 2FA setup", variant: "destructive" }); - } - } catch { - toast({ title: "Could not connect to the server", variant: "destructive" }); - } finally { - setSetupLoading(false); - } - } - - async function handleSetupVerify(e: React.FormEvent) { - e.preventDefault(); - if (!pendingSecret || !setupCode || (!twoFactorProtected && !securityEnrollmentPassword)) return; - await runWithTwoFA(async (verification) => { - setSetupLoading(true); - try { - const token = getToken(); - const res = await fetch("/api/me/totp/enable", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ - secret: pendingSecret, - code: setupCode, - totpCode: verification.totpCode, - challengeId: verification.challengeId, - webauthnResponse: verification.webauthnResponse, - backupCode: verification.backupCode, - currentPassword: securityEnrollmentPassword, - }), - }); - const json = await res.json() as { ok: boolean; error?: string }; - if (json.ok) { - setTotpEnabled(true); - setSetupStep("idle"); - setPendingSecret(null); - setPendingUri(null); - setSetupCode(""); - setSecurityEnrollmentPassword(""); - toast({ title: "Two-factor authentication enabled" }); - return undefined; - } - return json.error === "invalid_totp" ? "Invalid authenticator code." : "Invalid code. Please try again."; - } catch { - return "Could not connect to the server."; - } finally { - setSetupLoading(false); - } - }); - } - - async function handleGenerateBackupCodes() { - await runWithTwoFA(async (verification) => { - setBackupCodesLoading(true); - try { - const token = getToken(); - const res = await fetch("/api/me/totp/backup-codes/generate", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify(verification), - }); - const json = await res.json() as { ok: boolean; data?: { codes: string[] }; error?: string }; - if (json.ok && json.data) { - setBackupCodes(json.data.codes); - setBackupCodesOpen(true); - return undefined; - } - return json.error === "invalid_totp" ? "Invalid authenticator code." : "Failed to generate backup codes."; - } catch { - return "Could not connect to the server."; - } finally { - setBackupCodesLoading(false); - } - }); - } - - async function handleDisableTOTP() { - await runWithTwoFA(async (verification) => { - const token = getToken(); - const res = await fetch("/api/me/totp/disable", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify(verification), - }); - const json = await res.json() as { ok: boolean }; - if (json.ok) { - setTotpEnabled(false); - toast({ title: "Two-factor authentication disabled" }); - return undefined; - } - return "Invalid code. Please try again."; - }); - } - - async function handleRegisterKey(e: React.FormEvent) { - e.preventDefault(); - if (!twoFactorProtected && !securityEnrollmentPassword) return; - await runWithTwoFA(async (verification) => { - setRegisterLoading(true); - try { - const token = getToken(); - const startRes = await fetch("/api/me/webauthn/register/start", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({}), - }); - const startJson = await startRes.json() as { - ok: boolean; - data?: { options: Record; challengeId: string }; - }; - if (!startJson.ok || !startJson.data) { - return "Failed to start security key registration."; - } - - const { options, challengeId: registerChallengeId } = startJson.data; - let credential; - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - credential = await startRegistration(options as any); - } catch { - return "Security key registration was cancelled or failed."; - } - - const finishRes = await fetch("/api/me/webauthn/register/finish", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ - challengeId: registerChallengeId, - response: credential, - name: newKeyName.trim() || "Security Key", - totpCode: verification.totpCode, - challengeId2fa: verification.challengeId, - webauthnResponse: verification.webauthnResponse, - backupCode: verification.backupCode, - currentPassword: securityEnrollmentPassword, - }), - }); - const finishJson = await finishRes.json() as { ok: boolean; error?: string }; - if (finishJson.ok) { - // Reload credentials list - const listRes = await fetch("/api/me/webauthn/credentials", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({}), - }); - const listJson = await listRes.json() as { - ok: boolean; - data?: { credentials: WebAuthnCredential[] }; - }; - if (listJson.ok && listJson.data) setWebauthnCredentials(listJson.data.credentials); - setAddingKey(false); - setNewKeyName(""); - setSecurityEnrollmentPassword(""); - toast({ title: "Security key added" }); - } else { - return finishJson.error ?? "Failed to register security key."; - } - } catch { - return "Could not connect to the server."; - } finally { - setRegisterLoading(false); - } - }); - } - - async function handleDeleteKey(credentialId: string) { - setProcessingKeyId(credentialId); - await runWithTwoFA(async (verification) => { - const token = getToken(); - const res = await fetch("/api/me/webauthn/credentials/delete", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ credentialId, ...verification }), - }); - const json = await res.json() as { ok: boolean; error?: string }; - if (json.ok) { - setWebauthnCredentials(prev => prev.filter(c => c.id !== credentialId)); - toast({ title: "Security key removed" }); - return undefined; - } - if (json.error === "invalid_totp") return "Invalid code. Please try again."; - return "Failed to remove security key."; - }); - setProcessingKeyId(null); - } - - function resetPasswordDialog() { - setCurrentPassword(""); - setNewPassword(""); - setConfirmPassword(""); - } - - async function handleChangePassword(e: React.FormEvent) { - e.preventDefault(); - if (!currentPassword || !newPassword || newPassword !== confirmPassword) return; - if (zxcvbn(newPassword).score < 3) return; - await runWithTwoFA(async (verification) => { - setPasswordSaving(true); - try { - const token = getToken(); - const res = await fetch("/api/me/password", { - method: "PATCH", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ - currentPassword, - newPassword, - totpCode: verification.totpCode, - challengeId: verification.challengeId, - webauthnResponse: verification.webauthnResponse, - backupCode: verification.backupCode, - }), - }); - const json = await res.json() as { ok: boolean; error?: string }; - if (json.ok) { - resetPasswordDialog(); - setChangePasswordOpen(false); - toast({ title: "Password changed" }); - return undefined; - } - if (json.error === "invalid_totp") return "Invalid authenticator code."; - if (json.error === "password_too_weak") { - toast({ title: "New password is too weak", variant: "destructive" }); - return undefined; - } - toast({ title: "Current password is incorrect", variant: "destructive" }); - return undefined; - } catch { - return "Could not connect to the server."; - } finally { - setPasswordSaving(false); - } - }); - } - - function resetEmailDialog() { - setNewEmail(""); - setEmailCurrentPassword(""); - } - - async function handleChangeEmail(e: React.FormEvent) { - e.preventDefault(); - if (!newEmail.trim() || !emailCurrentPassword) return; - await runWithTwoFA(async (verification) => { - setEmailSaving(true); - try { - const token = getToken(); - const res = await fetch("/api/me/email", { - method: "PATCH", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ - newEmail: newEmail.trim(), - currentPassword: emailCurrentPassword, - totpCode: verification.totpCode, - challengeId: verification.challengeId, - webauthnResponse: verification.webauthnResponse, - backupCode: verification.backupCode, - }), - }); - const json = await res.json() as { ok: boolean; error?: string; data?: { applied: boolean; email?: string; pendingEmail?: string } }; - if (json.ok && json.data) { - resetEmailDialog(); - setChangeEmailOpen(false); - if (json.data.applied && json.data.email) { - setEmail(json.data.email); - setEmailVerified(false); - toast({ title: "Email address updated" }); - } else if (json.data.pendingEmail) { - setPendingEmail(json.data.pendingEmail); - toast({ title: `Confirmation link sent to ${json.data.pendingEmail}` }); - } - return undefined; - } - if (json.error === "invalid_totp") return "Invalid authenticator code."; - // Stale client MFA state (enrolled in another tab): the string routes - // to a toast via runWithTwoFA since no 2FA dialog is open. - if (json.error === "mfa_required") return "Two-factor authentication is required – reload the page and try again."; - if (json.error === "send_failed") { - toast({ title: "Couldn't send the confirmation email – try again", variant: "destructive" }); - return undefined; - } - if (res.status === 409) { - toast({ title: "That email address is already in use", variant: "destructive" }); - return undefined; - } - if (json.error === "same_email") { - toast({ title: "That's already your email address", variant: "destructive" }); - return undefined; - } - if (res.status === 429) { - toast({ title: "Too many attempts – try again in a minute", variant: "destructive" }); - return undefined; - } - if (res.status === 401) { - toast({ title: "Current password is incorrect", variant: "destructive" }); - return undefined; - } - toast({ title: "Failed to change email address", variant: "destructive" }); - return undefined; - } catch { - return "Could not connect to the server."; - } finally { - setEmailSaving(false); - } - }); - } - - async function handleResendEmailChange() { - setEmailChangeResending(true); - try { - const token = getToken(); - const res = await fetch("/api/me/email/resend", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - }); - const json = await res.json() as { ok: boolean; error?: string }; - if (json.ok) { - toast({ title: "Confirmation email re-sent" }); - } else if (json.error === "no_pending_change") { - // The pending change expired server-side - clear the stale UI. - setPendingEmail(null); - toast({ title: "This email change has expired – request it again", variant: "destructive" }); - } else if (json.error === "too_soon" || json.error === "rate_limited") { - toast({ title: "Give it a few minutes before resending", variant: "destructive" }); - } else if (json.error === "send_failed") { - toast({ title: "Couldn't send the email – try again in a few minutes", variant: "destructive" }); - } else { - toast({ title: "Could not re-send confirmation email", variant: "destructive" }); - } - } catch { - toast({ title: "Could not connect to the server", variant: "destructive" }); - } finally { - setEmailChangeResending(false); - } - } - - async function handleCancelEmailChange() { - setEmailChangeCancelling(true); - try { - const token = getToken(); - const res = await fetch("/api/me/email/cancel", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - }); - const json = await res.json() as { ok: boolean }; - if (json.ok) { - setPendingEmail(null); - toast({ title: "Email change cancelled" }); - } else { - toast({ title: "Could not cancel the email change", variant: "destructive" }); - } - } catch { - toast({ title: "Could not connect to the server", variant: "destructive" }); - } finally { - setEmailChangeCancelling(false); - } - } - - function handleCancelSetup() { - setSetupStep("idle"); - setPendingSecret(null); - setPendingUri(null); - setSetupCode(""); - setSecurityEnrollmentPassword(""); - } - - async function handleRevokeSession(id: string) { - setSessionRevokingId(id); - try { - const token = getToken(); - const res = await fetch("/api/me/sessions/revoke", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ sessionId: id }), - }); - if (res.ok) { - setSessions(prev => prev.filter(s => s.id !== id)); - toast({ title: "Session revoked" }); - } else { - toast({ title: "Could not revoke session", variant: "destructive" }); - } - } catch { - toast({ title: "Could not revoke session", variant: "destructive" }); - } finally { - setSessionRevokingId(null); - } - } - - async function handleRevokeOthers() { - setRevokingOthers(true); - try { - const token = getToken(); - const res = await fetch("/api/me/sessions/revoke-others", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - }); - if (res.ok) { - setSessions(prev => prev.filter(s => s.current)); - toast({ title: "Other sessions revoked" }); - } else { - toast({ title: "Could not revoke sessions", variant: "destructive" }); - } - } catch { - toast({ title: "Could not revoke sessions", variant: "destructive" }); - } finally { - setRevokingOthers(false); - } - } - - async function handleDeleteButtonClick() { - const token = getToken(); - try { - const [projectsRes, orgsRes] = await Promise.all([ - fetch("/api/projects", { headers: { Authorization: `Bearer ${token}` } }), - fetch("/api/organizations", { headers: { Authorization: `Bearer ${token}` } }), - ]); - const projectsJson = await projectsRes.json() as { ok: boolean; data?: Array<{ id: string; name: string; role: string }> }; - const orgsJson = await orgsRes.json() as { ok: boolean; data?: Array<{ id: string; name: string; role: string; site_count: number; member_count: number }> }; - const ownedSitesList = (projectsJson.data ?? []).filter(p => p.role === "owner").map(p => ({ id: p.id, name: p.name })); - const ownedOrgsList = (orgsJson.data ?? []).filter(o => o.role === "owner").map(o => ({ id: o.id, name: o.name })); - if (ownedSitesList.length > 0 || ownedOrgsList.length > 0) { - setOwnedSites(ownedSitesList); - setOwnedOrgs(ownedOrgsList); - setOwnedSitesOpen(true); - return; - } - } catch { - // fall through to confirmation if we can't check - } - setDeleteCurrentPassword(""); - setDeleteAccountOpen(true); - } - - async function handleDeleteAccount() { - const currentPassword = deleteCurrentPassword; - if (!currentPassword) return; - - setDeleteAccountOpen(false); - await runWithTwoFA(async (verification) => { - setDeletingAccount(true); - try { - const token = getToken(); - const res = await fetch("/api/me", { - method: "DELETE", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, - body: JSON.stringify({ ...verification, currentPassword }), - }); - const json = await res.json() as { ok: boolean; error?: string }; - if (json.ok) { - clearToken(); - navigate("/login"); - return undefined; - } - if (json.error === "invalid_totp") return "Invalid authenticator code."; - if (json.error === "invalid_backup_code") return "Invalid backup code."; - if (json.error === "Unauthorized") return "Current password is incorrect."; - if (json.error === "rate_limited") return "Too many attempts. Please wait a minute and try again."; - if (json.error === "owns_projects") return "Delete or transfer the sites you own before deleting your account."; - if (json.error === "owns_organizations") return "Delete the organizations you own before deleting your account."; - return "Failed to delete account. Please try again."; - } catch { - return "Could not connect to the server."; - } finally { - setDeletingAccount(false); - setDeleteCurrentPassword(""); - } - }); - } - - const twoFactorProtected = totpEnabled || webauthnCredentials.length > 0; - - // Posts to the auth-side billing endpoint (proxied by /api in dev) and - // navigates the browser to the Stripe-hosted url. We intentionally use - // window.location rather than fetch+redirect so the back button works. async function startCheckoutOrPortal(path: "/api/billing/checkout" | "/api/billing/portal") { if (billingBusy) return; setBillingBusy(true); @@ -1392,8 +681,7 @@ export function UserSettingsPage() { { id: "favourites", label: "Favourite sites", group: "profile" }, { id: "billing", label: "Billing", group: "plan" }, { id: "appearance", label: "Appearance", group: "preferences" }, - { id: "two-factor", label: "Two-factor & password", group: "security" }, - { id: "sessions", label: "Active sessions", group: "security" }, + { id: "security", label: "Sign-in & security", group: "security" }, { id: "danger", label: "Danger zone", group: "danger", danger: true }, ]; @@ -1550,141 +838,40 @@ export function UserSettingsPage() {
)} - {/* Email + Display name share one bordered card, in the same row - pattern as the toggle rows below: Email is a title with the - address as its description line and its controls (verification - status, Change) on the right; Display name is a labelled input. */} -
-
-
-
- - {/* The current email isn't editable in place - changing it - goes through the "Change" button, a password-confirmed - dialog. The borderless read-only input keeps the label - association and the value the e2e specs read. */} - -
-
- {emailVerified === false && emailVerificationEnabled && ( - - - - - - {resendCooldown > 0 ? `Sent – resend in ${resendCooldown}s` : "Resend verification email"} - - - )} - {emailVerified === true && emailVerificationEnabled && ( - - - - - - Email verified - - - )} - {emailVerified === false && emailVerificationEnabled && ( - - - - - - Email not verified - - - )} - -
+ {/* Email + display name come from the identity service (read-only + here); "Manage" opens the account page on auth.cubityfir.st. The + read-only inputs keep the label association and the values the + e2e specs read. */} +
+
+
+ +
- {pendingEmail && ( -
-

- Confirmation sent to {pendingEmail} – check that inbox to finish the change. -

-
- - -
-
- )}
- -
-
+
+
- -
-
- setName(currentName)} - saveDisabled={!name.trim() || name.trim() === currentName} - resetLabel="Reset display name" - saveLabel="Save display name" - > - setName(e.target.value)} - className="flex-1" - required - /> - +
+
- +
{/* Profile-card visibility rows: bordered row cards, matching the site-settings row pattern. Each reveals its detail inline. */} @@ -2447,220 +1634,37 @@ export function UserSettingsPage() { - {/* Security section */} -
-

Two-factor & password

-

Protect sign-in with a second factor, and change your password.

- + {/* Sign-in & security: owned by the identity service. */} +
+
- {/* Authenticator app */}
- )} - description="Use a TOTP authenticator app (Google Authenticator, Authy, 1Password, etc.) as a second factor." - action={totpLoading ? ( - - ) : totpEnabled ? ( - <> - - - - ) : setupStep === "idle" ? ( - - ) : null} - /> - {!totpLoading && !totpEnabled && setupStep !== "idle" && ( -
-
-

- Scan this QR code with your authenticator app - - (Google Authenticator, Authy, 1Password, etc.) - -

- {pendingUri && ( -
- -
- )} -
- -
-

Can't scan? Enter this key manually:

- - {pendingSecret} - -
- -
-
- - - - - - - - - - - -
- {!twoFactorProtected && ( -
- - setSecurityEnrollmentPassword(e.target.value)} - autoComplete="current-password" - required - /> -

Confirm your password before adding your first sign-in factor.

-
- )} -
- - -
-
-
- )} -
- - {/* Passkeys / security keys */} -
- 0} on="Enabled" off="Not set up" title={webauthnCredentials.length > 0 ? "Passkey or security key registered" : "No passkeys registered"} /> - )} - description="Sign in with a passkey instead of your password, or use a hardware security key (YubiKey, etc.) as a second factor." - action={webauthnLoading ? ( - - ) : !addingKey ? ( - - ) : null} + } /> - {!webauthnLoading && (webauthnCredentials.length > 0 || addingKey) && ( -
- {webauthnCredentials.length > 0 && ( -
    - {webauthnCredentials.map(cred => { - const isProcessing = processingKeyId === cred.id; - return ( -
  • -
    -
    - - {cred.name} - - {new Date(cred.created_at).toLocaleDateString(undefined, { dateStyle: "medium" })} - -
    - {isProcessing ? ( - - ) : ( - - )} -
    -
  • - ); - })} -
- )} - {addingKey && ( -
-
- - setNewKeyName(e.target.value)} - placeholder="Security Key" - maxLength={64} - autoFocus - /> -
- {!twoFactorProtected && ( -
- - setSecurityEnrollmentPassword(e.target.value)} - autoComplete="current-password" - required - /> -

Confirm your password before adding your first sign-in factor.

-
- )} -
- - -
-
- )} -
- )}
- - {/* Change password */}
{ resetPasswordDialog(); setChangePasswordOpen(true); }}> - Change password + } /> @@ -2670,412 +1674,22 @@ export function UserSettingsPage() { - {/* Active sessions */} -
-

Active sessions

-

- Devices currently signed in to your account. Revoke any you don't recognise. -

- - {sessionsLoading ? ( -
- -
- ) : sessions.length === 0 ? ( -
- No other devices are signed in. -
- ) : ( -
    - {/* Current session first, so "this device" is always on top. */} - {[...sessions].sort((a, b) => Number(b.current) - Number(a.current)).map(s => ( -
  • -
    - -
    -
    -

    {s.clientLabel ?? "Unknown device"}

    - {s.current && ( - - This device - - )} -
    -

    - {s.ip ? `${s.ip} · Signed in` : "Signed in"} {formatRelative(s.createdAt)} -

    -
    -
    - {!s.current && ( - - )} -
  • - ))} -
- )} - - {sessions.some(s => !s.current) && ( - - )} -
- - - {/* Danger zone */}
- {deletingAccount ? "Deleting…" : "Delete account"} + } />
- - - - - - {ownedOrgs.length > 0 - ? "Transfer or delete your sites and organizations first" - : "Transfer or delete your sites first"} - - -
-

- {ownedSites.length > 0 && ownedOrgs.length > 0 - ? "You own the following sites and organizations and cannot delete your account until you transfer ownership or delete them:" - : ownedOrgs.length > 0 - ? `You own the following ${ownedOrgs.length === 1 ? "organization" : "organizations"} and cannot delete your account until you transfer ownership or delete ${ownedOrgs.length === 1 ? "it" : "them"}:` - : `You own the following ${ownedSites.length === 1 ? "site" : "sites"} and cannot delete your account until you transfer ownership or delete ${ownedSites.length === 1 ? "it" : "them"}:`} -

-
    - {ownedSites.map(site => ( -
  • - setOwnedSitesOpen(false)} - > - {site.name} - -
  • - ))} - {ownedOrgs.map(org => ( -
  • - setOwnedSitesOpen(false)} - > - {org.name} - - {" "}(organization) -
  • - ))} -
-
-
-
- - setOwnedSitesOpen(false)}>OK - -
-
- - { - setDeleteAccountOpen(open); - if (!open) setDeleteCurrentPassword(""); - }} - > - - - Delete your account? - - This will permanently delete your account and all associated data. This action cannot be undone. - - - - {personalPlan === "ink" && personalPlanStatus !== "granted" && ( -
- - - You have an active Annex Ink subscription. It will be cancelled immediately when your account is deleted.{" "} - You will not be refunded for the remainder of the current billing period. - -
- )} - -
- - setDeleteCurrentPassword(event.target.value)} - autoComplete="current-password" - disabled={deletingAccount} - /> -

- Required to confirm this irreversible action. -

-
- - - Cancel - - Yes, delete my account - - -
-
- - { if (!open && twoFAActive) return; if (!open) resetPasswordDialog(); setChangePasswordOpen(open); }}> - { if (twoFAActive) e.preventDefault(); }} - onFocusOutside={e => { if (twoFAActive) e.preventDefault(); }} - > - - Change password - -
-
- - setCurrentPassword(e.target.value)} - autoComplete="current-password" - required - /> -
- -
- - setNewPassword(e.target.value)} - autoComplete="new-password" - aria-describedby="new-password-hint" - required - /> - {/* Same rule and copy as RegisterPage: the auth worker - rejects anything below zxcvbn score 3 ("Strong"), and - the submit button stays disabled until then - say so, - or a disabled button gives no reason. */} -

- Must rate “Strong” or better on the strength meter. A phrase of a few unrelated words works well. -

- {newPassword && (() => { - const score = zxcvbn(newPassword).score; - return ( -
-
- {[0, 1, 2, 3, 4].map(i => ( - -

{STRENGTH_LABELS[score]}

-
- ); - })()} -
- -
- - setConfirmPassword(e.target.value)} - autoComplete="new-password" - aria-invalid={confirmPassword.length > 0 && newPassword !== confirmPassword} - aria-describedby={confirmPassword && newPassword !== confirmPassword ? "confirm-password-error" : undefined} - required - /> - {confirmPassword && newPassword !== confirmPassword && ( - - )} -
- - - - - - - -
- - { if (!open && twoFAActive) return; if (!open) resetEmailDialog(); setChangeEmailOpen(open); }}> - { if (twoFAActive) e.preventDefault(); }} - onFocusOutside={e => { if (twoFAActive) e.preventDefault(); }} - > - - Change email address - -
-
- - setNewEmail(e.target.value)} - autoComplete="email" - required - /> - {emailVerificationEnabled && ( -

- We'll send a confirmation link to the new address. Your email only changes once you click it. -

- )} -
-
- - setEmailCurrentPassword(e.target.value)} - autoComplete="current-password" - required - /> -
-
- - - - -
-
- - - - - Generate new backup codes? - - This creates a fresh set of backup codes and permanently invalidates any codes generated before, so any previously saved codes will stop working. - - - - Cancel - { - setConfirmBackupCodesOpen(false); - void handleGenerateBackupCodes(); - }} - > - Generate codes - - - - - - - - - Backup codes - -

- Use these codes if your TOTP device is lost. Each code can only be used once. Generating new codes invalidates all previous ones. -

-
- {backupCodes.map(code => ( - - {code} - - ))} -
- - - - -
-
- - {twoFADialog} ); } diff --git a/packages/frontend/src/pages/VerifyEmailPage.test.tsx b/packages/frontend/src/pages/VerifyEmailPage.test.tsx deleted file mode 100644 index 7a49ac31..00000000 --- a/packages/frontend/src/pages/VerifyEmailPage.test.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { render, screen, waitFor } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; -import { MemoryRouter, Routes, Route } from "react-router-dom"; -import { VerifyEmailPage } from "./VerifyEmailPage"; -import { consumePendingOAuthNext, storePendingOAuthNext } from "@/lib/pendingOAuth"; - -function renderAt(path: string) { - return render( - - - } /> - DASHBOARD
} /> - LOGIN
} /> - OAUTH_AUTHORIZE
} /> - - , - ); -} - -function mockFetchOnce(json: unknown) { - return vi.fn().mockResolvedValue({ json: () => Promise.resolve(json) }); -} - -beforeEach(() => { - window.localStorage.clear(); -}); -afterEach(() => { - vi.restoreAllMocks(); -}); - -describe("VerifyEmailPage", () => { - it("shows the failure/resend UI when there is no token", () => { - renderAt("/verify-email"); - expect(screen.getByText(/invalid or has expired/i)).toBeInTheDocument(); - expect(screen.getByLabelText(/email address/i)).toBeInTheDocument(); - }); - - it("never signs the user in - verification sends them to sign in", async () => { - vi.stubGlobal("fetch", mockFetchOnce({ ok: true, data: { verified: true } })); - renderAt("/verify-email?token=good"); - expect(await screen.findByText(/your email has been verified/i)).toBeInTheDocument(); - expect(window.localStorage.getItem("token")).toBeNull(); - }); - - it("leaves a stashed OAuth authorize flow for LoginPage to resume", async () => { - const next = "/oauth/authorize?client_id=app1&redirect_uri=https%3A%2F%2Fapp.example%2Fcb&code_challenge=abc"; - storePendingOAuthNext(next); - vi.stubGlobal("fetch", mockFetchOnce({ ok: true, data: { verified: true } })); - renderAt("/verify-email?token=good"); - expect(await screen.findByText(/your email has been verified/i)).toBeInTheDocument(); - // Not consumed here - the post-verification sign-in picks it up. - expect(consumePendingOAuthNext()).toBe(next); - }); - - it("shows the failure state when the token is rejected", async () => { - vi.stubGlobal("fetch", mockFetchOnce({ ok: false, error: "invalid_or_expired_token" })); - renderAt("/verify-email?token=bad"); - expect(await screen.findByText(/invalid or has expired/i)).toBeInTheDocument(); - }); - - it("shows the email-updated state for a change-confirm link without logging in", async () => { - vi.stubGlobal("fetch", mockFetchOnce({ ok: true, data: { verified: true, emailChanged: true, userId: "u1", email: "new@example.com" } })); - renderAt("/verify-email?token=change"); - expect(await screen.findByText(/your email address has been updated/i)).toBeInTheDocument(); - // No session is minted from a change-confirm link. - expect(window.localStorage.getItem("token")).toBeNull(); - expect(screen.queryByText("DASHBOARD")).not.toBeInTheDocument(); - }); - - it("shows the expired-change state pointing back to settings, without the resend form", async () => { - vi.stubGlobal("fetch", mockFetchOnce({ ok: false, error: "change_link_expired" })); - renderAt("/verify-email?token=stale"); - expect(await screen.findByText(/request the change again from your account settings/i)).toBeInTheDocument(); - expect(screen.queryByLabelText(/email address/i)).not.toBeInTheDocument(); - }); - - it("shows the email-taken state without the signup resend form", async () => { - vi.stubGlobal("fetch", mockFetchOnce({ ok: false, error: "email_taken" })); - renderAt("/verify-email?token=change"); - expect(await screen.findByText(/claimed by another account/i)).toBeInTheDocument(); - expect(screen.queryByLabelText(/email address/i)).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: /resend verification email/i })).not.toBeInTheDocument(); - }); - - it("resends a verification email from the failure state", async () => { - const fetchMock = vi.fn().mockResolvedValue({ json: () => Promise.resolve({ ok: true }) }); - vi.stubGlobal("fetch", fetchMock); - renderAt("/verify-email"); - - await userEvent.type(screen.getByLabelText(/email address/i), "user@example.com"); - await userEvent.click(screen.getByRole("button", { name: /resend verification email/i })); - - expect(await screen.findByText(/verification email sent/i)).toBeInTheDocument(); - expect(fetchMock).toHaveBeenCalledWith("/api/verify-email/resend", expect.objectContaining({ method: "POST" })); - }); -}); diff --git a/packages/frontend/src/pages/VerifyEmailPage.tsx b/packages/frontend/src/pages/VerifyEmailPage.tsx deleted file mode 100644 index ce627cf6..00000000 --- a/packages/frontend/src/pages/VerifyEmailPage.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { useEffect, useState } from "react"; -import { useLocation, useNavigate } from "react-router-dom"; -import { ArrowLeft } from "lucide-react"; -import { AuthShell, AUTH_BUTTON_CLASS, AUTH_INPUT_CLASS } from "@/components/AuthForm"; -import { Alert, AlertDescription } from "@/components/ui/alert"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { Skeleton } from "@/components/ui/skeleton"; - -export function VerifyEmailPage() { - const location = useLocation(); - const navigate = useNavigate(); - const token = new URLSearchParams(location.search).get("token"); - - const [state, setState] = useState<"loading" | "success" | "changed" | "failure" | "email_taken" | "change_expired">( - token ? "loading" : "failure", - ); - const [resendEmail, setResendEmail] = useState(""); - const [resendState, setResendState] = useState<"idle" | "sending" | "sent" | "error">("idle"); - - useEffect(() => { - if (!token) return; - - fetch("/api/verify-email", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ token }), - }) - .then(res => res.json() as Promise<{ ok: boolean; data?: { verified: boolean; emailChanged?: boolean }; error?: string }>) - .then(json => { - // Verification links never mint a session - the clicker proved mailbox - // access, not account ownership - so success always sends the user to - // sign in. A "Sign in with Annex" flow interrupted by signup stays - // stashed and LoginPage resumes it after that sign-in. - if (json.ok && json.data?.emailChanged) { - setState("changed"); - return; - } - if (!json.ok && json.error === "email_taken") { - setState("email_taken"); - return; - } - if (!json.ok && json.error === "change_link_expired") { - setState("change_expired"); - return; - } - setState(json.ok ? "success" : "failure"); - }) - .catch(() => setState("failure")); - }, [token, navigate]); - - async function handleResend() { - if (!resendEmail.trim()) return; - setResendState("sending"); - try { - await fetch("/api/verify-email/resend", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: resendEmail.trim() }), - }); - setResendState("sent"); - } catch { - setResendState("error"); - } - } - - return ( - -
- {/* Same heading block as the other auth screens: left-aligned, the - wordmark then the step as the

. */} -
- - Annex - -

Email verification

-
- - {state === "loading" && ( -
- - Verifying your email… - - - -
- )} - - {state === "success" && ( - <> - - - Your email has been verified. You can now sign in to your account. - - - - - )} - - {state === "changed" && ( - <> - - - Your email address has been updated. Use it the next time you sign in. - - - - - )} - - {state === "change_expired" && ( - <> - - - This email-change link is no longer valid. Request the change again from your account settings. - - - - - )} - - {state === "email_taken" && ( - <> - - - That email address was claimed by another account before you confirmed. Request the change again from your account settings. - - - - - )} - - {state === "failure" && ( - <> - - - This verification link is invalid or has expired. Request a new one below. - - -
-
- - setResendEmail(e.target.value)} - /> -
- {resendState === "sent" && ( - - Verification email sent. Check your inbox. - - )} - {resendState === "error" && ( - - Failed to send email. Please try again. - - )} - - -
- - )} -

-
- ); -} diff --git a/packages/frontend/worker/customHost.test.ts b/packages/frontend/worker/customHost.test.ts index d3478208..3710ab9d 100644 --- a/packages/frontend/worker/customHost.test.ts +++ b/packages/frontend/worker/customHost.test.ts @@ -61,7 +61,7 @@ describe("app-host robots.txt", () => { }); it("blocks the app, auth flows and private API but keeps published sites crawlable", () => { - for (const path of ["/api/", "/oauth/", "/login", "/register", "/settings", "/projects/", "/dashboard", "/invite/", "/u/", "/@"]) { + for (const path of ["/api/", "/oauth/", "/auth/", "/login", "/register", "/settings", "/projects/", "/dashboard", "/invite/", "/u/", "/@"]) { expect(APP_ROBOTS_TXT).toContain(`Disallow: ${path}\n`); } expect(APP_ROBOTS_TXT).toContain("Allow: /api/public/\n"); @@ -69,3 +69,17 @@ describe("app-host robots.txt", () => { expect(APP_ROBOTS_TXT).not.toMatch(/Disallow: \/\n/); }); }); + +describe("/oauth/authorize redirect shim", () => { + it("sends the old app-origin authorization URL to the identity service, query string included", async () => { + const env = { IDENTITY_ORIGIN: "https://auth.example" } as Env; + const res = await worker.fetch(new Request("https://docs.cubityfir.st/oauth/authorize?client_id=x&state=s%20t&redirect_uri=https%3A%2F%2Fapp"), env); + expect(res.status).toBe(302); + expect(res.headers.get("Location")).toBe("https://auth.example/oauth/authorize?client_id=x&state=s%20t&redirect_uri=https%3A%2F%2Fapp"); + }); + + it("defaults to auth.cubityfir.st", async () => { + const res = await worker.fetch(new Request("https://docs.cubityfir.st/oauth/authorize?a=1"), {} as Env); + expect(res.headers.get("Location")).toBe("https://auth.cubityfir.st/oauth/authorize?a=1"); + }); +}); diff --git a/packages/frontend/worker/index.ts b/packages/frontend/worker/index.ts index a309e8eb..3e43f7cd 100644 --- a/packages/frontend/worker/index.ts +++ b/packages/frontend/worker/index.ts @@ -8,6 +8,19 @@ import { export interface Env { API: Fetcher; ASSETS: Fetcher; + // Public origin of the identity service (auth.cubityfir.st). + IDENTITY_ORIGIN?: string; +} + +// The OIDC authorization endpoint moved from this app origin to the identity +// service. Keep the old URL working (query string included) for any service +// that hard-coded https://docs.cubityfir.st/oauth/authorize. +export function oauthAuthorizeRedirect(env: Pick, url: URL): Response { + const origin = (env.IDENTITY_ORIGIN || "https://auth.cubityfir.st").replace(/\/+$/, ""); + return new Response(null, { + status: 302, + headers: { Location: `${origin}/oauth/authorize${url.search}`, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }, + }); } function extractFirstParagraph(content: string, maxLength = 160): string { @@ -218,8 +231,7 @@ export const APP_ROBOTS_TXT = [ "Disallow: /stripe/", "Disallow: /login", "Disallow: /register", - "Disallow: /check-email", - "Disallow: /verify-email", + "Disallow: /auth/", "Disallow: /demo", "Disallow: /dashboard", "Disallow: /projects/", @@ -395,6 +407,8 @@ export default { if (!isAppHost(host)) { const customResponse = await handleCustomHost(request, env, url, host); if (customResponse) return customResponse; + } else if (url.pathname === "/oauth/authorize") { + return oauthAuthorizeRedirect(env, url); } else if (url.pathname === "/robots.txt") { return new Response(APP_ROBOTS_TXT, { headers: { "Content-Type": "text/plain; charset=UTF-8", "Cache-Control": "public, max-age=3600" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 73b8bc26..68d00b59 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -281,9 +281,6 @@ importers: '@radix-ui/react-tooltip': specifier: ^1.1.0 version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4) - '@simplewebauthn/browser': - specifier: ^9.0.0 - version: 9.0.1 '@tailwindcss/typography': specifier: ^0.5.19 version: 0.5.19(tailwindcss@4.2.1) @@ -338,9 +335,6 @@ importers: react-markdown: specifier: ^10.1.0 version: 10.1.0(@types/react@19.2.14)(react@19.2.4) - react-qr-code: - specifier: ^2.0.15 - version: 2.0.18(react@19.2.4) react-resizable-panels: specifier: ^4 version: 4.7.3(react-dom@19.2.4(react@19.2.4))(react@19.2.4) @@ -380,9 +374,6 @@ importers: yjs: specifier: ^13.6.0 version: 13.6.30 - zxcvbn: - specifier: ^4.4.2 - version: 4.4.2 devDependencies: '@cloudflare/workers-types': specifier: ^4.0.0 @@ -420,9 +411,6 @@ importers: '@types/topojson-specification': specifier: ^1.0.5 version: 1.0.5 - '@types/zxcvbn': - specifier: ^4.4.5 - version: 4.4.5 '@vitejs/plugin-react': specifier: ^4.3.0 version: 4.7.0(vite@6.4.2(@types/node@22.19.15)(jiti@2.6.1)(lightningcss@1.31.1)(sass@1.51.0)(terser@5.48.0)) @@ -3087,9 +3075,6 @@ packages: '@shikijs/vscode-textmate@10.0.2': resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} - '@simplewebauthn/browser@9.0.1': - resolution: {integrity: sha512-wD2WpbkaEP4170s13/HUxPcAV5y4ZXaKo1TfNklS5zDefPinIgXOpgz1kpEvobAsaLPa2KeH7AKKX/od1mrBJw==} - '@simplewebauthn/server@9.0.3': resolution: {integrity: sha512-FMZieoBosrVLFxCnxPFD9Enhd1U7D8nidVDT4MsHc6l4fdVcjoeHjDueeXCloO1k5O/fZg1fsSXXPKbY2XTzDA==} engines: {node: '>=16.0.0'} @@ -5339,9 +5324,6 @@ packages: pwacompat@2.0.17: resolution: {integrity: sha512-6Du7IZdIy7cHiv7AhtDy4X2QRM8IAD5DII69mt5qWibC2d15ZU8DmBG1WdZKekG11cChSu4zkSUGPF9sweOl6w==} - qr.js@0.0.0: - resolution: {integrity: sha512-c4iYnWb+k2E+vYpRimHqSu575b1/wKl4XFeJGpFmrJQz5I88v9aY2czh7s0w36srfCM1sXgC/xpoJz5dJfq+OQ==} - qs@6.16.1: resolution: {integrity: sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==} engines: {node: '>=0.6'} @@ -5408,11 +5390,6 @@ packages: '@types/react': '>=18' react: '>=18' - react-qr-code@2.0.18: - resolution: {integrity: sha512-v1Jqz7urLMhkO6jkgJuBYhnqvXagzceg3qJUWayuCK/c6LTIonpWbwxR1f1APGd4xrW/QcQEovNrAojbUz65Tg==} - peerDependencies: - react: '*' - react-refresh@0.17.0: resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==} engines: {node: '>=0.10.0'} @@ -9114,10 +9091,6 @@ snapshots: '@shikijs/vscode-textmate@10.0.2': {} - '@simplewebauthn/browser@9.0.1': - dependencies: - '@simplewebauthn/types': 9.0.1 - '@simplewebauthn/server@9.0.3': dependencies: '@hexagon/base64': 1.1.28 @@ -11732,8 +11705,6 @@ snapshots: pwacompat@2.0.17: {} - qr.js@0.0.0: {} - qs@6.16.1: dependencies: es-define-property: 1.0.1 @@ -11863,12 +11834,6 @@ snapshots: transitivePeerDependencies: - supports-color - react-qr-code@2.0.18(react@19.2.4): - dependencies: - prop-types: 15.8.1 - qr.js: 0.0.0 - react: 19.2.4 - react-refresh@0.17.0: {} react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.4): From bdab74299a80ef8d7e66d699d4fef44455cbce76 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:38:52 +0000 Subject: [PATCH 2/3] 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. --- CLAUDE.md | 29 +- docs/oauth/CONSUMER_PROMPT.md | 86 ----- docs/oauth/README.md | 206 ++--------- memories/Oidc-Provider.md | 72 ---- packages/auth/cloudflare.config.ts | 38 -- packages/auth/src/cleanup.sqlite.test.ts | 33 -- packages/auth/src/index.test.ts | 23 -- packages/auth/src/index.ts | 92 +---- packages/auth/src/oidc.test.ts | 257 -------------- packages/auth/src/oidc.ts | 329 ------------------ .../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 ---- packages/auth/src/routes/register.ts | 2 +- scripts/gen-oidc-key.mjs | 57 --- scripts/register-oauth-client.mjs | 106 ------ 22 files changed, 36 insertions(+), 2426 deletions(-) delete mode 100644 docs/oauth/CONSUMER_PROMPT.md delete mode 100644 memories/Oidc-Provider.md delete mode 100644 packages/auth/src/index.test.ts delete mode 100644 packages/auth/src/oidc.test.ts delete mode 100644 packages/auth/src/oidc.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 scripts/gen-oidc-key.mjs delete mode 100644 scripts/register-oauth-client.mjs diff --git a/CLAUDE.md b/CLAUDE.md index f91a8cd4..3c4e65df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,25 +88,16 @@ 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-auth no longer serves `/oauth/*` or `/.well-known/*`, +has no `auth.cubityfir.st` routes (that hostname is cubityfirst-auth's Custom +Domain - **never re-add those triggers**), and holds no OIDC signing key. OAuth +clients are managed at `auth.cubityfir.st/admin/clients`. The old +`docs.cubityfir.st/oauth/authorize` URL redirects to the provider. See +`docs/oauth/README.md`. ## Tests diff --git a/docs/oauth/CONSUMER_PROMPT.md b/docs/oauth/CONSUMER_PROMPT.md deleted file mode 100644 index 5a6b5f19..00000000 --- a/docs/oauth/CONSUMER_PROMPT.md +++ /dev/null @@ -1,86 +0,0 @@ -# Prompt: wire up "Sign in with Annex" (OIDC) - -Copy everything in the block below into the other project's Claude agent. First -replace the three `<…>` placeholders with the values from -`scripts/register-oauth-client.mjs` (and the exact callback URL you registered). - -> ⚠️ The callback/redirect URL you put below must be registered **exactly** with -> the Annex provider (it's an exact-match allowlist). If you change it, re-register. - ---- - -``` -Add "Sign in with Annex" to this project. Annex is a standard OpenID Connect -(OIDC) provider - use a well-maintained OIDC client library for this stack, not -a hand-rolled flow. - -PROVIDER (everything else is discoverable): -- Issuer: https://auth.cubityfir.st -- Discovery: https://auth.cubityfir.st/.well-known/openid-configuration -- Flow: Authorization Code + PKCE (S256). id_tokens are RS256; verify - offline via the provider's JWKS (in the discovery doc). -- Scopes: openid profile email -- Claims you get: sub (stable unique user id - key your users on THIS, never on - email), email, email_verified, name, picture (avatar URL; may - 404 if the user has no avatar - fall back to your own placeholder). - -CREDENTIALS (store the secret server-side only - never ship it to the browser): -- client_id: -- client_secret: (omit if this is a public/SPA client) -- redirect_uri: (e.g. https://app.example.com/api/auth/callback/annex) - -REQUIREMENTS: -1. Configure the OIDC client from the discovery URL - do NOT hardcode the - authorization/token/userinfo/jwks endpoints (the authorization endpoint is on - a different host than the issuer; discovery handles that for you). -2. Use Authorization Code flow with PKCE (code_challenge_method=S256). -3. Send and verify `state` (CSRF) and a `nonce` (bound into the id_token). -4. Request scope "openid profile email". -5. On callback: exchange the code at the token endpoint (send the PKCE - code_verifier; include the client_secret only for a confidential/server-side - client), then VERIFY the id_token: signature against JWKS, and the iss, aud - (== client_id), exp, and nonce claims. Most OIDC libraries do this for you - - make sure it's enabled, not skipped. -6. Establish your app's own session from the verified identity. Use `sub` as the - primary key for the Annex identity; treat email as mutable. -7. The redirect_uri registered with Annex must match byte-for-byte what your app - sends (scheme, host, port, path). -8. (If this client was granted the `roles` scope) the id_token / userinfo carry a - `roles` string array. Gate admin-only features on `roles.includes("admin")` - - do NOT hardcode a user id or email for admin access. - -STACK-SPECIFIC GUIDANCE (pick what fits this project): -- Next.js / Auth.js (NextAuth): add a custom OIDC provider with - `{ id: "annex", name: "Annex", type: "oidc", issuer: "https://auth.cubityfir.st", - clientId, clientSecret, authorization: { params: { scope: "openid profile email" } }, - checks: ["pkce", "state", "nonce"] }`. Auth.js fetches discovery + JWKS and - verifies the id_token automatically. -- Node/Express: use `openid-client`. `Issuer.discover("https://auth.cubityfir.st")`, - then a `Client`, then `generators.codeVerifier()`/`codeChallenge()`, `client.authorizationUrl(...)`, - and `client.callback(...)` (which validates the id_token, state, nonce, PKCE). -- Python: `authlib` (`authlib.integrations.*` OAuth with - `server_metadata_url=".../.well-known/openid-configuration"`). -- Go: `coreos/go-oidc` + `golang.org/x/oauth2` (provider via `oidc.NewProvider`, - verify with `provider.Verifier`). -- Anything else: any conformant OIDC/OAuth2-with-PKCE client works - point it at - the discovery URL. - -Then: -- Add a "Sign in with Annex" button that starts the flow. -- Store the client_secret in the project's secret manager / env (never in client - code or the repo). -- Tell me the EXACT callback URL you wired up so it can be registered with Annex - (or confirm it matches above). -- Verify end-to-end: click the button, sign in, confirm a session is created and - the id_token's signature/iss/aud/nonce are validated. Show me the verified - claims you receive. -``` - ---- - -## If it's a browser-only SPA (no backend) - -Register the client with `--public` (no secret), and have the agent use a -browser OIDC library with PKCE (e.g. `oidc-client-ts`). The token endpoint -accepts public clients with PKCE and no secret. Never embed a `client_secret` in -front-end code. diff --git a/docs/oauth/README.md b/docs/oauth/README.md index 1cd406d0..0951283e 100644 --- a/docs/oauth/README.md +++ b/docs/oauth/README.md @@ -1,185 +1,21 @@ -# Sign in with Annex - OIDC provider - -Annex is an **OpenID Connect (OIDC) identity provider**. Other services you run -can offer a "Sign in with Annex" button: the user authenticates once against -their Annex account (password + TOTP + passkeys all apply, because the real -Annex login is reused) and your service receives a verified identity. - -It is a standard **authorization-code + PKCE** flow, so consuming services use -any off-the-shelf OIDC client library - there is no Annex-specific SDK. - -- **Provider side** (this doc): how the flow is built, the one-time setup, and - how to register a connected service. -- **Consumer side**: hand [`CONSUMER_PROMPT.md`](./CONSUMER_PROMPT.md) to the - agent working on the other service, filled in with that service's `client_id`, - `client_secret`, and callback URL. - ---- - -## Endpoints - -| Purpose | URL | -| --- | --- | -| Issuer (`iss`) | `https://auth.cubityfir.st` | -| Discovery | `https://auth.cubityfir.st/.well-known/openid-configuration` | -| Authorization (browser) | `https://docs.cubityfir.st/oauth/authorize` | -| Token | `https://auth.cubityfir.st/oauth/token` | -| UserInfo | `https://auth.cubityfir.st/oauth/userinfo` | -| JWKS | `https://auth.cubityfir.st/oauth/jwks` | - -The **authorization endpoint lives on the app origin** (`docs.cubityfir.st`), -not the issuer host. That's deliberate: the user's Annex session is a -browser-local token on the app origin, so the consent/login step has to happen -there. OIDC allows endpoints on different hosts - every client reads the exact -URLs from the discovery document, so this is transparent to consumers. - -**Scopes:** `openid` (required, yields `sub`), `profile` (adds `name` and -`picture` - a URL to the user's avatar; it 404s for users who haven't uploaded -one, so fall back to your own placeholder), `email` -(adds `email`, `email_verified`), `roles` (adds a `roles` array - `["user","admin"]` -for Annex platform-admins, `["user"]` otherwise; read live from `users.is_admin`). -A client must be granted `roles` at registration to receive it; gate admin-only -features on `roles.includes("admin")`. -**Signing:** RS256. id_tokens and access tokens are verifiable offline against -the JWKS. This key is **separate** from the Annex session `JWT_SECRET` - no -Annex secret is ever shared with a connected service. -**Tokens:** `id_token` + `access_token` (both JWT, 1-hour lifetime). - ---- - -## One-time provider setup - -1. **Generate the RS256 signing key** and store it as a secret: - ```bash - node scripts/gen-oidc-key.mjs - cd packages/auth && npx wrangler secret put OIDC_PRIVATE_KEY - # paste the printed JSON line when prompted - ``` - The public half is derived automatically and published at `/oauth/jwks`. - -2. **Add DNS for the issuer host.** In the Cloudflare dashboard, on the - **`cubityfir.st`** zone, add a **proxied** (orange-cloud) DNS record for - `auth` - e.g. `AAAA auth 100::` (a placeholder; the Worker route handles the - request, the record just makes the hostname resolve to Cloudflare's edge). - The `auth.cubityfir.st/oauth/*` and `/.well-known/*` routes in - `packages/auth/cloudflare.config.ts` attach the auth worker to those paths only - - nothing else on the auth worker is reachable at that host. - -3. **Apply the migration** (creates `oauth_clients` + `oauth_codes`): - ```bash - pnpm migrations:remote # cf d1 migrations apply for both DBs - # local dev: pnpm migrations:local - ``` - -4. **Deploy** the three workers that gained code (new tables aren't read by - `loadCurrentSession`, so the auth/api/admin triple-redeploy rule does *not* - apply here - but auth, api, and frontend each changed): - ```bash - cd packages/auth && pnpm run deploy # endpoints + routes (cf deploy) - cd packages/api && pnpm run deploy # /oauth/authorize proxy - cd packages/frontend && pnpm run deploy # /oauth/authorize SPA page - ``` - -5. **Smoke-test discovery + JWKS:** - ```bash - curl https://auth.cubityfir.st/.well-known/openid-configuration - curl https://auth.cubityfir.st/oauth/jwks - ``` - ---- - -## Registering a connected service - -### Option A - Admin dashboard (recommended) - -In the admin app (`admin.cubityfir.st`) → **OAuth** tab → **Register client**. -Enter a name, the exact redirect URI(s), scopes, and whether it's trusted / -public. The `client_id` + `client_secret` are shown **once** in a dialog (with -copy buttons and the discovery URL) - store the secret immediately. The same -page lists existing clients and lets you disable/enable, rotate the secret, or -delete them. (Backed by admin-only endpoints on the auth worker, proxied through -the admin worker - `packages/admin/src/routes/oauth.ts` → `auth` `/admin/oauth/clients*`.) - -### Option B - CLI - -```bash -node scripts/register-oauth-client.mjs \ - --name "My Dashboard" \ - --redirect "https://app.example.com/api/auth/callback/annex" -# add more --redirect for additional EXACT callback URLs -# --require-consent -> show a consent screen (default: trusted/auto-approve) -# --public -> SPA/native client (no secret; PKCE only) -``` - -It prints the `client_id` + `client_secret` (**secret shown once**) and writes a -`.sql` file. Apply it: - -```bash -cd packages/auth && npx wrangler d1 execute cubedocs-auth --remote --file -# local dev (with `pnpm dev` running), from the repo root: -node scripts/d1-local.mjs auth --file -``` - -Either way, put `client_id` + `client_secret` (+ the discovery URL) into the -connected service's config and follow [`CONSUMER_PROMPT.md`](./CONSUMER_PROMPT.md). - -- `redirect_uris` are matched **exactly** - register the precise callback URL(s), - including scheme, host, port, and path. No wildcards or trailing-slash slack. -- First-party services you run should stay **trusted** (auto-approve, no consent - screen). Use `--require-consent` only for something you don't fully control. - ---- - -## How the flow works - -``` -Service Browser Annex app (docs) Annex issuer (auth) - │ redirect to authorization_endpoint │ │ - │─────────────────────────────────────▶ /oauth/authorize (SPA) │ - │ │ (logs in via real Annex login │ - │ │ if no session; consent if not │ - │ │ trusted) │ - │ │ POST /api/oauth/authorize ──────▶ mint single-use code - │ 302 redirect_uri?code&state ◀───────│ │ - │ POST code + PKCE verifier (+secret) ───────────────────────────────────▶ /oauth/token - │ ◀───────────────────────── id_token + access_token (RS256) ────────────│ - │ verify id_token via JWKS, optionally GET /oauth/userinfo │ -``` - -PKCE (S256) is **mandatory**. `state` (CSRF) is echoed back. `nonce`, if sent, -is bound into the id_token. Authorization codes are single-use and expire in -5 minutes; consuming one a second time fails. - ---- - -## Operations - -- **Disable a client** (stops new sign-ins; keeps history): - `UPDATE oauth_clients SET disabled = 1 WHERE client_id = '…';` -- **Rotate a client secret:** re-run the register script for a new client, or - `UPDATE oauth_clients SET client_secret_hash = '' …`. -- **Tokens are short (1h)** and stateless - there is no token revocation list. - Disabling a client is refused at authorize, token, **and** userinfo, so its - access tokens stop resolving claims immediately (an id_token already delivered - to the consumer stays offline-verifiable until it expires). Disabling or - suspending a *user* likewise takes effect immediately at token + userinfo - (account standing is re-checked there). -- **Rotate the signing key:** generate a new key with a new `kid`. To avoid - invalidating live tokens, publish both keys in JWKS during the 1-hour overlap - before swapping `OIDC_PRIVATE_KEY` (current code serves a single key; extend - `/oauth/jwks` to an array for a zero-downtime roll). - -## Security model (why it's safe to point other services at it) - -- **Exact** redirect-URI matching - the primary defence against open-redirect / - token theft. No prefix or wildcard matching anywhere. -- **PKCE S256 mandatory** for every client; confidential clients additionally - authenticate with a secret at the token endpoint. -- **Single-use codes**, consumed atomically (`UPDATE … WHERE consumed_at IS NULL`). -- **RS256 with a dedicated key** - `JWT_SECRET` is never exposed; consumers - verify offline via JWKS. The token verifier pins `alg: RS256` (no alg-confusion). -- **Live account checks** - disabled/suspended/force-password-change users can't - obtain or use tokens even mid-session. -- The issuer host exposes **only** `/oauth/*` and `/.well-known/*`; the public - CORS (`*`) is scoped to those read/exchange endpoints, never the app session - routes. +# Sign in with cubityfir.st + +Annex is no longer an OpenID Connect provider. Since 2026-11-18 the identity +provider for every cubityfir.st service, Annex included, is the standalone +`cubityfirst-auth` worker at **https://auth.cubityfir.st**: hosted sign-in, +registration, account and security pages, OIDC endpoints, and client +management at `https://auth.cubityfir.st/admin/clients`. + +- Discovery: `https://auth.cubityfir.st/.well-known/openid-configuration` +- Authorization endpoint: `https://auth.cubityfir.st/oauth/authorize` + (the old `https://docs.cubityfir.st/oauth/authorize` redirects there, query + string included) +- Issuer, `sub` values (= Annex user ids) and existing client ids are + unchanged; the signing key is new, so verify id_tokens against the JWKS + from discovery. + +To connect a service, follow `docs/CONNECTING.md` in the `cubityfirst-auth` +repository. Workers on the `cubityfir.st` zone must reach the provider over a +service binding to `cubityfirst-auth` for every server-side request +(discovery, JWKS, token, userinfo): a Worker's `fetch()` to another Worker's +hostname on the same zone goes to the origin, not to that Worker. diff --git a/memories/Oidc-Provider.md b/memories/Oidc-Provider.md deleted file mode 100644 index d1840e10..00000000 --- a/memories/Oidc-Provider.md +++ /dev/null @@ -1,72 +0,0 @@ -# Sign in with Annex - OIDC provider - -Annex is an OpenID Connect identity provider so other first-party services can -offer "Sign in with Annex". Standard **authorization-code + PKCE**, RS256 -id_tokens verifiable offline via JWKS - consumers use any OIDC client library. -Generalizes the single-purpose admin handoff (`admin_handoffs`, 0009). - -## Hosts / endpoints -- **Issuer** = `https://auth.cubityfir.st` (dedicated identity host, decoupled - from the app origin which may migrate). The auth worker serves - `/oauth/{token,userinfo,jwks}` + `/.well-known/openid-configuration` there - directly via two routes in `packages/auth/cloudflare.config.ts` (`auth.cubityfir.st/oauth/*`, - `/.well-known/*`). Needs a **proxied** DNS record for `auth.cubityfir.st` on - the `cubityfir.st` zone. -- **authorization_endpoint** = `https://docs.cubityfir.st/oauth/authorize` - a - SPA page on the APP origin (the user's Annex session/JWT lives there, not on - the issuer host). It POSTs to `/api/oauth/authorize` (frontend → api → auth - via the `AUTH` binding) with the user's Bearer JWT to mint a single-use code. - -## Key files -- `packages/auth/src/oidc.ts` - pure crypto/helpers: RS256 sign/verify, JWKS - derivation, PKCE (S256), `resolveScopes`, exact `redirectUriAllowed`, claim - builders. Scopes: `openid`/`profile`/`email`/`roles`. `profile` adds `name` + - `picture` (the latter built as `${APP_ORIGIN}/api/avatar/{id}` in the token + - userinfo handlers, not in `scopedClaims`; the avatar endpoint 404s for users - with no avatar). The `roles` scope adds a - `roles` array claim via `rolesForUser` (admins → `["user","admin"]`, else - `["user"]`), sourced live from `users.is_admin` at token+userinfo time - lets - connected services gate admin features on `roles.includes("admin")`. Unit-tested - in `oidc.test.ts` (PKCE RFC vectors, alg-confusion, exact redirect match, - RS256 round-trip, roles). -- `packages/auth/src/routes/oauth-{authorize,token,userinfo,discovery}.ts`. -- `packages/auth/src/routes/oauth-clients.ts` - **admin-only** client CRUD - (`/admin/oauth/clients` GET/POST + `/set-disabled`, `/delete`, `/rotate-secret`). - NOT on the public routes; reached only via the admin worker's `AUTH` binding; - each handler re-checks `session.isAdmin`. Secrets generated/hashed here. -- Admin UI: `packages/admin/src/routes/oauth.ts` (thin proxy under - `/api/oauth-clients`, gated by `enforceAdmin`) + `packages/admin/frontend/src/pages/OAuthClientsPage.tsx` - (the "OAuth" nav tab - register/list/disable/rotate/delete; secret shown once). -- `packages/auth/src/index.ts` - routing + **path-aware CORS** (public OIDC - paths = `*`; everything else locked to the app origin) + `RATE_LIMITER_OIDC`. -- `packages/auth/migrations/0028_add_oauth_clients.sql` - `oauth_clients` - (exact-match `redirect_uris` JSON, hashed secret, `trusted`/`disabled`) + - `oauth_codes` (single-use, PKCE-bound, 5-min). -- `packages/api/src/index.ts` - proxies `/oauth/authorize` only. -- `packages/frontend/src/pages/OAuthAuthorizePage.tsx` (+ App.tsx route). -- `scripts/gen-oidc-key.mjs` (RS256 key → `OIDC_PRIVATE_KEY` secret), - `scripts/register-oauth-client.mjs` (per-service client_id/secret + SQL). -- Docs: `docs/oauth/README.md` (provider/ops), `docs/oauth/CONSUMER_PROMPT.md` - (paste into the connected service's agent). - -## Security invariants -- **Exact** redirect-URI match only (no wildcard/prefix). The `/oauth/authorize` - endpoint NEVER emits a `redirectTo` until the URI is validated; pre-validation - failures (unknown/disabled client, bad redirect) return a plain 400 with no - redirect. -- **PKCE S256 mandatory** for all clients; verified **before** the code is - atomically consumed (so a bad verifier can't burn an unredeemed code). - Confidential clients also auth with a secret (Basic or post). -- Codes consumed atomically (`UPDATE … WHERE consumed_at IS NULL`, assert 1 row). -- **RS256 with a dedicated key** (`OIDC_PRIVATE_KEY`) - `JWT_SECRET` is NEVER - shared. Verifier pins `alg: RS256` (no alg-confusion). -- Live account standing re-checked at token + userinfo; **disabled client** - refused at authorize, token, AND userinfo (so disabling cuts off existing - access tokens, not just new ones). -- Tokens are stateless, 1h, no revocation list - disable the client to cut off. - -## Deploy -New tables aren't read by `loadCurrentSession`, so the auth/api/admin -triple-redeploy rule does NOT apply. But auth + api + frontend all changed: -migrate auth DB → deploy auth → api → frontend. See `docs/oauth/README.md` for -the full one-time setup (key, DNS, migrate, deploy, register client). diff --git a/packages/auth/cloudflare.config.ts b/packages/auth/cloudflare.config.ts index 3ec31acc..c3d2470f 100644 --- a/packages/auth/cloudflare.config.ts +++ b/packages/auth/cloudflare.config.ts @@ -15,21 +15,6 @@ export default defineConfig({ entrypoint: "src/index.ts", workersDev: false, triggers: [ - // "Sign in with Annex" OIDC provider - public endpoints on a DEDICATED - // identity host so the issuer is decoupled from the app origin - // (docs.cubityfir.st), which may migrate. Only /oauth/* and /.well-known/* - // are exposed here; nothing else on the auth worker is reachable at - // auth.cubityfir.st. Requires a proxied DNS record for `auth.cubityfir.st` - // on the cubityfir.st zone (see docs/oauth/README.md). The browser-facing - // authorization page lives on the app origin (OIDC_AUTHORIZE_URL). - triggers.fetch({ - pattern: "auth.cubityfir.st/oauth/*", - zone: "cubityfir.st", - }), - triggers.fetch({ - pattern: "auth.cubityfir.st/.well-known/*", - zone: "cubityfir.st", - }), // Weekly sweep of long-dead session rows (see scheduled handler). triggers.scheduled({ schedule: "0 3 * * SUN", @@ -39,13 +24,6 @@ export default defineConfig({ JWT_ISSUER: bindings.text("https://auth.cubedocs.com"), ADMIN_APP_ORIGIN: bindings.text("https://admin.cubityfir.st"), APP_ORIGIN: bindings.text("https://docs.cubityfir.st"), - // "Sign in with Annex" OIDC provider. OIDC_ISSUER is the `iss` of every - // token and the base for discovery - // (https://auth.cubityfir.st/.well-known/openid-configuration). - // OIDC_AUTHORIZE_URL is the browser-facing authorize page on the app - // origin (the user's Annex session lives there, not on the issuer host). - OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), - OIDC_AUTHORIZE_URL: bindings.text("https://docs.cubityfir.st/oauth/authorize"), WEBAUTHN_RP_ID: bindings.text("docs.cubityfir.st"), WEBAUTHN_RP_NAME: bindings.text("Annex"), WEBAUTHN_ORIGIN: bindings.text("https://docs.cubityfir.st"), @@ -105,18 +83,6 @@ export default defineConfig({ period: 60, }, }), - // OIDC token endpoint (/oauth/token). Server-to-server, so a single - // connected service exchanges every user's code from one egress IP - - // needs a far higher ceiling than the interactive login limiter. - // IP-keyed (CF-Connecting-IP is real on the directly-routed - // auth.cubityfir.st host). - RATE_LIMITER_OIDC: bindings.rateLimit({ - namespace: "1004", - simple: { - limit: 100, - period: 60, - }, - }), // Secrets (set via `npx wrangler secret put --name annex-auth`; // existing secrets are kept across `cf deploy`): // JWT_SECRET @@ -124,10 +90,6 @@ export default defineConfig({ // STRIPE_SECRET_KEY (sk_test_... or sk_live_...) // STRIPE_WEBHOOK_SECRET (whsec_... - generated by Stripe when you // register the /stripe/webhook endpoint) - // OIDC_PRIVATE_KEY (RS256 signing key - RSA private JWK as a JSON - // string. Generate with - // `node scripts/gen-oidc-key.mjs`. The public - // half is published at /oauth/jwks.) }, }, }); diff --git a/packages/auth/src/cleanup.sqlite.test.ts b/packages/auth/src/cleanup.sqlite.test.ts index 3f6a0d0f..a9c5a8dc 100644 --- a/packages/auth/src/cleanup.sqlite.test.ts +++ b/packages/auth/src/cleanup.sqlite.test.ts @@ -16,7 +16,6 @@ import { sweepExpiredRows, SWEEP_RETENTION_MS } from "./cleanup"; import { createSession, SESSION_TTL_MS } from "./sessions"; import { handleLookupById } from "./routes/lookup-by-id"; import { handleAdminHandoffStart } from "./routes/admin-handoff-start"; -import { handleOAuthAuthorize } from "./routes/oauth-authorize"; import { requireAuthenticatedSession } from "./auth-session"; import type { Env } from "./index"; @@ -27,7 +26,6 @@ function setup() { const { db, sqlite } = createSqliteD1(AUTH_MIGRATIONS); const env = { DB: db, - RATE_LIMITER_OIDC: { limit: async () => ({ success: true }) }, } as unknown as Env; const addUser = (id: string) => sqlite.prepare( @@ -209,35 +207,4 @@ describe("handoff / authorization-code GC", () => { expect(left).not.toContain("h-expired"); expect(left).not.toContain("h-expired-consumed"); }); - - it("oauth-authorize drops expired codes and keeps unexpired (incl. consumed) ones", async () => { - const { env, sqlite, addUser, ids } = setup(); - addUser("u1"); - const now = Date.now(); - sqlite.prepare( - "INSERT INTO oauth_clients (client_id, client_name, redirect_uris, allowed_scopes, trusted, disabled, created_at) VALUES ('c1', 'App', ?, 'openid profile email', 1, 0, ?)", - ).run(JSON.stringify(["https://app.example/cb"]), now); - const add = sqlite.prepare( - `INSERT INTO oauth_codes (code, client_id, user_id, redirect_uri, scope, code_challenge, created_at, expires_at, consumed_at) - VALUES (?, 'c1', 'u1', 'https://app.example/cb', 'openid', 'x', ?, ?, ?)`, - ); - add.run("code-expired", now - 10 * 60 * 1000, now - 5 * 60 * 1000, null); - add.run("code-consumed-live", now - 60 * 1000, now + 4 * 60 * 1000, now - 30 * 1000); - - const res = await handleOAuthAuthorize( - new Request("http://auth/oauth/authorize", { - method: "POST", - body: JSON.stringify({ - client_id: "c1", redirect_uri: "https://app.example/cb", response_type: "code", - scope: "openid", code_challenge: "abc", code_challenge_method: "S256", - }), - }), - env, - ); - expect(res.status).toBe(200); - const left = ids("SELECT code AS id FROM oauth_codes"); - expect(left).toHaveLength(2); - expect(left).toContain("code-consumed-live"); - expect(left).not.toContain("code-expired"); - }); }); diff --git a/packages/auth/src/index.test.ts b/packages/auth/src/index.test.ts deleted file mode 100644 index 8aee9dcf..00000000 --- a/packages/auth/src/index.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import worker, { type Env } from "./index"; - -describe("auth worker routing", () => { - it("rate-limits OIDC userinfo by direct client IP using OAuth response semantics", async () => { - const limit = vi.fn().mockResolvedValue({ success: false }); - const env = { RATE_LIMITER_OIDC: { limit } } as unknown as Env; - const request = new Request("https://auth.cubityfir.st/oauth/userinfo", { - headers: { "CF-Connecting-IP": "203.0.113.8" }, - }); - - const response = await worker.fetch(request, env, {} as ExecutionContext); - - expect(response.status).toBe(429); - expect(response.headers.get("Cache-Control")).toBe("no-store"); - expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); - expect(limit).toHaveBeenCalledWith({ key: "oidc-userinfo:203.0.113.8" }); - expect(await response.json()).toEqual({ - error: "temporarily_unavailable", - error_description: "rate limit exceeded", - }); - }); -}); diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 37432853..2c240d3f 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -31,17 +31,6 @@ import { handleWebauthnCredentialsDelete } from "./routes/webauthn-credentials-d import { handleTotpBackupCodesGenerate } from "./routes/totp-backup-codes-generate"; import { handleAdminHandoffStart } from "./routes/admin-handoff-start"; import { handleAdminHandoffExchange } from "./routes/admin-handoff-exchange"; -import { handleOAuthAuthorize } from "./routes/oauth-authorize"; -import { handleOAuthToken } from "./routes/oauth-token"; -import { handleOAuthUserinfo } from "./routes/oauth-userinfo"; -import { handleOAuthDiscovery, handleOAuthJwks } from "./routes/oauth-discovery"; -import { - handleOAuthClientCreate, - handleOAuthClientDelete, - handleOAuthClientRotateSecret, - handleOAuthClientSetDisabled, - handleOAuthClientsList, -} from "./routes/oauth-clients"; import { handleVerifyEmail } from "./routes/verify-email"; import { handleVerifyEmailResend } from "./routes/verify-email-resend"; import { handleDeleteAccount } from "./routes/delete-account"; @@ -60,13 +49,6 @@ export interface Env { JWT_ISSUER: string; ADMIN_APP_ORIGIN: string; APP_ORIGIN: string; - // "Sign in with Annex" OIDC provider. OIDC_ISSUER is the dedicated identity - // origin (https://auth.cubityfir.st); OIDC_AUTHORIZE_URL is the app-origin - // authorization page; OIDC_PRIVATE_KEY is the RS256 signing key (RSA private - // JWK as a JSON string, set via `wrangler secret put OIDC_PRIVATE_KEY`). - OIDC_ISSUER: string; - OIDC_AUTHORIZE_URL: string; - OIDC_PRIVATE_KEY: string; TURNSTILE_SECRET: string; WEBAUTHN_RP_ID: string; WEBAUTHN_RP_NAME: string; @@ -90,7 +72,6 @@ export interface Env { RATE_LIMITER_LOOKUP: { limit(opts: { key: string }): Promise<{ success: boolean }> }; RATE_LIMITER_AUTH: { limit(opts: { key: string }): Promise<{ success: boolean }> }; RATE_LIMITER_EMAIL_VERIFY: { limit(opts: { key: string }): Promise<{ success: boolean }> }; - RATE_LIMITER_OIDC: { limit(opts: { key: string }): Promise<{ success: boolean }> }; STRIPE_SECRET_KEY: string; STRIPE_WEBHOOK_SECRET: string; DEV_QUICK_LOGIN?: string; @@ -105,10 +86,10 @@ export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(request.url); - // Public OIDC endpoints are cross-origin by nature (called by connected - // services from their own origins), so they advertise `*`. Every other - // route stays locked to the app origin. - const corsOrigin = isPublicOidcPath(url.pathname) ? "*" : "https://docs.cubityfir.st"; + // Every route is reached from the app origin (over the api/frontend + // service bindings). The OpenID provider that used to live here moved to + // the cubityfirst-auth worker at https://auth.cubityfir.st. + const corsOrigin = "https://docs.cubityfir.st"; // CORS preflight if (request.method === "OPTIONS") { @@ -192,59 +173,6 @@ export default { response = await handleAdminHandoffStart(request, env); } else if (url.pathname === "/admin/handoff/exchange" && request.method === "POST") { response = await handleAdminHandoffExchange(request, env); - } else if (url.pathname === "/oauth/authorize" && request.method === "POST") { - // Browser-facing authorize step, reached via the app's /api proxy with - // the signed-in user's Bearer token. Mints a single-use code. - response = await handleOAuthAuthorize(request, env); - } else if (url.pathname === "/oauth/token" && request.method === "POST") { - // Public token endpoint (server-to-server). Dedicated, higher-ceiling - // IP cap on its own binding: a confidential client's backend exchanges - // every user's code from a single egress IP, so the login-grade 10/min - // limiter would throttle legitimate logins. Rejections use the OAuth - // error shape (RFC 6749), not the internal {ok,error} envelope. - const { success } = await env.RATE_LIMITER_OIDC.limit({ key: `oidc-token:${ip}` }); - if (!success) { - return addCorsHeaders( - Response.json( - { error: "temporarily_unavailable", error_description: "rate limit exceeded" }, - { status: 429, headers: { "Cache-Control": "no-store" } }, - ), - corsOrigin, - ); - } - response = await handleOAuthToken(request, env); - } else if (url.pathname === "/oauth/userinfo" && (request.method === "GET" || request.method === "POST")) { - // Public endpoint: every call runs an RS256 verify (+ DB reads for a - // valid token), so cap it per-IP like /oauth/token. IP is real here — - // userinfo is directly routed on auth.cubityfir.st, not proxied. - const { success } = await env.RATE_LIMITER_OIDC.limit({ key: `oidc-userinfo:${ip}` }); - if (!success) { - return addCorsHeaders( - Response.json( - { error: "temporarily_unavailable", error_description: "rate limit exceeded" }, - { status: 429, headers: { "Cache-Control": "no-store" } }, - ), - corsOrigin, - ); - } - response = await handleOAuthUserinfo(request, env); - } else if (url.pathname === "/oauth/jwks" && request.method === "GET") { - response = handleOAuthJwks(request, env); - } else if (url.pathname === "/.well-known/openid-configuration" && request.method === "GET") { - response = handleOAuthDiscovery(request, env); - } else if (url.pathname === "/admin/oauth/clients" && request.method === "GET") { - // Admin-only OIDC client management. Reached via the admin worker's - // AUTH service binding (NOT a public route); each handler re-checks - // the admin session. - response = await handleOAuthClientsList(request, env); - } else if (url.pathname === "/admin/oauth/clients" && request.method === "POST") { - response = await handleOAuthClientCreate(request, env); - } else if (url.pathname === "/admin/oauth/clients/set-disabled" && request.method === "POST") { - response = await handleOAuthClientSetDisabled(request, env); - } else if (url.pathname === "/admin/oauth/clients/delete" && request.method === "POST") { - response = await handleOAuthClientDelete(request, env); - } else if (url.pathname === "/admin/oauth/clients/rotate-secret" && request.method === "POST") { - response = await handleOAuthClientRotateSecret(request, env); } else if (url.pathname === "/webauthn/register/start" && request.method === "POST") { response = await handleWebauthnRegisterStart(request, env); } else if (url.pathname === "/webauthn/register/finish" && request.method === "POST") { @@ -313,18 +241,6 @@ export default { }, }; -// Public OIDC endpoints served to connected services from their own origins. -// `/oauth/authorize` is intentionally NOT here - it's reached internally via -// the API worker's service binding and stays locked to the app origin. -function isPublicOidcPath(pathname: string): boolean { - return ( - pathname === "/oauth/token" || - pathname === "/oauth/userinfo" || - pathname === "/oauth/jwks" || - pathname === "/.well-known/openid-configuration" - ); -} - function corsHeaders(origin: string): HeadersInit { return { "Access-Control-Allow-Origin": origin, diff --git a/packages/auth/src/oidc.test.ts b/packages/auth/src/oidc.test.ts deleted file mode 100644 index 869accac..00000000 --- a/packages/auth/src/oidc.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { - b64urlToBytes, - bytesToB64url, - buildDiscoveryDocument, - buildIdTokenClaims, - constantTimeEqual, - rolesForUser, - deriveS256Challenge, - derivePublicJwk, - hashClientSecret, - parseRedirectUris, - redirectUriAllowed, - resolveScopes, - scopedClaims, - signRs256, - verifyClientSecret, - verifyPkceS256, - verifyRs256, - type OidcUser, - type PrivateJwk, -} from "./oidc"; - -async function generatePrivateJwk(): Promise { - const kp = await crypto.subtle.generateKey( - { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, - true, - ["sign", "verify"], - ); - const jwk = (await crypto.subtle.exportKey("jwk", kp.privateKey)) as PrivateJwk; - jwk.kid = "test-key"; - jwk.alg = "RS256"; - jwk.use = "sig"; - return jwk; -} - -describe("base64url", () => { - it("round-trips arbitrary bytes", () => { - const bytes = new Uint8Array([0, 1, 2, 250, 251, 255, 64, 63, 62]); - expect([...b64urlToBytes(bytesToB64url(bytes))]).toEqual([...bytes]); - }); - it("produces url-safe output with no padding", () => { - const s = bytesToB64url(new Uint8Array([255, 255, 255])); - expect(s).not.toMatch(/[+/=]/); - }); -}); - -describe("PKCE (S256)", () => { - // RFC 7636 Appendix B reference vector. - const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; - const challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; - - it("derives the spec challenge from the spec verifier", async () => { - expect(await deriveS256Challenge(verifier)).toBe(challenge); - }); - it("verifies a correct verifier", async () => { - expect(await verifyPkceS256(verifier, challenge)).toBe(true); - }); - it("rejects a wrong verifier", async () => { - expect(await verifyPkceS256("not-the-verifier", challenge)).toBe(false); - }); - it("rejects empty inputs", async () => { - expect(await verifyPkceS256("", challenge)).toBe(false); - expect(await verifyPkceS256(verifier, "")).toBe(false); - }); -}); - -describe("resolveScopes", () => { - const allowed = "openid profile email"; - it("intersects requested with allowed", () => { - expect(resolveScopes("openid email", allowed)).toBe("openid email"); - }); - it("drops scopes the client may not request", () => { - expect(resolveScopes("openid email", "openid")).toBe("openid"); - }); - it("drops unknown scopes", () => { - expect(resolveScopes("openid admin profile", allowed)).toBe("openid profile"); - }); - it("requires openid", () => { - expect(resolveScopes("profile email", allowed)).toBeNull(); - expect(resolveScopes("", allowed)).toBeNull(); - expect(resolveScopes(null, allowed)).toBeNull(); - }); - it("grants roles only when the client allows it", () => { - expect(resolveScopes("openid roles", "openid profile email roles")).toBe("openid roles"); - // client not allowed `roles` -> it's dropped - expect(resolveScopes("openid roles", "openid profile email")).toBe("openid"); - }); -}); - -describe("roles", () => { - const admin: OidcUser = { id: "u1", email: "a@b.com", emailVerified: true, name: "Ada", isAdmin: true }; - const plain: OidcUser = { id: "u2", email: "c@d.com", emailVerified: true, name: "Cy", isAdmin: false }; - - it("gives admins the admin role, others just user", () => { - expect(rolesForUser(admin)).toEqual(["user", "admin"]); - expect(rolesForUser(plain)).toEqual(["user"]); - }); - - it("only emits the roles claim when the scope is granted", () => { - expect(scopedClaims(admin, new Set(["openid"]))).not.toHaveProperty("roles"); - expect(scopedClaims(admin, new Set(["openid", "roles"]))).toMatchObject({ roles: ["user", "admin"] }); - expect(scopedClaims(plain, new Set(["openid", "roles"]))).toMatchObject({ roles: ["user"] }); - }); -}); - -describe("redirect URIs", () => { - it("parses a JSON array and ignores junk", () => { - expect(parseRedirectUris('["https://a/cb","https://b/cb"]')).toEqual(["https://a/cb", "https://b/cb"]); - expect(parseRedirectUris("not json")).toEqual([]); - expect(parseRedirectUris('{"a":1}')).toEqual([]); - }); - it("matches only on an exact string", () => { - const reg = ["https://app.example.com/cb"]; - expect(redirectUriAllowed("https://app.example.com/cb", reg)).toBe(true); - expect(redirectUriAllowed("https://app.example.com/cb/", reg)).toBe(false); - expect(redirectUriAllowed("https://app.example.com/cb?x=1", reg)).toBe(false); - expect(redirectUriAllowed("https://evil.example.com/cb", reg)).toBe(false); - expect(redirectUriAllowed("https://app.example.com.evil.com/cb", reg)).toBe(false); - }); -}); - -describe("client secrets", () => { - it("verifies the right secret and rejects the wrong one", async () => { - const hash = await hashClientSecret("s3cr3t-value"); - expect(await verifyClientSecret("s3cr3t-value", hash)).toBe(true); - expect(await verifyClientSecret("wrong", hash)).toBe(false); - }); - it("constantTimeEqual compares correctly", () => { - expect(constantTimeEqual("abc", "abc")).toBe(true); - expect(constantTimeEqual("abc", "abd")).toBe(false); - expect(constantTimeEqual("abc", "abcd")).toBe(false); - }); -}); - -describe("JWKS derivation", () => { - it("strips private fields from the public JWK", async () => { - const priv = await generatePrivateJwk(); - const pub = derivePublicJwk(priv); - expect(pub).toEqual({ kty: priv.kty, n: priv.n, e: priv.e, alg: "RS256", use: "sig", kid: "test-key" }); - expect(pub).not.toHaveProperty("d"); - expect(pub).not.toHaveProperty("p"); - expect(pub).not.toHaveProperty("q"); - }); -}); - -describe("RS256 sign/verify", () => { - it("round-trips a payload", async () => { - const priv = await generatePrivateJwk(); - const token = await signRs256({ sub: "u1", exp: Math.floor(Date.now() / 1000) + 60 }, priv); - const payload = await verifyRs256(token, priv); - expect(payload?.sub).toBe("u1"); - }); - it("rejects a tampered signature", async () => { - const priv = await generatePrivateJwk(); - const token = await signRs256({ sub: "u1" }, priv); - const tampered = `${token.slice(0, -3)}aaa`; - expect(await verifyRs256(tampered, priv)).toBeNull(); - }); - it("rejects a token with no exp (fail closed)", async () => { - const priv = await generatePrivateJwk(); - const token = await signRs256({ sub: "u1" }, priv); - expect(await verifyRs256(token, priv)).toBeNull(); - }); - it("rejects an expired token", async () => { - const priv = await generatePrivateJwk(); - const token = await signRs256({ sub: "u1", exp: Math.floor(Date.now() / 1000) - 5 }, priv); - expect(await verifyRs256(token, priv)).toBeNull(); - }); - it("rejects alg-confusion (none / HS256 headers)", async () => { - const priv = await generatePrivateJwk(); - const valid = await signRs256({ sub: "u1" }, priv); - const [, body, sig] = valid.split("."); - const noneHeader = bytesToB64url(new TextEncoder().encode(JSON.stringify({ alg: "none", typ: "JWT" }))); - const hsHeader = bytesToB64url(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" }))); - expect(await verifyRs256(`${noneHeader}.${body}.`, priv)).toBeNull(); - expect(await verifyRs256(`${hsHeader}.${body}.${sig}`, priv)).toBeNull(); - }); -}); - -describe("claims", () => { - const user: OidcUser = { id: "u1", email: "a@b.com", emailVerified: true, name: "Ada", isAdmin: false }; - - it("scopes claims by grant", () => { - expect(scopedClaims(user, new Set(["openid"]))).toEqual({ sub: "u1" }); - expect(scopedClaims(user, new Set(["openid", "email"]))).toEqual({ - sub: "u1", - email: "a@b.com", - email_verified: true, - }); - expect(scopedClaims(user, new Set(["openid", "profile"]))).toEqual({ sub: "u1", name: "Ada" }); - }); - - it("emits picture under the profile scope when the user has one", () => { - const withPic: OidcUser = { ...user, picture: "https://app.example/api/avatar/u1" }; - // picture rides the profile scope alongside name... - expect(scopedClaims(withPic, new Set(["openid", "profile"]))).toEqual({ - sub: "u1", - name: "Ada", - picture: "https://app.example/api/avatar/u1", - }); - // ...not openid alone, and is omitted entirely when unset. - expect(scopedClaims(withPic, new Set(["openid"]))).toEqual({ sub: "u1" }); - expect(scopedClaims(user, new Set(["openid", "profile"]))).not.toHaveProperty("picture"); - }); - - it("builds id_token claims with iss/aud/exp and optional nonce", () => { - const claims = buildIdTokenClaims({ - issuer: "https://auth.cubityfir.st", - clientId: "annx_abc", - user, - scopes: new Set(["openid", "email"]), - nonce: "n-123", - nowSec: 1000, - ttlSec: 3600, - }); - expect(claims).toMatchObject({ - iss: "https://auth.cubityfir.st", - aud: "annx_abc", - sub: "u1", - email: "a@b.com", - email_verified: true, - nonce: "n-123", - iat: 1000, - auth_time: 1000, - exp: 4600, - }); - }); - - it("omits nonce when not supplied", () => { - const claims = buildIdTokenClaims({ - issuer: "i", - clientId: "c", - user, - scopes: new Set(["openid"]), - nowSec: 0, - ttlSec: 1, - }); - expect(claims).not.toHaveProperty("nonce"); - }); -}); - -describe("discovery document", () => { - it("points each endpoint at the right host", () => { - const doc = buildDiscoveryDocument("https://auth.cubityfir.st", "https://docs.cubityfir.st/oauth/authorize"); - expect(doc).toMatchObject({ - issuer: "https://auth.cubityfir.st", - authorization_endpoint: "https://docs.cubityfir.st/oauth/authorize", - token_endpoint: "https://auth.cubityfir.st/oauth/token", - userinfo_endpoint: "https://auth.cubityfir.st/oauth/userinfo", - jwks_uri: "https://auth.cubityfir.st/oauth/jwks", - code_challenge_methods_supported: ["S256"], - id_token_signing_alg_values_supported: ["RS256"], - claims_supported: expect.arrayContaining(["picture"]), - }); - }); -}); diff --git a/packages/auth/src/oidc.ts b/packages/auth/src/oidc.ts deleted file mode 100644 index 32b3edd5..00000000 --- a/packages/auth/src/oidc.ts +++ /dev/null @@ -1,329 +0,0 @@ -// OIDC provider primitives for "Sign in with Annex". -// -// This module is deliberately framework-free and mostly pure so the -// security-critical bits (PKCE, scope resolution, exact redirect matching, -// RS256 signing/verification, JWKS derivation) are unit-testable in isolation. -// -// Signing uses RS256 (asymmetric) - NOT the HS256 `JWT_SECRET` used for -// first-party Annex sessions - so connected services can verify id_tokens -// offline against the published JWKS without ever holding an Annex secret. - -import { toArrayBuffer } from "./crypto"; - -const RS = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const; - -// --------------------------------------------------------------------------- -// base64url + JSON (UTF-8 safe; payloads carry names/emails that may be unicode) -// --------------------------------------------------------------------------- - -export function bytesToB64url(bytes: Uint8Array): string { - let bin = ""; - for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - -export function b64urlToBytes(input: string): Uint8Array { - let s = input.replace(/-/g, "+").replace(/_/g, "/"); - const pad = s.length % 4; - if (pad) s += "=".repeat(4 - pad); - const bin = atob(s); - const out = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); - return out; -} - -function encodeJson(obj: unknown): string { - return bytesToB64url(new TextEncoder().encode(JSON.stringify(obj))); -} - -function decodeJsonPart>(part: string): T { - return JSON.parse(new TextDecoder().decode(b64urlToBytes(part))) as T; -} - -// --------------------------------------------------------------------------- -// Hashing / constant-time compare -// --------------------------------------------------------------------------- - -async function sha256Bytes(input: string): Promise { - const digest = await crypto.subtle.digest("SHA-256", toArrayBuffer(new TextEncoder().encode(input))); - return new Uint8Array(digest); -} - -export async function sha256b64url(input: string): Promise { - return bytesToB64url(await sha256Bytes(input)); -} - -// Length-independent only when both inputs are the same length; we compare -// fixed-length digests so this is a constant-time equality for our use. -export function constantTimeEqual(a: string, b: string): boolean { - if (a.length !== b.length) return false; - let diff = 0; - for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); - return diff === 0; -} - -// Client secrets are high-entropy random strings, so a single SHA-256 is -// sufficient (unlike user passwords, which need a slow KDF). Mirrors how the -// registration script computes the stored hash. -export async function hashClientSecret(secret: string): Promise { - return sha256b64url(secret); -} - -export async function verifyClientSecret(secret: string, storedHash: string): Promise { - return constantTimeEqual(await sha256b64url(secret), storedHash); -} - -// --------------------------------------------------------------------------- -// PKCE (S256 only) -// --------------------------------------------------------------------------- - -export async function deriveS256Challenge(verifier: string): Promise { - return sha256b64url(verifier); -} - -export async function verifyPkceS256(verifier: string, challenge: string): Promise { - if (!verifier || !challenge) return false; - return constantTimeEqual(await deriveS256Challenge(verifier), challenge); -} - -// --------------------------------------------------------------------------- -// Scopes / redirect URIs -// --------------------------------------------------------------------------- - -// Intersect requested scopes with what the client is allowed, dropping unknowns. -// Returns null if the result wouldn't include `openid` (which OIDC requires). -export function resolveScopes(requested: string | null | undefined, allowed: string): string | null { - const allow = new Set(allowed.split(/\s+/).filter(Boolean)); - const granted = new Set((requested ?? "").split(/\s+/).filter(Boolean).filter((s) => allow.has(s))); - if (!granted.has("openid")) return null; - return [...granted].join(" "); -} - -export function parseRedirectUris(json: string): string[] { - try { - const arr: unknown = JSON.parse(json); - return Array.isArray(arr) ? arr.filter((x): x is string => typeof x === "string") : []; - } catch { - return []; - } -} - -// Exact string match - no prefix/wildcard matching, which is the single most -// important defence against open-redirect / token-theft in an OAuth provider. -export function redirectUriAllowed(redirectUri: string, registered: string[]): boolean { - return registered.includes(redirectUri); -} - -// --------------------------------------------------------------------------- -// RS256 sign / verify + JWKS -// --------------------------------------------------------------------------- - -export interface PrivateJwk { - kty: string; - n: string; - e: string; - d: string; - kid: string; - alg?: string; - use?: string; - [k: string]: unknown; -} - -export interface PublicJwk { - kty: string; - n: string; - e: string; - alg: "RS256"; - use: "sig"; - kid: string; -} - -export function parsePrivateJwk(secret: string): PrivateJwk { - const jwk = JSON.parse(secret) as PrivateJwk; - if (jwk.kty !== "RSA" || !jwk.n || !jwk.e || !jwk.d || !jwk.kid) { - throw new Error("OIDC_PRIVATE_KEY is not a complete RSA private JWK (need kty/n/e/d/kid)"); - } - return jwk; -} - -// The public half is just the private JWK with the private fields stripped - -// an RSA private JWK already carries the public modulus (n) and exponent (e). -export function derivePublicJwk(privateJwk: PrivateJwk): PublicJwk { - return { kty: privateJwk.kty, n: privateJwk.n, e: privateJwk.e, alg: "RS256", use: "sig", kid: privateJwk.kid }; -} - -async function importPrivate(jwk: PrivateJwk): Promise { - return crypto.subtle.importKey("jwk", jwk as JsonWebKey, RS, false, ["sign"]); -} - -async function importPublic(jwk: PublicJwk): Promise { - return crypto.subtle.importKey("jwk", jwk as JsonWebKey, RS, false, ["verify"]); -} - -export async function signRs256(payload: Record, privateJwk: PrivateJwk): Promise { - const header = { alg: "RS256", typ: "JWT", kid: privateJwk.kid }; - const signingInput = `${encodeJson(header)}.${encodeJson(payload)}`; - const key = await importPrivate(privateJwk); - const sig = await crypto.subtle.sign(RS, key, toArrayBuffer(new TextEncoder().encode(signingInput))); - return `${signingInput}.${bytesToB64url(new Uint8Array(sig))}`; -} - -// Verifies an RS256 JWT signed by THIS provider (alg pinned to RS256 - never -// trust the token's alg to pick the verifier; that's the classic alg-confusion -// hole). Returns the payload, or null if signature/format/exp is bad. -export async function verifyRs256(token: string, privateJwk: PrivateJwk): Promise | null> { - const parts = token.split("."); - if (parts.length !== 3) return null; - - let header: { alg?: unknown; typ?: unknown }; - try { - header = decodeJsonPart(parts[0]); - } catch { - return null; - } - if (header.alg !== "RS256" || header.typ !== "JWT") return null; - - const key = await importPublic(derivePublicJwk(privateJwk)); - let ok: boolean; - try { - ok = await crypto.subtle.verify( - RS, - key, - toArrayBuffer(b64urlToBytes(parts[2])), - toArrayBuffer(new TextEncoder().encode(`${parts[0]}.${parts[1]}`)), - ); - } catch { - return null; - } - if (!ok) return null; - - let payload: Record; - try { - payload = decodeJsonPart(parts[1]); - } catch { - return null; - } - // Fail closed: every token we mint carries exp, so one without it is not ours. - if (typeof payload.exp !== "number" || payload.exp * 1000 <= Date.now()) return null; - return payload; -} - -// --------------------------------------------------------------------------- -// Claims -// --------------------------------------------------------------------------- - -export interface OidcUser { - id: string; - email: string; - emailVerified: boolean; - name: string; - // Annex platform-admin flag (users.is_admin). Surfaced as the "admin" role - // when the `roles` scope is granted, so connected services can gate admin-only - // features. Read live at token/userinfo time, so revoking admin takes effect. - isAdmin: boolean; - // Public URL of the user's avatar (`${APP_ORIGIN}/api/avatar/{id}`), set by the - // token/userinfo handlers and emitted as the `picture` claim under the `profile` - // scope. The avatar endpoint 404s for users who never uploaded one, so relying - // parties should fall back to their own placeholder. Optional so unit tests and - // any non-request caller can omit it. - picture?: string; -} - -// The roles a user carries. Everyone is a "user"; Annex platform-admins also -// get "admin". Kept as an array so more roles can be added without a breaking -// claim-shape change. -export function rolesForUser(user: OidcUser): string[] { - return user.isAdmin ? ["user", "admin"] : ["user"]; -} - -// Standard OIDC claims, filtered by the granted scope set. `openid` always -// yields `sub`; `email` adds email/email_verified; `profile` adds name + -// picture (when the caller supplied one); `roles` adds the roles array. -export function scopedClaims(user: OidcUser, scopes: Set): Record { - const claims: Record = { sub: user.id }; - if (scopes.has("email")) { - claims.email = user.email; - claims.email_verified = user.emailVerified; - } - if (scopes.has("profile")) { - claims.name = user.name; - if (user.picture) claims.picture = user.picture; - } - if (scopes.has("roles")) { - claims.roles = rolesForUser(user); - } - return claims; -} - -export function buildIdTokenClaims(opts: { - issuer: string; - clientId: string; - user: OidcUser; - scopes: Set; - nonce?: string | null; - nowSec: number; - ttlSec: number; -}): Record { - const claims: Record = { - iss: opts.issuer, - aud: opts.clientId, - iat: opts.nowSec, - auth_time: opts.nowSec, - exp: opts.nowSec + opts.ttlSec, - ...scopedClaims(opts.user, opts.scopes), - }; - if (opts.nonce) claims.nonce = opts.nonce; - return claims; -} - -export function buildAccessTokenClaims(opts: { - issuer: string; - clientId: string; - sub: string; - scope: string; - nowSec: number; - ttlSec: number; -}): Record { - return { - iss: opts.issuer, - aud: opts.clientId, - sub: opts.sub, - scope: opts.scope, - token_use: "access", - iat: opts.nowSec, - exp: opts.nowSec + opts.ttlSec, - }; -} - -// --------------------------------------------------------------------------- -// Discovery -// --------------------------------------------------------------------------- - -// `issuer` is the dedicated identity origin (e.g. https://auth.cubityfir.st). -// `authorizeUrl` is the browser-facing authorization endpoint, which lives on -// the APP origin (docs.cubityfir.st) because that's where the user's Annex -// session exists - OIDC permits endpoints on different hosts. -export function buildDiscoveryDocument(issuer: string, authorizeUrl: string): Record { - return { - issuer, - authorization_endpoint: authorizeUrl, - token_endpoint: `${issuer}/oauth/token`, - userinfo_endpoint: `${issuer}/oauth/userinfo`, - jwks_uri: `${issuer}/oauth/jwks`, - response_types_supported: ["code"], - grant_types_supported: ["authorization_code"], - subject_types_supported: ["public"], - id_token_signing_alg_values_supported: ["RS256"], - scopes_supported: ["openid", "profile", "email", "roles"], - token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"], - code_challenge_methods_supported: ["S256"], - claims_supported: ["sub", "iss", "aud", "exp", "iat", "auth_time", "nonce", "email", "email_verified", "name", "picture", "roles"], - }; -} - -// ID + access tokens both live 1h. The Annex session that authorized them is -// independent and longer-lived; revoking the Annex session does not retro-kill -// already-issued OIDC tokens (they're short by design). -export const OIDC_TOKEN_TTL_SEC = 60 * 60; -// Authorization codes are single-use and short - matches admin_handoffs. -export const OIDC_CODE_TTL_MS = 5 * 60 * 1000; diff --git a/packages/auth/src/routes/oauth-authorize.test.ts b/packages/auth/src/routes/oauth-authorize.test.ts deleted file mode 100644 index 6df2795c..00000000 --- a/packages/auth/src/routes/oauth-authorize.test.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleOAuthAuthorize } from "./oauth-authorize"; - -vi.mock("../auth-session", () => ({ requireAuthenticatedSession: vi.fn() })); -vi.mock("../oidc", () => ({ - OIDC_CODE_TTL_MS: 60_000, - parseRedirectUris: vi.fn((s: string) => s.split(",")), - redirectUriAllowed: vi.fn(() => true), - resolveScopes: vi.fn(() => "openid profile"), -})); - -import { requireAuthenticatedSession } from "../auth-session"; -import { redirectUriAllowed, resolveScopes } from "../oidc"; - -const mockSession = { userId: "user-1", email: "user@example.com", expiresAt: Date.now() + 3600_000 }; - -const trustedClient = { - client_id: "client-1", client_name: "App", redirect_uris: "https://app/cb", - allowed_scopes: "openid profile", trusted: 1, disabled: 0, -}; - -function makeEnv(client: typeof trustedClient | null, rateLimitSuccess = true) { - const first = vi.fn().mockResolvedValue(client); - const run = vi.fn().mockResolvedValue({ meta: { changes: 1 } }); - const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - const batch = vi.fn(async (stmts: unknown[]) => stmts.map(() => ({ results: [], meta: { changes: 1 } }))); - const limit = vi.fn().mockResolvedValue({ success: rateLimitSuccess }); - return { env: { DB: { prepare, batch }, RATE_LIMITER_OIDC: { limit } } as unknown as Parameters[1], prepare, bind, run, first, batch, limit }; -} - -const base = { - client_id: "client-1", redirect_uri: "https://app/cb", response_type: "code", - scope: "openid profile", state: "xyz", code_challenge: "abc", code_challenge_method: "S256", -}; - -function req(body: Record) { - return new Request("http://localhost/oauth/authorize", { - method: "POST", - headers: { Authorization: "Bearer t", "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(requireAuthenticatedSession).mockResolvedValue(mockSession); - vi.mocked(redirectUriAllowed).mockReturnValue(true); - vi.mocked(resolveScopes).mockReturnValue("openid profile"); -}); - -describe("handleOAuthAuthorize", () => { - it("returns 401 when the session is invalid", async () => { - vi.mocked(requireAuthenticatedSession).mockResolvedValue( - Response.json({ ok: false, error: "Unauthorized" }, { status: 401 }), - ); - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req(base), env); - expect(res.status).toBe(401); - }); - - it("returns 429 before reading or writing OAuth state when the user limit is exceeded", async () => { - const { env, prepare, limit } = makeEnv(trustedClient, false); - const res = await handleOAuthAuthorize(req(base), env); - expect(res.status).toBe(429); - expect(limit).toHaveBeenCalledWith({ key: "oidc-authorize:user-1" }); - expect(prepare).not.toHaveBeenCalled(); - }); - - it("rejects a body missing client_id / redirect_uri", async () => { - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req({ client_id: "client-1" }), env); - expect(res.status).toBe(400); - }); - - it("400s (never redirects) for an unknown/disabled client", async () => { - const { env } = makeEnv(null); - const res = await handleOAuthAuthorize(req(base), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("invalid_client"); - }); - - it("400s (never redirects) for a redirect_uri off the allowlist", async () => { - vi.mocked(redirectUriAllowed).mockReturnValue(false); - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req(base), env); - expect(res.status).toBe(400); - const json = (await res.json()) as { error: string }; - expect(json.error).toBe("invalid_redirect_uri"); - }); - - it("redirects with access_denied when the user denies", async () => { - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req({ ...base, denied: true }), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { redirectTo: string } }; - expect(json.data.redirectTo).toContain("error=access_denied"); - expect(json.data.redirectTo).toContain("state=xyz"); - }); - - it("redirects with unsupported_response_type for non-code flows", async () => { - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req({ ...base, response_type: "token" }), env); - const json = (await res.json()) as { data: { redirectTo: string } }; - expect(json.data.redirectTo).toContain("error=unsupported_response_type"); - }); - - it("redirects with invalid_scope when scope resolution fails", async () => { - vi.mocked(resolveScopes).mockReturnValue(null as never); - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req(base), env); - const json = (await res.json()) as { data: { redirectTo: string } }; - expect(json.data.redirectTo).toContain("error=invalid_scope"); - }); - - it("redirects with invalid_request when PKCE is missing / not S256", async () => { - const { env } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req({ ...base, code_challenge_method: "plain" }), env); - const json = (await res.json()) as { data: { redirectTo: string } }; - expect(json.data.redirectTo).toContain("error=invalid_request"); - }); - - it("returns consentRequired for an untrusted client without approval", async () => { - const { env, run } = makeEnv({ ...trustedClient, trusted: 0 }); - const res = await handleOAuthAuthorize(req(base), env); - const json = (await res.json()) as { data: { consentRequired: boolean; scope: string; email: string } }; - expect(json.data.consentRequired).toBe(true); - expect(json.data.email).toBe("user@example.com"); - // no code minted yet - expect(run).not.toHaveBeenCalled(); - }); - - it("mints a code and returns redirectTo for a trusted client", async () => { - const { env, run, batch, prepare } = makeEnv(trustedClient); - const res = await handleOAuthAuthorize(req(base), env); - expect(res.status).toBe(200); - const json = (await res.json()) as { data: { redirectTo: string } }; - expect(json.data.redirectTo).toContain("code="); - expect(json.data.redirectTo).toContain("state=xyz"); - // GC delete + code INSERT in one batch round trip. - expect(run).not.toHaveBeenCalled(); - expect(batch).toHaveBeenCalledTimes(1); - expect(batch.mock.calls[0][0]).toHaveLength(2); - // Index-backed GC: expiry only (consumed codes are inert until they expire). - expect(prepare).toHaveBeenCalledWith("DELETE FROM oauth_codes WHERE expires_at <= ?"); - expect(prepare.mock.calls.some(([sql]) => String(sql).includes("INSERT INTO oauth_codes"))).toBe(true); - }); -}); diff --git a/packages/auth/src/routes/oauth-authorize.ts b/packages/auth/src/routes/oauth-authorize.ts deleted file mode 100644 index 9b8182e4..00000000 --- a/packages/auth/src/routes/oauth-authorize.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { errorResponse, Errors, okResponse, rateLimitUser } from "../lib"; -import { OIDC_CODE_TTL_MS, parseRedirectUris, redirectUriAllowed, resolveScopes } from "../oidc"; -import type { Env } from "../index"; - -interface ClientRow { - client_id: string; - client_name: string; - redirect_uris: string; - allowed_scopes: string; - trusted: number; - disabled: number; -} - -interface AuthorizeBody { - client_id?: string; - redirect_uri?: string; - response_type?: string; - scope?: string; - state?: string; - nonce?: string; - code_challenge?: string; - code_challenge_method?: string; - // SPA consent controls (the authorize page re-POSTs with one of these set): - approved?: boolean; - denied?: boolean; -} - -// Build a `redirect_uri?...&state=...` URL. Only ever called AFTER redirect_uri -// has been validated against the client's exact allowlist. -function buildRedirect(redirectUri: string, params: Record): string { - const url = new URL(redirectUri); - for (const [k, v] of Object.entries(params)) { - if (v !== undefined && v !== "") url.searchParams.set(k, v); - } - return url.toString(); -} - -// POST /oauth/authorize (proxied to the app origin as /api/oauth/authorize) -// -// The browser-facing authorization step. Called by the Annex app's -// /oauth/authorize page with the signed-in user's Bearer token plus the OIDC -// request params. Validates the client + redirect, optionally surfaces a -// consent gate, then mints a single-use authorization code and returns the -// `redirectTo` the page should send the browser to. -// -// Errors are split deliberately: -// - Pre-validation failures (unknown/disabled client, redirect not on the -// allowlist) return a plain 400 - we must NEVER redirect to an unvalidated -// URI, or we become an open redirector / token-leak vector. -// - Post-validation failures (bad scope, missing PKCE, denial) come back as a -// `redirectTo` carrying `error=...&state=...`, per the OAuth spec. -export async function handleOAuthAuthorize(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - - // This is the only code-minting path and each approved call writes to - // oauth_codes. The public /oauth/token side is IP-capped; throttle the - // issuing side per-user too (proxy strips IP, so key on the session userId). - const limited = await rateLimitUser(env.RATE_LIMITER_OIDC, `oidc-authorize:${session.userId}`); - if (limited) return limited; - - const body = await request.json().catch(() => ({} as AuthorizeBody)); - - if (!body.client_id || !body.redirect_uri) return errorResponse(Errors.BAD_REQUEST); - - const client = await env.DB.prepare( - "SELECT client_id, client_name, redirect_uris, allowed_scopes, trusted, disabled FROM oauth_clients WHERE client_id = ?", - ).bind(body.client_id).first(); - - // Pre-validation: never redirect on these. - if (!client || client.disabled) { - return Response.json({ ok: false, error: "invalid_client" }, { status: 400 }); - } - const registered = parseRedirectUris(client.redirect_uris); - if (!redirectUriAllowed(body.redirect_uri, registered)) { - return Response.json({ ok: false, error: "invalid_redirect_uri" }, { status: 400 }); - } - - const redirectUri = body.redirect_uri; - const state = body.state; - - // Post-validation failures redirect back to the (now trusted) redirect_uri. - if (body.denied) { - return okResponse({ redirectTo: buildRedirect(redirectUri, { error: "access_denied", state }) }); - } - if (body.response_type !== "code") { - return okResponse({ redirectTo: buildRedirect(redirectUri, { error: "unsupported_response_type", state }) }); - } - const scope = resolveScopes(body.scope, client.allowed_scopes); - if (!scope) { - return okResponse({ redirectTo: buildRedirect(redirectUri, { error: "invalid_scope", state }) }); - } - // PKCE is mandatory and S256-only. - if (!body.code_challenge || body.code_challenge_method !== "S256") { - return okResponse({ redirectTo: buildRedirect(redirectUri, { error: "invalid_request", state }) }); - } - - // Consent gate. First-party (`trusted`) clients auto-approve; others must - // come back with `approved: true` after the page shows the consent screen. - if (!client.trusted && !body.approved) { - return okResponse({ - consentRequired: true, - client: { name: client.client_name }, - scope, - email: session.email, - }); - } - - const now = Date.now(); - const code = crypto.randomUUID(); - - // Opportunistic GC of expired codes (mirrors admin-handoff-start), batched - // with the INSERT. Consumed codes are left to expire (<= OIDC_CODE_TTL_MS): - // the token endpoint only accepts `consumed_at IS NULL`, so they're inert, - // and an `OR consumed_at IS NOT NULL` arm would force a full table scan. - await env.DB.batch([ - env.DB.prepare("DELETE FROM oauth_codes WHERE expires_at <= ?").bind(now), - env.DB.prepare( - `INSERT INTO oauth_codes (code, client_id, user_id, redirect_uri, scope, code_challenge, nonce, created_at, expires_at, consumed_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)`, - ).bind( - code, - client.client_id, - session.userId, - redirectUri, - scope, - body.code_challenge, - body.nonce ?? null, - now, - now + OIDC_CODE_TTL_MS, - ), - ]); - - return okResponse({ redirectTo: buildRedirect(redirectUri, { code, state }) }); -} diff --git a/packages/auth/src/routes/oauth-clients.ts b/packages/auth/src/routes/oauth-clients.ts deleted file mode 100644 index ecdb1a3b..00000000 --- a/packages/auth/src/routes/oauth-clients.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { requireAuthenticatedSession } from "../auth-session"; -import { errorResponse, Errors, okResponse, type Session } from "../lib"; -import { bytesToB64url, hashClientSecret, parseRedirectUris } from "../oidc"; -import type { Env } from "../index"; - -// Admin-only management of "Sign in with Annex" OIDC clients. These endpoints -// live on the auth worker (which owns auth-DB writes) and are reached only via -// the admin worker's AUTH service binding - they are NOT on the public -// auth.cubityfir.st routes (only /oauth/* and /.well-known/* are). Every -// handler still re-checks the admin session as defence in depth. - -interface ClientRow { - client_id: string; - client_name: string; - client_secret_hash: string | null; - redirect_uris: string; - allowed_scopes: string; - trusted: number; - disabled: number; - created_at: number; -} - -interface CreateBody { - name?: string; - redirect_uris?: string[]; - scopes?: string; - trusted?: boolean; - public?: boolean; -} - -interface ClientIdBody { - client_id?: string; -} - -interface SetDisabledBody { - client_id?: string; - disabled?: boolean; -} - -const ALLOWED_SCOPES = ["openid", "profile", "email", "roles"]; - -async function requireAdmin(request: Request, env: Env): Promise { - const session = await requireAuthenticatedSession(request, env); - if (session instanceof Response) return session; - if (!session.isAdmin) return errorResponse(Errors.FORBIDDEN); - return session; -} - -function isValidRedirect(uri: string): boolean { - try { - const u = new URL(uri); - // https everywhere; localhost is allowed for development callbacks. - return u.protocol === "https:" || u.hostname === "localhost" || u.hostname === "127.0.0.1"; - } catch { - return false; - } -} - -// Restrict to the known scopes and guarantee `openid`. Empty/missing => the -// full default set. Returns null for an unknown scope (caller rejects). -function normalizeScopes(input: string | undefined): string | null { - if (input === undefined || input.trim() === "") return "openid profile email"; - const set = new Set(input.split(/\s+/).filter(Boolean)); - for (const s of set) if (!ALLOWED_SCOPES.includes(s)) return null; - if (!set.has("openid")) return null; - return ALLOWED_SCOPES.filter((s) => set.has(s)).join(" "); -} - -function randomHex(bytes: number): string { - const arr = crypto.getRandomValues(new Uint8Array(bytes)); - return [...arr].map((b) => b.toString(16).padStart(2, "0")).join(""); -} - -function generateSecret(): string { - return bytesToB64url(crypto.getRandomValues(new Uint8Array(32))); -} - -// Never expose the secret hash. Secrets are returned exactly once, at creation -// or rotation, and never stored in plaintext. -function publicView(row: ClientRow) { - return { - client_id: row.client_id, - client_name: row.client_name, - is_public: row.client_secret_hash === null, - redirect_uris: parseRedirectUris(row.redirect_uris), - allowed_scopes: row.allowed_scopes, - trusted: Boolean(row.trusted), - disabled: Boolean(row.disabled), - created_at: row.created_at, - }; -} - -// GET /admin/oauth/clients -export async function handleOAuthClientsList(request: Request, env: Env): Promise { - const session = await requireAdmin(request, env); - if (session instanceof Response) return session; - - const rows = await env.DB.prepare( - `SELECT client_id, client_name, client_secret_hash, redirect_uris, allowed_scopes, trusted, disabled, created_at - FROM oauth_clients ORDER BY created_at DESC`, - ).all(); - - return okResponse({ clients: rows.results.map(publicView) }); -} - -// POST /admin/oauth/clients { name, redirect_uris[], scopes?, trusted?, public? } -export async function handleOAuthClientCreate(request: Request, env: Env): Promise { - const session = await requireAdmin(request, env); - if (session instanceof Response) return session; - - const body = await request.json().catch(() => ({} as CreateBody)); - - const name = (body.name ?? "").trim(); - const redirects = Array.isArray(body.redirect_uris) - ? [...new Set(body.redirect_uris.map((s) => s.trim()).filter(Boolean))] - : []; - - if (!name || redirects.length === 0) return errorResponse(Errors.BAD_REQUEST); - if (!redirects.every(isValidRedirect)) { - return Response.json({ ok: false, error: "invalid_redirect_uri" }, { status: 400 }); - } - - const scopes = normalizeScopes(body.scopes); - if (!scopes) return Response.json({ ok: false, error: "invalid_scope" }, { status: 400 }); - - const isPublic = body.public === true; - const trusted = body.trusted === false ? 0 : 1; - const clientId = `annx_${randomHex(12)}`; - - let secret: string | null = null; - let secretHash: string | null = null; - if (!isPublic) { - secret = generateSecret(); - secretHash = await hashClientSecret(secret); - } - - await env.DB.prepare( - `INSERT INTO oauth_clients (client_id, client_name, client_secret_hash, redirect_uris, allowed_scopes, trusted, disabled, created_at) - VALUES (?, ?, ?, ?, ?, ?, 0, ?)`, - ).bind(clientId, name, secretHash, JSON.stringify(redirects), scopes, trusted, Date.now()).run(); - - // `client_secret` is returned ONCE here and never again. - return okResponse({ - client_id: clientId, - client_secret: secret, - client_name: name, - is_public: isPublic, - redirect_uris: redirects, - allowed_scopes: scopes, - trusted: Boolean(trusted), - disabled: false, - }); -} - -// POST /admin/oauth/clients/set-disabled { client_id, disabled } -export async function handleOAuthClientSetDisabled(request: Request, env: Env): Promise { - const session = await requireAdmin(request, env); - if (session instanceof Response) return session; - - const body = await request.json().catch(() => ({} as SetDisabledBody)); - if (!body.client_id || typeof body.disabled !== "boolean") return errorResponse(Errors.BAD_REQUEST); - - const result = await env.DB.prepare( - "UPDATE oauth_clients SET disabled = ? WHERE client_id = ?", - ).bind(body.disabled ? 1 : 0, body.client_id).run(); - - if ((result.meta.changes ?? 0) === 0) return errorResponse(Errors.NOT_FOUND); - return okResponse({ client_id: body.client_id, disabled: body.disabled }); -} - -// POST /admin/oauth/clients/delete { client_id } -export async function handleOAuthClientDelete(request: Request, env: Env): Promise { - const session = await requireAdmin(request, env); - if (session instanceof Response) return session; - - const body = await request.json().catch(() => ({} as ClientIdBody)); - if (!body.client_id) return errorResponse(Errors.BAD_REQUEST); - - // ON DELETE CASCADE drops any outstanding oauth_codes for this client. - const result = await env.DB.prepare( - "DELETE FROM oauth_clients WHERE client_id = ?", - ).bind(body.client_id).run(); - - if ((result.meta.changes ?? 0) === 0) return errorResponse(Errors.NOT_FOUND); - return okResponse({ client_id: body.client_id, deleted: true }); -} - -// POST /admin/oauth/clients/rotate-secret { client_id } -export async function handleOAuthClientRotateSecret(request: Request, env: Env): Promise { - const session = await requireAdmin(request, env); - if (session instanceof Response) return session; - - const body = await request.json().catch(() => ({} as ClientIdBody)); - if (!body.client_id) return errorResponse(Errors.BAD_REQUEST); - - const existing = await env.DB.prepare( - "SELECT client_secret_hash FROM oauth_clients WHERE client_id = ?", - ).bind(body.client_id).first<{ client_secret_hash: string | null }>(); - if (!existing) return errorResponse(Errors.NOT_FOUND); - if (existing.client_secret_hash === null) { - // Public clients have no secret to rotate. - return Response.json({ ok: false, error: "public_client_no_secret" }, { status: 400 }); - } - - const secret = generateSecret(); - await env.DB.prepare( - "UPDATE oauth_clients SET client_secret_hash = ? WHERE client_id = ?", - ).bind(await hashClientSecret(secret), body.client_id).run(); - - return okResponse({ client_id: body.client_id, client_secret: secret }); -} diff --git a/packages/auth/src/routes/oauth-discovery.test.ts b/packages/auth/src/routes/oauth-discovery.test.ts deleted file mode 100644 index a5f4e836..00000000 --- a/packages/auth/src/routes/oauth-discovery.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { handleOAuthDiscovery, handleOAuthJwks } from "./oauth-discovery"; - -// A structurally complete RSA private JWK (values are opaque to these handlers - -// nothing here signs or verifies), so the real ../oidc helpers run end to end. -const PRIVATE_JWK = { kty: "RSA", n: "modulus", e: "AQAB", d: "priv-d", p: "priv-p", q: "priv-q", dp: "priv-dp", dq: "priv-dq", qi: "priv-qi", kid: "k1" }; - -const env = { - OIDC_ISSUER: "https://auth.example.com", - OIDC_AUTHORIZE_URL: "https://app.example.com/oauth/authorize", - OIDC_PRIVATE_KEY: JSON.stringify(PRIVATE_JWK), -} as unknown as Parameters[1]; - -describe("handleOAuthDiscovery", () => { - it("serves the discovery doc with a cache header", async () => { - const res = handleOAuthDiscovery(new Request("http://localhost/.well-known/openid-configuration"), env); - expect(res.headers.get("Cache-Control")).toContain("max-age=3600"); - const json = (await res.json()) as Record; - expect(json.issuer).toBe("https://auth.example.com"); - expect(json.authorization_endpoint).toBe("https://app.example.com/oauth/authorize"); - expect(json.jwks_uri).toBe("https://auth.example.com/oauth/jwks"); - }); -}); - -describe("handleOAuthJwks", () => { - it("publishes only the public JWK (private fields stripped)", async () => { - const res = handleOAuthJwks(new Request("http://localhost/oauth/jwks"), env); - expect(res.headers.get("Cache-Control")).toContain("max-age=3600"); - const json = (await res.json()) as { keys: Array> }; - expect(json.keys).toEqual([{ kty: "RSA", n: "modulus", e: "AQAB", alg: "RS256", use: "sig", kid: "k1" }]); - }); -}); diff --git a/packages/auth/src/routes/oauth-discovery.ts b/packages/auth/src/routes/oauth-discovery.ts deleted file mode 100644 index 955d01fa..00000000 --- a/packages/auth/src/routes/oauth-discovery.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { buildDiscoveryDocument, derivePublicJwk, parsePrivateJwk } from "../oidc"; -import type { Env } from "../index"; - -// GET /.well-known/openid-configuration (public, on the issuer origin) -// -// The OIDC discovery document. Standard clients read this from -// `${issuer}/.well-known/openid-configuration` and self-configure every -// endpoint from it. Safe to cache - it only changes on a config/key roll. -export function handleOAuthDiscovery(_request: Request, env: Env): Response { - const doc = buildDiscoveryDocument(env.OIDC_ISSUER, env.OIDC_AUTHORIZE_URL); - return Response.json(doc, { - headers: { "Cache-Control": "public, max-age=3600" }, - }); -} - -// GET /oauth/jwks (public, on the issuer origin) -// -// Publishes the RSA public key(s) so clients can verify id_tokens offline. -// Derived from the private signing JWK with the private fields stripped. -export function handleOAuthJwks(_request: Request, env: Env): Response { - const publicJwk = derivePublicJwk(parsePrivateJwk(env.OIDC_PRIVATE_KEY)); - return Response.json( - { keys: [publicJwk] }, - { headers: { "Cache-Control": "public, max-age=3600" } }, - ); -} diff --git a/packages/auth/src/routes/oauth-token.test.ts b/packages/auth/src/routes/oauth-token.test.ts deleted file mode 100644 index 96e597bf..00000000 --- a/packages/auth/src/routes/oauth-token.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleOAuthToken } from "./oauth-token"; - -vi.mock("../oidc", () => ({ - OIDC_TOKEN_TTL_SEC: 3600, - parsePrivateJwk: vi.fn(() => ({ kty: "RSA" })), - signRs256: vi.fn(async (claims: { token_use?: string }) => (claims.token_use === "access" ? "access.jwt" : "id.jwt")), - verifyClientSecret: vi.fn(async () => true), - verifyPkceS256: vi.fn(async () => true), - buildIdTokenClaims: vi.fn(() => ({ token_use: "id" })), - buildAccessTokenClaims: vi.fn(() => ({ token_use: "access" })), -})); -vi.mock("./login", () => ({ checkModeration: vi.fn(() => false) })); - -import { verifyClientSecret, verifyPkceS256 } from "../oidc"; -import { checkModeration } from "./login"; - -const publicClient = { client_id: "client-1", client_secret_hash: null, disabled: 0 }; -const confidentialClient = { client_id: "client-1", client_secret_hash: "hash", disabled: 0 }; -const codeRow = { - code: "code-1", client_id: "client-1", user_id: "user-1", - redirect_uri: "https://app/cb", scope: "openid profile", code_challenge: "chal", nonce: null, -}; -const userRow = { - id: "user-1", email: "u@example.com", name: "U", - email_verified: 1, is_admin: 0, moderation: 0, force_password_change: 0, -}; - -// first() returns each queued value in order: client, codeRow, user. -function makeEnv(opts: { - client?: typeof publicClient | typeof confidentialClient | null; - code?: typeof codeRow | null; - user?: typeof userRow | null; - consumeChanges?: number; -}) { - const first = vi.fn() - .mockResolvedValueOnce(opts.client === undefined ? publicClient : opts.client) - .mockResolvedValueOnce(opts.code === undefined ? codeRow : opts.code) - .mockResolvedValueOnce(opts.user === undefined ? userRow : opts.user); - const run = vi.fn().mockResolvedValue({ meta: { changes: opts.consumeChanges ?? 1 } }); - const bind = vi.fn().mockReturnValue({ first, run }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { - DB: { prepare }, - OIDC_PRIVATE_KEY: "{}", - OIDC_ISSUER: "https://auth.example.com", - APP_ORIGIN: "https://app.example.com", - } as unknown as Parameters[1], - prepare, - run, - }; -} - -function req(params: Record, headers: Record = {}) { - return new Request("http://localhost/oauth/token", { - method: "POST", - headers: { "Content-Type": "application/json", ...headers }, - body: JSON.stringify(params), - }); -} - -const goodParams = { - grant_type: "authorization_code", client_id: "client-1", code: "code-1", - code_verifier: "verifier", redirect_uri: "https://app/cb", -}; - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyClientSecret).mockResolvedValue(true); - vi.mocked(verifyPkceS256).mockResolvedValue(true); - vi.mocked(checkModeration).mockReturnValue(false); -}); - -describe("handleOAuthToken", () => { - it("rejects an unsupported grant_type", async () => { - const { env } = makeEnv({}); - const res = await handleOAuthToken(req({ grant_type: "password" }), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("unsupported_grant_type"); - }); - - it("rejects a missing client_id", async () => { - const { env } = makeEnv({}); - const res = await handleOAuthToken(req({ grant_type: "authorization_code" }), env); - expect(res.status).toBe(401); - expect((await res.json() as { error: string }).error).toBe("invalid_client"); - }); - - it("rejects an unknown/disabled client", async () => { - const { env } = makeEnv({ client: null }); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(401); - expect((await res.json() as { error: string }).error).toBe("invalid_client"); - }); - - it("rejects a known but disabled client at the token endpoint", async () => { - // A client row that exists but has disabled=1 must be refused - this pins - // the `|| client.disabled` term in the guard (the null-client case above - // alone wouldn't catch dropping it). - const { env } = makeEnv({ client: { ...publicClient, disabled: 1 } }); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(401); - expect((await res.json() as { error: string }).error).toBe("invalid_client"); - }); - - it("rejects a confidential client with a bad secret", async () => { - vi.mocked(verifyClientSecret).mockResolvedValue(false); - const { env } = makeEnv({ client: confidentialClient }); - const res = await handleOAuthToken(req({ ...goodParams, client_secret: "wrong" }), env); - expect(res.status).toBe(401); - expect((await res.json() as { error: string }).error).toBe("invalid_client"); - }); - - it("rejects a request missing code/verifier/redirect_uri", async () => { - const { env } = makeEnv({ client: publicClient }); - const res = await handleOAuthToken(req({ grant_type: "authorization_code", client_id: "client-1" }), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("invalid_request"); - }); - - it("rejects when the code row is missing/expired/consumed", async () => { - const { env } = makeEnv({ code: null }); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("invalid_grant"); - }); - - it("rejects a bad PKCE verifier before consuming the code", async () => { - vi.mocked(verifyPkceS256).mockResolvedValue(false); - const { env, run } = makeEnv({}); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("invalid_grant"); - // PKCE is verified BEFORE the single-use code is consumed: a bad verifier - // must never burn a still-unredeemed code (the only run() is the consume). - expect(run).not.toHaveBeenCalled(); - }); - - it("rejects when the atomic consume changes 0 rows (replay)", async () => { - const { env } = makeEnv({ consumeChanges: 0 }); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("invalid_grant"); - }); - - it("rejects when the subject is suspended at token time", async () => { - vi.mocked(checkModeration).mockReturnValue(true); - const { env } = makeEnv({}); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(400); - expect((await res.json() as { error: string }).error).toBe("invalid_grant"); - }); - - it("mints id_token + access_token on success (no-store)", async () => { - const { env } = makeEnv({}); - const res = await handleOAuthToken(req(goodParams), env); - expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("no-store"); - const json = (await res.json()) as { access_token: string; id_token: string; token_type: string; scope: string }; - expect(json.access_token).toBe("access.jwt"); - expect(json.id_token).toBe("id.jwt"); - expect(json.token_type).toBe("Bearer"); - expect(json.scope).toBe("openid profile"); - }); -}); diff --git a/packages/auth/src/routes/oauth-token.ts b/packages/auth/src/routes/oauth-token.ts deleted file mode 100644 index d4916aa5..00000000 --- a/packages/auth/src/routes/oauth-token.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { - buildAccessTokenClaims, - buildIdTokenClaims, - OIDC_TOKEN_TTL_SEC, - parsePrivateJwk, - signRs256, - verifyClientSecret, - verifyPkceS256, - type OidcUser, -} from "../oidc"; -import { checkModeration } from "./login"; -import type { Env } from "../index"; - -interface ClientRow { - client_id: string; - client_secret_hash: string | null; - disabled: number; -} - -interface CodeRow { - code: string; - client_id: string; - user_id: string; - redirect_uri: string; - scope: string; - code_challenge: string; - nonce: string | null; -} - -interface UserRow { - id: string; - email: string; - name: string; - email_verified: number; - is_admin: number; - moderation: number; - force_password_change: number; -} - -// Standard OAuth token-endpoint responses are RAW JSON (no `{ok,data}` -// envelope) and must not be cached. -function tokenJson(body: Record, status = 200): Response { - return Response.json(body, { - status, - headers: { "Cache-Control": "no-store", Pragma: "no-cache" }, - }); -} - -function tokenError(error: string, status: number, description?: string): Response { - return tokenJson(description ? { error, error_description: description } : { error }, status); -} - -// Pull client credentials from either HTTP Basic auth or the POST body -// (client_secret_post). Returns the body params too. -async function parseTokenRequest(request: Request): Promise<{ - params: Record; - basicId?: string; - basicSecret?: string; -}> { - const params: Record = {}; - const contentType = request.headers.get("Content-Type") ?? ""; - if (contentType.includes("application/json")) { - const json = await request.json>().catch(() => ({})); - for (const [k, v] of Object.entries(json)) if (typeof v === "string") params[k] = v; - } else { - const form = await request.formData().catch(() => null); - if (form) for (const [k, v] of form.entries()) if (typeof v === "string") params[k] = v; - } - - let basicId: string | undefined; - let basicSecret: string | undefined; - const auth = request.headers.get("Authorization"); - if (auth?.startsWith("Basic ")) { - try { - const decoded = atob(auth.slice(6)); - const idx = decoded.indexOf(":"); - if (idx >= 0) { - const dec = (s: string) => { - try { - return decodeURIComponent(s); - } catch { - return s; - } - }; - basicId = dec(decoded.slice(0, idx)); - basicSecret = dec(decoded.slice(idx + 1)); - } - } catch { - /* malformed Basic header - ignored, falls through to invalid_client */ - } - } - return { params, basicId, basicSecret }; -} - -// POST /oauth/token (public, on the issuer origin - server-to-server) -// -// Exchanges a single-use authorization code for an id_token + access_token. -// Authenticates the client (secret for confidential clients; PKCE for all), -// atomically consumes the code (replay-proof), and re-checks live account -// standing before minting tokens. -export async function handleOAuthToken(request: Request, env: Env): Promise { - const { params, basicId, basicSecret } = await parseTokenRequest(request); - - if (params.grant_type !== "authorization_code") { - return tokenError("unsupported_grant_type", 400); - } - - const clientId = basicId ?? params.client_id; - const clientSecret = basicSecret ?? params.client_secret; - if (!clientId) return tokenError("invalid_client", 401); - - const client = await env.DB.prepare( - "SELECT client_id, client_secret_hash, disabled FROM oauth_clients WHERE client_id = ?", - ).bind(clientId).first(); - if (!client || client.disabled) return tokenError("invalid_client", 401); - - // Confidential clients (those with a stored secret) MUST authenticate. - // Public clients (no secret) rely on PKCE alone. - if (client.client_secret_hash) { - if (!clientSecret || !(await verifyClientSecret(clientSecret, client.client_secret_hash))) { - return tokenError("invalid_client", 401); - } - } - - const code = params.code; - const codeVerifier = params.code_verifier; - const redirectUri = params.redirect_uri; - if (!code || !codeVerifier || !redirectUri) return tokenError("invalid_request", 400); - - const codeRow = await env.DB.prepare( - `SELECT code, client_id, user_id, redirect_uri, scope, code_challenge, nonce - FROM oauth_codes - WHERE code = ? AND client_id = ? AND redirect_uri = ? AND consumed_at IS NULL AND expires_at > ?`, - ).bind(code, clientId, redirectUri, Date.now()).first(); - if (!codeRow) return tokenError("invalid_grant", 400); - - // PKCE proof-of-possession is verified BEFORE the code is consumed. A request - // with a bad verifier must not be able to burn a still-unredeemed code - for a - // public (PKCE-only) client the code is observable in the redirect URL, so a - // consume-then-verify order would let an observer DoS that client's logins. - if (!(await verifyPkceS256(codeVerifier, codeRow.code_challenge))) { - return tokenError("invalid_grant", 400); - } - - // Atomically consume - exactly one caller can win, so a replayed code (or a - // concurrent double-submit with the correct verifier) fails here with 0 rows. - const consume = await env.DB.prepare( - "UPDATE oauth_codes SET consumed_at = ? WHERE code = ? AND consumed_at IS NULL", - ).bind(Date.now(), codeRow.code).run(); - if ((consume.meta.changes ?? 0) !== 1) return tokenError("invalid_grant", 400); - - const user = await env.DB.prepare( - "SELECT id, email, name, email_verified, is_admin, moderation, force_password_change FROM users WHERE id = ?", - ).bind(codeRow.user_id).first(); - if (!user || user.force_password_change) return tokenError("invalid_grant", 400); - // Re-check live account standing (disabled/suspended) at token time. - if (checkModeration(user.moderation)) return tokenError("invalid_grant", 400); - - const privateJwk = parsePrivateJwk(env.OIDC_PRIVATE_KEY); - const issuer = env.OIDC_ISSUER; - const nowSec = Math.floor(Date.now() / 1000); - const scopes = new Set(codeRow.scope.split(/\s+/).filter(Boolean)); - const oidcUser: OidcUser = { - id: user.id, - email: user.email, - emailVerified: Boolean(user.email_verified), - name: user.name, - isAdmin: Boolean(user.is_admin), - picture: `${env.APP_ORIGIN}/api/avatar/${user.id}`, - }; - - const idToken = await signRs256( - buildIdTokenClaims({ - issuer, - clientId, - user: oidcUser, - scopes, - nonce: codeRow.nonce, - nowSec, - ttlSec: OIDC_TOKEN_TTL_SEC, - }), - privateJwk, - ); - - const accessToken = await signRs256( - buildAccessTokenClaims({ - issuer, - clientId, - sub: user.id, - scope: codeRow.scope, - nowSec, - ttlSec: OIDC_TOKEN_TTL_SEC, - }), - privateJwk, - ); - - return tokenJson({ - access_token: accessToken, - token_type: "Bearer", - expires_in: OIDC_TOKEN_TTL_SEC, - id_token: idToken, - scope: codeRow.scope, - }); -} diff --git a/packages/auth/src/routes/oauth-userinfo.test.ts b/packages/auth/src/routes/oauth-userinfo.test.ts deleted file mode 100644 index 7c736f85..00000000 --- a/packages/auth/src/routes/oauth-userinfo.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleOAuthUserinfo } from "./oauth-userinfo"; - -vi.mock("../oidc", () => ({ - parsePrivateJwk: vi.fn(() => ({ kty: "RSA" })), - verifyRs256: vi.fn(), - scopedClaims: vi.fn(() => ({ sub: "user-1", email: "u@example.com" })), -})); -vi.mock("./login", () => ({ checkModeration: vi.fn(() => false) })); - -import { verifyRs256, scopedClaims } from "../oidc"; -import { checkModeration } from "./login"; - -const validPayload = { token_use: "access", iss: "https://auth.example.com", sub: "user-1", aud: "client-1", scope: "openid profile" }; -const userRow = { id: "user-1", email: "u@example.com", name: "U", email_verified: 1, is_admin: 0, moderation: 0, force_password_change: 0 }; - -function makeEnv(opts: { client?: { disabled: number } | null; user?: typeof userRow | null }) { - const first = vi.fn() - .mockResolvedValueOnce(opts.client === undefined ? { disabled: 0 } : opts.client) - .mockResolvedValueOnce(opts.user === undefined ? userRow : opts.user); - const bind = vi.fn().mockReturnValue({ first }); - const prepare = vi.fn().mockReturnValue({ bind }); - return { - env: { - DB: { prepare }, - OIDC_PRIVATE_KEY: "{}", - OIDC_ISSUER: "https://auth.example.com", - APP_ORIGIN: "https://app.example.com", - } as unknown as Parameters[1], - }; -} - -function req(bearer?: string) { - return new Request("http://localhost/oauth/userinfo", { - headers: bearer ? { Authorization: `Bearer ${bearer}` } : {}, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(verifyRs256).mockResolvedValue(validPayload as never); - vi.mocked(checkModeration).mockReturnValue(false); -}); - -describe("handleOAuthUserinfo", () => { - it("401s without a bearer token", async () => { - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req(), env); - expect(res.status).toBe(401); - expect(res.headers.get("WWW-Authenticate")).toContain("Bearer"); - }); - - it("401s on an invalid/expired token", async () => { - vi.mocked(verifyRs256).mockResolvedValue(null as never); - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req("bad"), env); - expect(res.status).toBe(401); - }); - - it("401s when the token isn't an access token", async () => { - vi.mocked(verifyRs256).mockResolvedValue({ ...validPayload, token_use: "id" } as never); - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(401); - }); - - it("401s on an issuer mismatch", async () => { - vi.mocked(verifyRs256).mockResolvedValue({ ...validPayload, iss: "https://evil" } as never); - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(401); - }); - - it("401s when the client has been disabled since issuance", async () => { - const { env } = makeEnv({ client: { disabled: 1 } }); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(401); - }); - - it("401s when the subject is suspended", async () => { - vi.mocked(checkModeration).mockReturnValue(true); - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(401); - }); - - it("returns scoped claims live from the DB on success", async () => { - const { env } = makeEnv({}); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("no-store"); - const json = (await res.json()) as { sub: string; email: string }; - expect(json.sub).toBe("user-1"); - expect(json.email).toBe("u@example.com"); - - // scopedClaims must be fed the oidcUser derived from the live DB row (not a - // constant) and the Set parsed from the token's scope. userRow.email_verified - // is 1 -> emailVerified true; picture is built from APP_ORIGIN + user.id. - expect(vi.mocked(scopedClaims)).toHaveBeenCalledWith( - { - id: "user-1", - email: "u@example.com", - emailVerified: true, - name: "U", - isAdmin: false, - picture: "https://app.example.com/api/avatar/user-1", - }, - new Set(["openid", "profile"]), - ); - }); - - it("derives the oidcUser from a distinct DB row (not a constant)", async () => { - const otherRow = { - id: "user-2", email: "other@example.com", name: "Other", - email_verified: 0, is_admin: 1, moderation: 0, force_password_change: 0, - }; - // Token sub/aud still match user-1/client-1 (verifyRs256 mock), but the DB - // returns a different row; scopedClaims must receive THAT row's values. - const { env } = makeEnv({ user: otherRow }); - const res = await handleOAuthUserinfo(req("t"), env); - expect(res.status).toBe(200); - expect(vi.mocked(scopedClaims)).toHaveBeenCalledWith( - { - id: "user-2", - email: "other@example.com", - emailVerified: false, - name: "Other", - isAdmin: true, - picture: "https://app.example.com/api/avatar/user-2", - }, - new Set(["openid", "profile"]), - ); - }); -}); diff --git a/packages/auth/src/routes/oauth-userinfo.ts b/packages/auth/src/routes/oauth-userinfo.ts deleted file mode 100644 index 71e11e6d..00000000 --- a/packages/auth/src/routes/oauth-userinfo.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { parsePrivateJwk, scopedClaims, verifyRs256, type OidcUser } from "../oidc"; -import { checkModeration } from "./login"; -import type { Env } from "../index"; - -interface UserRow { - id: string; - email: string; - name: string; - email_verified: number; - is_admin: number; - moderation: number; - force_password_change: number; -} - -function unauthorized(description: string): Response { - // Per RFC 6750, signal bearer-token problems via WWW-Authenticate. - return new Response(JSON.stringify({ error: "invalid_token", error_description: description }), { - status: 401, - headers: { - "Content-Type": "application/json", - "WWW-Authenticate": `Bearer error="invalid_token", error_description="${description}"`, - "Cache-Control": "no-store", - }, - }); -} - -// GET|POST /oauth/userinfo (public, on the issuer origin) -// -// Returns the standard OIDC claims for the subject of a valid access token, -// filtered by the token's granted scope. Claims are read live from the DB -// (not the token) so email/name changes and account suspension take effect -// immediately. -export async function handleOAuthUserinfo(request: Request, env: Env): Promise { - const authHeader = request.headers.get("Authorization"); - if (!authHeader?.startsWith("Bearer ")) return unauthorized("missing bearer token"); - - const privateJwk = parsePrivateJwk(env.OIDC_PRIVATE_KEY); - const payload = await verifyRs256(authHeader.slice(7), privateJwk); - if (!payload) return unauthorized("invalid or expired token"); - if (payload.token_use !== "access") return unauthorized("not an access token"); - if (payload.iss !== env.OIDC_ISSUER) return unauthorized("wrong issuer"); - if (typeof payload.sub !== "string" || typeof payload.aud !== "string") { - return unauthorized("malformed token"); - } - - // Mirror the token endpoint's disabled-client refusal so flipping - // disabled=1 cuts off a client's already-issued access tokens too - not just - // new ones. (Also a belt-and-braces audience check.) - const client = await env.DB.prepare( - "SELECT disabled FROM oauth_clients WHERE client_id = ?", - ).bind(payload.aud).first<{ disabled: number }>(); - if (!client || client.disabled) return unauthorized("client no longer authorized"); - - const user = await env.DB.prepare( - "SELECT id, email, name, email_verified, is_admin, moderation, force_password_change FROM users WHERE id = ?", - ).bind(payload.sub).first(); - if (!user || user.force_password_change || checkModeration(user.moderation)) { - return unauthorized("subject no longer valid"); - } - - const scopes = new Set(String(payload.scope ?? "").split(/\s+/).filter(Boolean)); - const oidcUser: OidcUser = { - id: user.id, - email: user.email, - emailVerified: Boolean(user.email_verified), - name: user.name, - isAdmin: Boolean(user.is_admin), - picture: `${env.APP_ORIGIN}/api/avatar/${user.id}`, - }; - - return Response.json(scopedClaims(oidcUser, scopes), { - headers: { "Cache-Control": "no-store" }, - }); -} diff --git a/packages/auth/src/routes/register.ts b/packages/auth/src/routes/register.ts index c431720b..045fc833 100644 --- a/packages/auth/src/routes/register.ts +++ b/packages/auth/src/routes/register.ts @@ -56,7 +56,7 @@ export async function handleRegister(request: Request, env: Env): Promise"] \ -// [--scopes "openid profile email"] \ -// [--require-consent] # show a consent screen instead of auto-approving -// [--public] # SPA/native client: no secret, PKCE only -// -// Then apply the generated file: -// 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 - -import { webcrypto } from "node:crypto"; -import { randomBytes, randomUUID } from "node:crypto"; -import { writeFileSync } from "node:fs"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; - -function parseArgs(argv) { - const out = { redirect: [], scopes: "openid profile email", requireConsent: false, public: false }; - for (let i = 0; i < argv.length; i++) { - const a = argv[i]; - if (a === "--name") out.name = argv[++i]; - else if (a === "--redirect") out.redirect.push(argv[++i]); - else if (a === "--scopes") out.scopes = argv[++i]; - else if (a === "--require-consent") out.requireConsent = true; - else if (a === "--public") out.public = true; - else throw new Error(`Unknown argument: ${a}`); - } - if (!out.name) throw new Error("--name is required"); - if (out.redirect.length === 0) throw new Error("at least one --redirect is required"); - for (const r of out.redirect) { - let u; - try { - u = new URL(r); - } catch { - throw new Error(`--redirect is not a valid absolute URL: ${r}`); - } - if (u.protocol !== "https:" && u.hostname !== "localhost" && u.hostname !== "127.0.0.1") { - throw new Error(`--redirect must be https (or localhost for dev): ${r}`); - } - } - return out; -} - -async function sha256b64url(input) { - const digest = await webcrypto.subtle.digest("SHA-256", new TextEncoder().encode(input)); - return Buffer.from(digest).toString("base64url"); -} - -function sqlString(value) { - return `'${String(value).replace(/'/g, "''")}'`; -} - -const args = parseArgs(process.argv.slice(2)); - -const clientId = `annx_${randomBytes(12).toString("hex")}`; -let clientSecret = null; -let secretHashSql = "NULL"; -if (!args.public) { - clientSecret = randomBytes(32).toString("base64url"); - secretHashSql = sqlString(await sha256b64url(clientSecret)); -} - -const redirectJson = JSON.stringify(args.redirect); -const trusted = args.requireConsent ? 0 : 1; -const createdAt = Date.now(); - -const sql = `INSERT INTO oauth_clients (client_id, client_name, client_secret_hash, redirect_uris, allowed_scopes, trusted, disabled, created_at) -VALUES (${sqlString(clientId)}, ${sqlString(args.name)}, ${secretHashSql}, ${sqlString(redirectJson)}, ${sqlString(args.scopes)}, ${trusted}, 0, ${createdAt}); -`; - -const here = dirname(fileURLToPath(import.meta.url)); -const outFile = join(here, `register-${clientId}.sql`); -writeFileSync(outFile, sql, "utf8"); - -const line = "─".repeat(60); -console.log(`\n${line}`); -console.log(" Connected service registered (apply the SQL below to finish)"); -console.log(line); -console.log(` client_id: ${clientId}`); -if (clientSecret) { - console.log(` client_secret: ${clientSecret}`); - console.log(" ^ shown ONCE - copy into the service's config now"); -} else { - console.log(" client_secret: (none - public client, PKCE only)"); -} -console.log(` client_name: ${args.name}`); -console.log(` redirect_uris: ${redirectJson}`); -console.log(` scopes: ${args.scopes}`); -console.log(` consent screen: ${trusted ? "no (trusted / auto-approve)" : "yes"}`); -console.log(line); -console.log("\nApply it:"); -console.log(` cd packages/auth && npx wrangler d1 execute cubedocs-auth --remote --file ${outFile}`); -console.log("\nThen delete the generated .sql file (it contains the secret hash):"); -console.log(` rm ${outFile}\n`); From e3403625b9bf534185353e3f077f862728002ced Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 22:08:49 -0500 Subject: [PATCH 3/3] 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 | 56 +- CONTRIBUTING.md | 5 +- README.md | 29 +- 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/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 | 95 --- 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 | 210 ------ 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.ts | 258 -------- 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/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 - .../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 - .../frontend/src/components/UserAvatar.tsx | 2 +- packages/frontend/src/lib/fonts.ts | 2 +- packages/frontend/src/lib/handle.test.ts | 2 +- packages/frontend/src/lib/handle.ts | 2 +- packages/frontend/src/lib/theme.ts | 2 +- .../src/pages/AuthCompletePage.test.tsx | 12 +- .../frontend/src/pages/AuthCompletePage.tsx | 20 +- .../frontend/src/pages/UserSettingsPage.tsx | 2 +- pnpm-lock.yaml | 186 ------ scripts/d1-local.mjs | 18 +- scripts/import-auth-data.mjs | 2 +- scripts/migrate.mjs | 12 - scripts/oidc-check.mjs | 70 ++ 265 files changed, 2779 insertions(+), 15004 deletions(-) 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 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.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/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/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 create mode 100644 scripts/oidc-check.mjs diff --git a/CLAUDE.md b/CLAUDE.md index 3c4e65df..1c74390c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,28 +3,30 @@ pnpm + Turbo monorepo - `packages/frontend` - React 19 SPA (Vite, Tailwind CSS 4, shadcn/ui) -- `packages/api` - Core Cloudflare Worker (projects, docs, files) -- `packages/auth` - Auth Cloudflare Worker (login, register, TOTP, WebAuthn) +- `packages/api` - Core Cloudflare Worker (projects, docs, files, Annex sign-in + sessions, billing, preferences) +- `packages/admin` - Admin panel Worker + SPA (`admin.cubityfir.st`) - `packages/mcp` - stdio MCP server over the public `/v1` API, authenticated by one or more site-scoped API keys (see "Public API & Scoped API Keys") ### Auth -Authentication uses `Authorization: Bearer ` headers. JWTs are issued by the Auth Worker and verified by the API Worker via a shared `JWT_SECRET`. The Auth Worker handles all identity concerns (register, login, TOTP, WebAuthn). +Accounts live on the standalone identity service **auth.cubityfir.st** (worker `cubityfirst-auth`, its own repo + D1). Annex is an **OpenID Connect client** of it, like every other service: password, 2FA, passkeys, email changes, sessions on the identity side, account moderation, registration and account deletion all happen there. Annex keeps its own **sessions**, a **users mirror**, and everything Annex-specific (billing/Ink, preferences, handles, badges). See `memories/Identity-Client.md`. -**Verification boundary - read this before touching auth flow:** +**Read this before touching auth flow:** -- **API Worker verifies sessions inline.** It binds the auth D1 as `AUTH_DB` (read-only by convention - no migrations) and calls `loadCurrentSession` from `packages/auth/src/session.ts` directly. One batched read of `sessions` + a `users` row LEFT-JOINed against `user_billing` and `user_preferences`, no service-binding hop. This is what every authenticated API request goes through (`packages/api/src/auth.ts`). -- **Auth Worker owns credential/session writes; the admin worker writes a bounded set of auth-DB tables directly.** Login, register, change-password, session revoke, TOTP/WebAuthn enroll, lookup, etc. are still proxied through the `AUTH` service binding from the API worker. Anything that mutates credentials/sessions or needs rate limiting / email sending stays in the auth worker. The **admin worker** (`packages/admin`), however, binds the auth D1 as `AUTH_DB` read+write and writes these tables directly: `users` (moderation, force_password_change), `user_moderation_events`, `user_preferences` (badges, `handle`/`handle_locked`), `user_billing` (granted-plan columns), `user_deletions` (scheduled account deletion), and `admin_audit_log`. The API worker's `AUTH_DB` binding remains read-only by convention. Migrations still only live in `packages/auth/migrations/`. -- **Cross-package import.** API worker imports `loadCurrentSession`, `sessionResultToResponse`, and `verifyJwt` directly from `packages/auth/src/`. The API tsconfig lists those files in `include`. **A schema change to `users` / `sessions` / `user_billing` / `user_preferences` columns referenced in `loadCurrentSession` requires redeploying auth + api + admin (in that order)**, because all three packages read these tables directly. Migrations themselves still only live in `packages/auth/migrations/`. -- The auth worker's `/verify` endpoint still exists but the API worker no longer calls it - leave it in place for now in case external tooling depends on it. +- **Sign-in** (`packages/api/src/routes/auth.ts`, `src/account/oidc.ts` on oauth4webapi): `GET /api/auth/login` → identity service (PKCE S256, state, nonce in an HMAC-sealed HttpOnly cookie) → `GET /api/auth/callback` (id_token claims + JWKS signature verified, `users` mirror upserted, pending Annex session created, its single-use handoff code set ONLY as an HttpOnly SameSite=Strict `annex_handoff_` cookie - never in a URL, so a crafted link can't sign anyone in; one per sign-in) → SPA `/auth/complete#status=ok&attempt=` → `POST /api/auth/exchange?attempt=` redeems that cookie for the session JWT (kept in localStorage, sent as `Authorization: Bearer`). Sign-out: `POST /api/auth/logout` revokes the session and returns the end-session URL (`id_token_hint` kept on the session row). The admin panel runs the same flow (shared `AuthFlow`) as its own client with session `kind = 'admin'`. +- **Server-side OIDC requests never fetch `https://auth.cubityfir.st` directly.** Annex's workers share the cubityfir.st zone with it, and a Worker's same-zone `fetch()` to another Worker's hostname goes to the origin, not that Worker. Discovery/JWKS/token go through the **`IDENTITY_OIDC`** service binding (`cubityfirst-auth` default export; `identityFetch` in `account/oidc.ts`). Only browser redirects use the public URL. Local dev falls back to the public/local issuer when the binding has no target. +- **Sessions are verified inline** against cubedocs-main (`account/session.ts` `loadCurrentSession(token, env, kind)`: one batch of `sessions` + `users` mirror LEFT JOIN `user_billing`/`user_preferences`/`user_deletions`). The JWT (HS256, Annex-only `JWT_SECRET`) only proves Annex minted the session. **Account standing comes from the identity service** via the **`IDENTITY`** RPC binding (`IdentityService.getUser`, cached ~60s per isolate in `account/identity.ts`, falls back to the mirror's last known standing when unreachable). An admin-scheduled `user_deletions` row blocks the user in Annex regardless. +- **The users mirror** (`users` in cubedocs-main) is refreshed at sign-in and whenever the standing check sees a change; name/email changes are copied to `project_members`/`organization_members` snapshots. `PATCH /me` refuses `name` (owned by the identity service). Invite-by-email asks `IDENTITY.findUserByEmail` and mirrors the result. +- **No `AUTH_DB` / `AUTH` binding, no `packages/auth`.** Don't reintroduce a shared secret or a direct read of the identity DB. ### Database Schemas - **API DB** (`cubedocs-main`): projects, docs (+ `doc_ai_summaries` satellite; `docs.slug` is the doc's custom public-URL segment from the `slug:` frontmatter key - unique per project, normalized + synced by `docOps.syncDocSlug` on every save path incl. collab checkpoints and restores, resolved by `/public/docs/:site/:idOrSlug`), doc_revisions, folders, files, members, site_reports + user_reports (abuse reports: public "Report Site" button → `POST /public/projects/:id/report`, profile-card "Report user" → authenticated `POST /users/:id/report`; both triaged via the admin worker's `/api/reports/{sites,users}` routes + the admin "Reports" page's Sites/Users tabs) - see `packages/api/migrations/`. Bound as `DB` on the API worker. - **Recycle bin** (API DB, `0062_add_trash.sql`, `lib/trash.ts`, `routes/trash.ts`, `components/RecycleBin.tsx` - shown as the "Recycle bin" section of Site Settings, `/projects/:id/trash` redirects there): deleting a doc/file/folder (app, or `/v1` doc DELETE) **moves its rows out of** `docs`/`files`/`folders` into `trash_items` JSON snapshots (one `trash_entries` row per user-visible entry; a folder bins its whole subtree as one entry, except the home doc, which is moved to the root). Because binned rows are physically gone from the live tables, **no reader needs a "not deleted" filter - don't add one, and don't hard-delete docs/files/folders from a route; call `moveToTrash`**. Cascade-lost satellites that aren't derivable (`doc_shares`, the `docs_fts` row, `site_reports.doc_id`) ride in `extra_json` and come back on restore; R2 objects + `asset_revisions` stay until purge. Restore/list = editor+, delete-forever/empty = admin+, auto-purge after 30 days on the daily cron. Site deletion (api + admin) must include `trash_items` ids in its R2 sweep. `trash.test.ts` runs against real SQLite via `src/test/sqliteD1.ts` (all migrations applied) - use that harness for SQL-heavy logic. - **Doc search index** (API DB, `0064_rebuild_docs_fts.sql`, `lib/fts.ts`): `docs_fts` is FTS5 with an indexed `pid` = `hex(project_id)` token column plus a `docs_fts_map(rid, doc_id)` rowid map, so per-doc writes are rowid lookups and search MATCHes `pid:""` (`siteFtsMatch`) instead of scanning every site. **Never write `docs_fts` with raw SQL (`WHERE doc_id = ?` / `WHERE project_id = ?` are full scans, and a bare INSERT gets no `pid` or map row) - use the `fts*Statements` helpers**, which keep exactly one map row per FTS row and compose into a caller's batch (the insert + map statements must stay adjacent: `last_insert_rowid()`). Search weights stay `bm25(docs_fts, 5.0, 1.0, 0.0)` (pid weighted 0). `scripts/repair-docs-fts.sql` reconciles rows written by pre-0064 code. -- **Admin account deletion is always delayed** (auth `0034_add_user_deletions.sql`, admin `lib/userDeletion.ts`, Users page checkboxes → bulk Delete/Disable/Re-enable/Cancel deletion): "Delete" only **schedules** - it disables the account now and writes a `user_deletions` row; the admin worker's hourly cron (`runDueUserDeletions`) performs the delete after 7 days, and any admin can cancel before then (restoring the prior moderation). Owned sites/orgs are deleted **only** when the operator ticked an explicit per-account box in the preview, scheduling refuses unless the confirmed ids exactly match current ownership (`sameIdSet`), and execution refuses if the account owns anything outside them. While a deletion is pending, `PATCH /api/users/:id` moderation is refused - cancel instead (the guard is inside the write, not just a pre-check). The cron claims each schedule by `(user_id, id)` with a lease; cancel is refused while leased or once `started_at` is set (first irreversible step), after which a failed run is retried to completion - a confirmed site/org that no longer exists counts as done. Real-SQLite scenario tests: `userDeletion.sqlite.test.ts`. **Don't add an immediate admin delete path.** Site deletion itself is shared via `lib/projectDelete.ts`. -- **Auth DB** (`cubedocs-auth`): users, sessions, totp, webauthn_credentials, plus the 1:1 satellites `user_billing` (Stripe + plan state) and `user_preferences` (fonts, Ink cosmetics, timezone, bio, badges, opt-in profile `handle`) - see `packages/auth/migrations/`. The `handle` (`0035`, partial unique index, stored lowercase, rules in `packages/auth/src/handle.ts` mirrored by `frontend/src/lib/handle.ts`) powers the `/@` profile link: set/cleared via auth `/update-handle` (proxied as `PATCH /me/handle`), resolved by the API's `GET /users/by-handle/:handle` reading `AUTH_DB` directly. Null = link off. Admins moderate it via the admin worker's `PATCH /api/users/:id/handle` (Users → details → "Profile Link"; may assign reserved names) and can set `handle_locked`, which makes `/update-handle` refuse every user change (403 `reason: "locked"`, guarded inside the write too). Bound as `DB` on the auth worker (read+write), as `AUTH_DB` on the API worker (read-only by convention), and as `AUTH_DB` on the admin worker (read+write for moderation/badges/billing-grants/audit - see the verification-boundary note above). **A schema change to any column these direct readers/writers touch requires redeploying auth + api + admin (in that order).** +- **Admin deletion is always delayed and deletes Annex data only** (api `0065_add_identity_mirror.sql` `user_deletions`, admin `lib/userDeletion.ts`, Users page checkboxes → bulk Delete/Cancel deletion): "Delete" only **schedules** - the `user_deletions` row blocks the person from Annex at once; the admin worker's hourly cron (`runDueUserDeletions`) deletes their Annex data after 7 days (Stripe customer, confirmed sites/orgs, memberships, billing, preferences, sessions) and sets `completed_at`. The users mirror row and schedule stay, so they remain blocked until the operator deletes the **identity account on auth.cubityfir.st** (Annex never deletes it). Any admin can cancel before execution starts. Moderation (disable/suspend) happens on auth.cubityfir.st, not in the Annex admin. Owned sites/orgs are deleted **only** when the operator ticked an explicit per-account box in the preview, scheduling refuses unless the confirmed ids exactly match current ownership (`sameIdSet`), and execution refuses if the account owns anything outside them. The cron claims each schedule by `(user_id, id)` with a lease; cancel is refused while leased or once `started_at` is set (first irreversible step), after which a failed run is retried to completion - a confirmed site/org that no longer exists counts as done; completed rows are never re-run. Real-SQLite scenario tests: `userDeletion.sqlite.test.ts`. **Don't add an immediate admin delete path.** Site deletion itself is shared via `lib/projectDelete.ts`. +- **Account data** (cubedocs-main, `0065_add_identity_mirror.sql`; copied once from the retired `cubedocs-auth` by `scripts/import-auth-data.mjs`): the `users` mirror (`id` = OIDC `sub`, email, name, is_admin, last known `status`/`suspended_until`), Annex `sessions` (`kind` app/admin, `id_token`, single-use `handoff_hash`), and the satellites `user_billing` (Stripe + plan state) and `user_preferences` (fonts, theme, Ink cosmetics, timezone, bio, badges, opt-in profile `handle` + `handle_locked`), plus `webhook_events`, `user_deletions`, `user_moderation_events` (read-only history), `admin_audit_log` and `identity_deletions`. The `handle` (partial unique index, stored lowercase, rules in `packages/api/src/account/handle.ts` mirrored by `frontend/src/lib/handle.ts`) powers the `/@` profile link: set via `PATCH /me/handle`, resolved by `GET /users/by-handle/:handle`; admins moderate it via the admin worker's `PATCH /api/users/:id/handle` and can lock it (`403 reason: "locked"`). +- **Deletion sync** (api `lib/identityDeletions.ts`, hourly cron `23 * * * *`): `IDENTITY.listDeletedUsers` from the newest recorded `identity_deletions.deleted_at`; for each account it deletes the Stripe customer, memberships, API keys, shares, favourites, avatars and the users mirror row (cascading the rest). **Sites/orgs the person owned are kept** (owner rows too) and listed on the admin Projects page ("Owner account deleted") for an operator to delete or leave. Failures stay pending with `last_error` and retry. #### Satellite tables and the resolver @@ -33,9 +35,9 @@ Authentication uses `Authorization: Bearer ` headers. JWTs are issued by th - Satellite row is created lazily - first write does `INSERT … ON CONFLICT(parent_id) DO UPDATE SET …`. A user/doc/etc. that has never had the feature touched has no satellite row at all. - Every reader does `LEFT JOIN ON ._id = .id`. Missing rows return NULL for every satellite column, which the consumer treats as "default." - The satellite declares `REFERENCES (id) ON DELETE CASCADE` so deleting the parent wipes the satellite row automatically. -- Existing satellites: `doc_ai_summaries` (api DB; ai_summary cache), `user_billing` (auth DB; Stripe/plan state), `user_preferences` (auth DB; fonts + cosmetics + timezone + bio + badges). +- Existing satellites: `doc_ai_summaries` (ai_summary cache), `user_billing` (Stripe/plan state), `user_preferences` (fonts + cosmetics + timezone + bio + badges + handle). All in cubedocs-main. -`resolvePersonalPlan` in `packages/auth/src/plan.ts` is fed inputs from multiple tables (billing-state from `user_billing`, cosmetic prefs from `user_preferences`). Callers build a flat `PlanRow` from the LEFT-JOINed query result and hand it to the resolver - see `loadCurrentSession`, `members.ts`, `update-ink-prefs.ts` for the pattern. +`resolvePersonalPlan` in `packages/api/src/account/plan.ts` is fed inputs from multiple tables (billing-state from `user_billing`, cosmetic prefs from `user_preferences`). Callers build a flat `PlanRow` from the LEFT-JOINed query result and hand it to the resolver - see `loadCurrentSession`, `members.ts`, `routes/me/update-ink-prefs.ts` for the pattern. ## Frontend Notes @@ -62,7 +64,7 @@ The landing page's "See a demo" links to **`/demo`**, a local-only sandbox: a se ## Annex Ink + Stripe -Personal supporter subscription ($5/mo) with Stripe billing, comp-grant override, animated avatar ring, admin grant/revoke/cancel controls, and a webhook proxy through the frontend worker. **Anything touching the `user_billing` table (Stripe ids, `personal_plan_*`, `granted_plan_*`), the cosmetic-pref columns on `user_preferences` (`personal_plan_style`, `personal_presence_color`, `personal_crit_sparkles`), `billing.ts`, `stripe-webhook.ts`, the billing UI in user settings or the admin user-details sheet, or the `InkBillingCard` belongs to this system** - see `memories/Ink-Stripe.md` for schema, plan resolution rules, webhook flow, deploy/dev setup, and ops cheatsheet. +Personal supporter subscription ($5/mo) with Stripe billing, comp-grant override, animated avatar ring, admin grant/revoke/cancel controls, and a webhook proxy through the frontend worker. **Anything touching the `user_billing` table (Stripe ids, `personal_plan_*`, `granted_plan_*`), the cosmetic-pref columns on `user_preferences` (`personal_plan_style`, `personal_presence_color`, `personal_crit_sparkles`), `routes/billing.ts`, `routes/stripeWebhook.ts` (api worker), the billing UI in user settings or the admin user-details sheet, or the `InkBillingCard` belongs to this system** - see `memories/Ink-Stripe.md` for schema, plan resolution rules, webhook flow, deploy/dev setup, and ops cheatsheet. ## Realtime Collaboration @@ -92,24 +94,24 @@ A site owner can map their **own domain** (e.g. `docs.example.com`) to their pub Annex is **not** an OpenID Connect provider any more. Since 2026-11-18 the provider is the standalone `cubityfirst-auth` worker at `https://auth.cubityfir.st` -(its own repo and D1). annex-auth no longer serves `/oauth/*` or `/.well-known/*`, -has no `auth.cubityfir.st` routes (that hostname is cubityfirst-auth's Custom -Domain - **never re-add those triggers**), and holds no OIDC signing key. OAuth -clients are managed at `auth.cubityfir.st/admin/clients`. The old -`docs.cubityfir.st/oauth/authorize` URL redirects to the provider. See +(its own repo and D1); Annex is one of its clients (see "Auth" above). The +`auth.cubityfir.st` hostname is cubityfirst-auth's Custom Domain - **never add +routes for it to an Annex worker**. OAuth clients are managed at +`auth.cubityfir.st/admin/clients`. The old `docs.cubityfir.st/oauth/authorize` +URL redirects to the provider (frontend worker + SPA shim). See `docs/oauth/README.md`. ## Tests Tests exist - run them before reporting work as done when changes are testable. -- **Vitest unit tests** live next to source as `*.test.ts(x)` in each package. Run per-package with `pnpm --filter test`, or all packages + e2e with `pnpm test` from the root. Coverage is heaviest in `packages/auth` (login, password, jwt, totp, plan, billing, stripe-webhook) and `packages/frontend/src/lib` (remark plugins, dice, frontmatter, userColor). -- **Playwright e2e tests** live in `e2e/tests/` (one `*.spec.ts` per feature area - list the directory to see current coverage). Run with `pnpm test:e2e` (headless) or `pnpm test:e2e:ui` (UI mode). First run needs `pnpm --filter cubedocs-e2e install:browsers`. +- **Vitest unit tests** live next to source as `*.test.ts(x)` in each package. Run per-package with `pnpm --filter test`, or all packages + e2e with `pnpm test` from the root. Sign-in is covered end to end against a fake OpenID provider (`packages/api/src/test/fakeIdp.ts`, `routes/auth.test.ts`); SQL-heavy logic runs on real SQLite (`src/test/sqliteD1.ts`, `test/session.ts` seeds a mirror user + session). +- **Playwright e2e tests** live in `e2e/tests/` (one `*.spec.ts` per feature area - list the directory to see current coverage). Accounts live on auth.cubityfir.st, so suites sign in with `e2e/signIn.ts` (`devSignIn` via the api worker's localhost-only `POST /api/dev/quick-login`; needs `DEV_QUICK_LOGIN=true` + `APP_ORIGIN=http://localhost:5173` in `packages/api/.dev.vars`). `admin.spec.ts` uses the admin worker's own `POST /api/dev/quick-login` (`DEV_QUICK_LOGIN=true` + `APP_ORIGIN=http://localhost:5174` in `packages/admin/.dev.vars`). Keep `OIDC_ISSUER` in both `.dev.vars` local (see the `.example` files) so sign-out never redirects a test to the real provider. Run with `pnpm test:e2e` (headless) or `pnpm test:e2e:ui` (UI mode). First run needs `pnpm --filter cubedocs-e2e install:browsers`. - When adding behavior with existing test coverage in the same area, extend the corresponding suite rather than leaving it untested. ## Commits -Use Conventional Commits with a type **and** scope: `(): ` (e.g. `feat(frontend): draft-first doc creation`, `fix(auth): ...`). Types/scopes are listed in `CONTRIBUTING.md` - scope is the package (`frontend`, `api`, `auth`, `admin`, `e2e`) or feature area (`files`, `search`, `orgs`, `billing`, `collab`, `oidc`, ...). +Use Conventional Commits with a type **and** scope: `(): ` (e.g. `feat(frontend): draft-first doc creation`, `fix(auth): ...`). Types/scopes are listed in `CONTRIBUTING.md` - scope is the package (`frontend`, `api`, `admin`, `e2e`) or feature area (`files`, `search`, `orgs`, `billing`, `collab`, `oidc`, ...). ## CLI Notes @@ -117,10 +119,10 @@ Use Conventional Commits with a type **and** scope: `(): --persist-to ../../.wrangler/state`, which loads `cloudflare.config.ts` + `wrangler.config.ts` (and `.dev.vars`) directly. Plain `cf dev` isn't used because it can't take a persist dir yet, and all workers must share one state dir (the api reads auth's DB via `AUTH_DB`). The frontend's `pnpm dev` is plain Vite. -- **Local D1 SQL** (no Wrangler config means `wrangler d1 execute --local` can't resolve a database, and `cf d1 query --local` isn't implemented yet): use `node scripts/d1-local.mjs ""` (or `--file`), which runs through the running api dev server's Local Explorer API against the shared state - see "Local D1 State" below. Remote commands (`npx wrangler d1 execute --remote`, `npx wrangler r2 object ... --remote`) work without a config file. +- **Local dev** (`pnpm dev`): api/admin run `wrangler dev --experimental-new-config --port --persist-to ../../.wrangler/state`, which loads `cloudflare.config.ts` + `wrangler.config.ts` (and `.dev.vars`) directly. Plain `cf dev` isn't used because it can't take a persist dir yet, and both workers must share one state dir (they share cubedocs-main). The frontend's `pnpm dev` is plain Vite. **Sign-in locally**: run the identity worker (`G:\scripts\auth`) with `npx wrangler dev --port 8790` (Annex's api owns :8787) and point `OIDC_*` in `packages/{api,admin}/.dev.vars` at it (see the `.dev.vars.example` files), or skip it with the dev quick-login buttons (`DEV_QUICK_LOGIN=true`). +- **Local D1 SQL** (no Wrangler config means `wrangler d1 execute --local` can't resolve a database, and `cf d1 query --local` isn't implemented yet): use `node scripts/d1-local.mjs main ""` (or `--file`), which runs through the running api dev server's Local Explorer API against the shared state - see "Local D1 State" below. Remote commands (`npx wrangler d1 execute --remote`, `npx wrangler r2 object ... --remote`) work without a config file. - D1 migrations: `pnpm migrate` / `node scripts/migrate.mjs ` run `cf d1 migrations apply ` (remote unless `--local`). - `annex-api`'s `DocCollabRoom` is declared as `exports.durableObject({ storage: "legacy-kv" })` - it was created with `new_classes` (KV-backed). Never change it to `"sqlite"`. - The frontend package depends on Vite, so `cf build` would run `vite build` instead of Wrangler; its deploy is `pnpm build && pnpm build:worker (cf-wrangler build) && cf deploy --prebuilt`. @@ -132,10 +134,10 @@ The dev servers use a shared wrangler state at the **monorepo root** (`/.wrangle Local migrations (`pnpm migrate` / `node scripts/migrate.mjs local`) pass `--persist-to ../../.wrangler/state` from the package directory; any manual `cf d1 migrations apply --local` must too, otherwise it hits a state the dev servers never read. -Ad-hoc local queries go through `scripts/d1-local.mjs` (needs `pnpm dev` running - it talks to the api worker on :8787, override with `ANNEX_DEV_API_ORIGIN`). `main` = `cubedocs-main`, `auth` = `cubedocs-auth`; it prints the last statement's rows as JSON. Use it for DML/SELECTs - schema changes belong in migrations. e2e specs use the `e2e/d1Local.ts` wrapper. +Ad-hoc local queries go through `scripts/d1-local.mjs` (needs `pnpm dev` running - it talks to the api worker on :8787, override with `ANNEX_DEV_API_ORIGIN`). `main` = `cubedocs-main` (the only database; accounts live on auth.cubityfir.st); it prints the last statement's rows as JSON. Use it for DML/SELECTs - schema changes belong in migrations. e2e specs use the `e2e/d1Local.ts` wrapper. ``` -node scripts/d1-local.mjs auth "SELECT id, email FROM users LIMIT 5" +node scripts/d1-local.mjs main "SELECT id, email, status FROM users LIMIT 5" node scripts/d1-local.mjs main "UPDATE projects SET features = features | 4 WHERE id = ''" ``` @@ -143,7 +145,7 @@ node scripts/d1-local.mjs main "UPDATE projects SET features = features | 4 WHER For running several feature branches side-by-side (e.g. many agents in parallel, each reviewable in a browser on its own port), use `scripts/worktree.mjs`. The main checkout runs -the full stack via `pnpm dev` (frontend 5173 + api 8787 + auth 8788 + admin 8789 + the shared +the full stack via `pnpm dev` (frontend 5173 + api 8787 + admin 8789 + the shared `.wrangler/state` D1) - that's the **one backend**. Each worktree adds **another frontend** on its own port, and the Vite `/api` proxy (hardcoded to `:8787` in `vite.config.ts`) makes every worktree frontend talk to that single backend and share the one dev DB. No app-code or diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ce73fb5..4e674a00 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ This is a pnpm + Turbo monorepo (`packageManager: pnpm@10`, Node 20+ recommended ```sh pnpm install pnpm migrations:local # apply D1 migrations to the shared local dev state -pnpm dev # frontend :5173, api :8787, auth :8788, admin :8789 +pnpm dev # frontend :5173, api :8787, admin :8789 (+ admin SPA :5174) ``` The dev servers share one local state at the monorepo root (`.wrangler/state`). Worker config lives only in each package's `cloudflare.config.ts` (+ `wrangler.config.ts` for build settings) - there is no `wrangler.toml`. Local migrations (`pnpm migrate`) pass `--persist-to ../../.wrangler/state` from the package directory; for ad-hoc local SQL use `node scripts/d1-local.mjs ""` while `pnpm dev` is running. All wrangler invocations go through `npx wrangler`. @@ -16,7 +16,6 @@ The dev servers share one local state at the monorepo root (`.wrangler/state`). - `packages/frontend` - React 19 SPA (Vite, Tailwind CSS 4, shadcn/ui) - `packages/api` - Core Cloudflare Worker (projects, docs, files) -- `packages/auth` - Auth Cloudflare Worker (login, register, TOTP, WebAuthn, OIDC) - `packages/admin` - Admin Cloudflare Worker + admin frontend - `e2e` - Playwright end-to-end tests @@ -63,5 +62,5 @@ When you add behavior in an area that already has a test suite, extend that suit ## Pull requests - Keep PRs focused on one change; separate refactors from behavior changes. -- Schema changes: migrations live only in `packages/api/migrations/` and `packages/auth/migrations/`. A change to auth-DB columns read by `loadCurrentSession` requires redeploying auth + api + admin, in that order - call this out in the PR description. +- Schema changes: migrations live only in `packages/api/migrations/` (cubedocs-main, shared by the api and admin workers). A change to columns read by `loadCurrentSession` (users mirror, sessions, user_billing, user_preferences, user_deletions) needs both workers redeployed (api first) - call this out in the PR description. Accounts themselves live on auth.cubityfir.st. - If you add or remove a runtime dependency in `packages/frontend`, update `src/lib/acknowledgements.ts` to match. diff --git a/README.md b/README.md index 923c9eb6..7eac1965 100644 --- a/README.md +++ b/README.md @@ -80,18 +80,15 @@ Create local secrets files for each Worker: ```bash cp packages/api/.dev.vars.example packages/api/.dev.vars -cp packages/auth/.dev.vars.example packages/auth/.dev.vars +cp packages/admin/.dev.vars.example packages/admin/.dev.vars ``` -Both Workers need a shared `JWT_SECRET`: - -```ini -# packages/api/.dev.vars -JWT_SECRET=your-secret-here - -# packages/auth/.dev.vars -JWT_SECRET=your-secret-here # must match api -``` +Accounts live on the identity service at auth.cubityfir.st, and Annex signs +in through it with OpenID Connect. Locally you can either run that worker (its +repo, `npx wrangler dev --port 8790`) and register local clients as described +in the `.dev.vars.example` files, or skip it: with `DEV_QUICK_LOGIN=true` (the +default in the example) `/login` shows dev quick-login buttons. See +`memories/Identity-Client.md`. **3. Apply local database migrations** @@ -113,7 +110,7 @@ Starts all packages concurrently. Once running: |---|---| | Frontend | http://localhost:5173 | | API Worker | http://localhost:8787 | -| Auth Worker | http://localhost:8788 | +| Admin Worker | http://localhost:8789 | | Admin Dashboard | http://localhost:5174 | The frontend dev server automatically proxies `/api` requests to the local Workers - no separate configuration needed. @@ -138,7 +135,7 @@ Then `stripe login` once to authorise the CLI against your Stripe account. **2. Add Stripe secrets to `.dev.vars`** ```ini -# packages/auth/.dev.vars +# packages/api/.dev.vars STRIPE_SECRET_KEY=sk_test_... # from Stripe Dashboard → API keys (test mode) STRIPE_WEBHOOK_SECRET=whsec_... # filled in step 3 STRIPE_INK_PRICE_ID=price_... # the test-mode Annex Ink price id @@ -148,18 +145,18 @@ APP_ORIGIN=http://localhost:5173 # so Checkout redirects come back to loc STRIPE_SECRET_KEY=sk_test_... # same value, for admin-driven cancels ``` -**3. Forward Stripe webhooks to the local auth worker** +**3. Forward Stripe webhooks to the local api worker** In a separate terminal alongside `pnpm dev`: ```bash pnpm dev:stripe -# (equivalent to: stripe listen --forward-to http://localhost:8788/stripe/webhook) +# (equivalent to: stripe listen --forward-to http://localhost:8787/stripe/webhook) ``` -The CLI prints a `whsec_...` at startup - paste it into `packages/auth/.dev.vars` as `STRIPE_WEBHOOK_SECRET`, then restart the auth worker dev so it picks up the new value. The `whsec_` printed by the CLI is only valid for events forwarded by that CLI session; it's separate from the live-mode webhook secret in the Stripe Dashboard. +The CLI prints a `whsec_...` at startup - paste it into `packages/api/.dev.vars` as `STRIPE_WEBHOOK_SECRET`, then restart the api worker dev so it picks up the new value. The `whsec_` printed by the CLI is only valid for events forwarded by that CLI session; it's separate from the live-mode webhook secret in the Stripe Dashboard. -Without `pnpm dev:stripe` running, the local auth worker will accept webhook POSTs from the public internet but won't see any. Local checkouts will succeed at Stripe, but local DB state won't update until events are forwarded. +Without `pnpm dev:stripe` running, the local api worker will accept webhook POSTs from the public internet but won't see any. Local checkouts will succeed at Stripe, but local DB state won't update until events are forwarded. ## Direct video streaming via presigned R2 URLs (optional) diff --git a/e2e/d1Local.ts b/e2e/d1Local.ts index 51b3dbcc..2e99192f 100644 --- a/e2e/d1Local.ts +++ b/e2e/d1Local.ts @@ -6,12 +6,12 @@ const SCRIPT = resolve(__dirname, "../scripts/d1-local.mjs"); /** * Run SQL against the local dev D1 (the shared .wrangler/state behind * `pnpm dev`) via scripts/d1-local.mjs - the config-free replacement for - * `npx wrangler d1 execute --local`. `main` = cubedocs-main (api DB), - * `auth` = cubedocs-auth. Needs the api dev server (:8787) running, which every + * `npx wrangler d1 execute --local`. `main` = cubedocs-main (the only + * database). Needs the api dev server (:8787) running, which every * e2e spec already does. Spawned without a shell, so SQL quotes pass through * verbatim. Throws with the helper's error message on failure. */ -export function d1Local(db: "main" | "auth", sql: string): void { +export function d1Local(db: "main", sql: string): void { try { execFileSync(process.execPath, [SCRIPT, db, sql], { stdio: "pipe" }); } catch (err) { diff --git a/e2e/global-teardown.ts b/e2e/global-teardown.ts index cd31c227..c37657a0 100644 --- a/e2e/global-teardown.ts +++ b/e2e/global-teardown.ts @@ -10,12 +10,12 @@ import { d1Local } from "./d1Local"; // so it writes the local D1 directly (scripts/d1-local.mjs, via the running // api dev server). It also runs on Playwright failure exits. // -// FK cascades handle most of the auth-DB tail (sessions, webauthn, backup -// codes, moderation events). email_verification_tokens has no cascade, so we -// delete it explicitly first. On the API DB, deleting projects cascades -// everything below (docs, folders, files, members, invite links). +// Accounts live on auth.cubityfir.st; Annex keeps a users mirror in +// cubedocs-main, where deleting a mirror row cascades its sessions, billing +// and preferences. Deleting projects cascades everything below them (docs, +// folders, files, members, invite links). export default async function globalTeardown() { - const run = (db: "main" | "auth", sql: string) => { + const run = (db: "main", sql: string) => { try { d1Local(db, sql); } catch (err) { @@ -25,12 +25,8 @@ export default async function globalTeardown() { } }; - // Auth DB: orphan tokens first, then users (cascades the rest). - run( - "auth", - "DELETE FROM email_verification_tokens WHERE user_id IN (SELECT id FROM users WHERE email LIKE 'e2e-%@example.com');", - ); - run("auth", "DELETE FROM users WHERE email LIKE 'e2e-%@example.com';"); + // Users mirror (e2e users are dev quick-login users or e2e-* addresses). + run("main", "DELETE FROM users WHERE email LIKE 'e2e-%@example.com';"); // API DB: delete e2e-suite projects by name prefix (cascades everything). // Patterns track the names used in app.spec.ts, invites.spec.ts, and diff --git a/e2e/signIn.ts b/e2e/signIn.ts new file mode 100644 index 00000000..66deb534 --- /dev/null +++ b/e2e/signIn.ts @@ -0,0 +1,28 @@ +import type { Page } from "@playwright/test"; + +/** + * Signs a browser page in as a local-dev Annex user without the identity + * service. Accounts live on auth.cubityfir.st now, so the suites can no + * longer register through Annex's own forms; this uses the api worker's + * localhost-only POST /api/dev/quick-login (packages/api/src/routes/auth.ts), + * which needs `DEV_QUICK_LOGIN=true` and `APP_ORIGIN=http://localhost:5173` + * in packages/api/.dev.vars. + * + * The same email always maps to the same dev user, so a spec can sign the + * same person back in. Use `e2e-…@example.com` addresses so global-teardown + * cleans them up. + */ +export async function devSignIn( + page: Page, + user: { email: string; name?: string; admin?: boolean }, +): Promise<{ token: string; userId: string }> { + const res = await page.request.post("/api/dev/quick-login", { data: user }); + if (!res.ok()) throw new Error(`dev quick-login failed (${res.status()}): is DEV_QUICK_LOGIN=true set for the api worker?`); + const { data } = (await res.json()) as { data: { token: string; userId: string } }; + // The SPA keeps its session JWT in localStorage["token"] (src/lib/auth.ts). + await page.goto("/"); + await page.evaluate(token => window.localStorage.setItem("token", token), data.token); + // Land where a sign-in does. + await page.goto("/dashboard"); + return data; +} diff --git a/e2e/tests/2fa.spec.ts b/e2e/tests/2fa.spec.ts deleted file mode 100644 index eab11f03..00000000 --- a/e2e/tests/2fa.spec.ts +++ /dev/null @@ -1,405 +0,0 @@ -/** - * E2E tests for two-factor authentication. - * - * Covers: - * - TOTP: enable, login with code, disable - * - WebAuthn: register a virtual passkey, login with it, remove it - * - * Prerequisites - run from the monorepo root: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * WEBAUTHN_RP_ID=localhost - * WEBAUTHN_ORIGIN=http://localhost:5173 - * - * A fresh account is registered at the start and deleted in afterAll, so no - * data is left behind even if tests fail mid-way. - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-2fa-${RUN_ID}@example.com`; -const PASSWORD = "2FA-Test-P@ssw0rd!"; -const NAME = "2FA Test User"; -// Offset +1 from app.spec so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 1) % 256}`; - -// ── TOTP secret shared across tests in this file ───────────────────────────── - -// Captured during "enables authenticator app" and reused in subsequent tests. -let totpSecret = ""; - -// ── TOTP helper ─────────────────────────────────────────────────────────────── - -/** - * Computes the current TOTP code for a base32-encoded secret. - * Mirrors the HOTP implementation in packages/auth/src/totp.ts. - * The auth server accepts ±1 time step, so clock drift of up to 30 s is fine. - */ -async function computeTOTP(secret: string): Promise { - const BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - const clean = secret.toUpperCase().replace(/[^A-Z2-7]/g, ""); - const bytes: number[] = []; - let bits = 0, value = 0; - for (const char of clean) { - const idx = BASE32.indexOf(char); - if (idx === -1) continue; - value = (value << 5) | idx; - bits += 5; - if (bits >= 8) { - bits -= 8; - bytes.push((value >>> bits) & 255); - } - } - const secretBytes = new Uint8Array(bytes); - const counter = Math.floor(Date.now() / 1000 / 30); - const key = await crypto.subtle.importKey( - "raw", secretBytes.buffer, - { name: "HMAC", hash: "SHA-1" }, - false, ["sign"], - ); - const counterBuf = new ArrayBuffer(8); - new DataView(counterBuf).setBigUint64(0, BigInt(counter), false); - const hmac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBuf)); - const offset = hmac[19] & 0x0f; - const code = ( - ((hmac[offset] & 0x7f) << 24) | - ((hmac[offset + 1] & 0xff) << 16) | - ((hmac[offset + 2] & 0xff) << 8) | - (hmac[offset + 3] & 0xff) - ) % 1_000_000; - return code.toString().padStart(6, "0"); -} - -/** - * Fills a shadcn/ui InputOTP widget. - * input-otp renders a native positioned absolutely over - * the visual slot divs. We click that native input directly to focus it, then - * keyboard.type flows each digit into successive slots automatically. - */ -async function fillOTP(page: Page, code: string) { - const otpInput = page.locator('[data-input-otp]').first(); - await otpInput.click(); - await page.keyboard.type(code); -} - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -let cdpSession: any = null; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - // ?logout=1 tells LoginPage to call clearToken() before checking for an - // existing session, so the user lands on the login form rather than being - // redirected straight to the dashboard. - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function loginWithPassword(p: Page) { - await p.goto("/login"); - await p.getByLabel("Email").fill(EMAIL); - await p.getByLabel("Password").fill(PASSWORD); - await expect(p.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await p.getByRole("button", { name: "Sign in" }).click(); -} - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. The "deletes the account - 2FA -// confirmation required" test exercises the UI delete flow itself. -test.afterAll(async () => { - if (cdpSession) { - await cdpSession.detach().catch(() => {}); - cdpSession = null; - } - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account for 2FA testing", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ════════════════════════════════════════════════════════════════════════════ -// TOTP -// ════════════════════════════════════════════════════════════════════════════ - -test("TOTP - enables authenticator app", async () => { - await page.goto("/settings"); - await page.getByRole("button", { name: "Set up authenticator app" }).click(); - - // The UI shows a QR code and the manual-entry secret in a element. - const secretEl = page.locator("code").first(); - await expect(secretEl).toBeVisible({ timeout: 5000 }); - totpSecret = (await secretEl.textContent())?.trim() ?? ""; - expect(totpSecret.length).toBeGreaterThan(10); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // First sign-in factor on the account, so enrollment asks for the password. - await page.locator("#totp-enrollment-password").fill(PASSWORD); - await page.getByRole("button", { name: "Enable 2FA" }).click(); - - // Setup exits and the disable button appears. - await expect(page.getByRole("button", { name: "Disable authenticator app" })).toBeVisible({ timeout: 10000 }); -}); - -test("TOTP - login prompts for the authenticator code", async () => { - await logout(page); - await loginWithPassword(page); - // Server returns totp_required → login page switches to the TOTP step. - await expect(page.getByText("Two-factor authentication")).toBeVisible({ timeout: 8000 }); - await expect(page.getByText(/authenticator code/i)).toBeVisible({ timeout: 3000 }); -}); - -test("TOTP - entering a valid code completes login", async () => { - // Still on the TOTP challenge screen from the previous test. - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // The 2FA step auto-submits once six digits are entered (no Turnstile here, - // and clicking "Verify" again would replay the now-consumed code), so just - // wait for the redirect off the login page. - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); -}); - -test("TOTP - a parent settings dialog survives the stacked 2FA dialog", async () => { - // Regression: the change-email/change-password dialogs and the use2FA dialog - // are sibling Radix modals. Opening the 2FA dialog used to make the parent - // dismiss itself (resetting its fields), and the focus shuffle could knock - // the 2FA dialog down too. The parent must keep its state through the whole - // 2FA exchange. - await page.goto("/settings"); - await page.getByRole("button", { name: "Change email address" }).click(); - await page.getByLabel("New email address", { exact: true }).fill("stacked-dialogs@example.com"); - await page.getByLabel("Current password", { exact: true }).fill("wrong-on-purpose"); - await page.getByRole("button", { name: "Change email", exact: true }).click(); - - // 2FA dialog stacks on top (the parent is aria-hidden behind it, so it - // disappears from the accessibility tree - that's expected). - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // The wrong password is rejected AFTER 2FA passes - the parent dialog must - // reappear with its fields intact so the user can just fix the password. - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - await expect(page.getByRole("dialog", { name: "Change email address" })).toBeVisible(); - await expect(page.getByLabel("New email address", { exact: true })).toHaveValue("stacked-dialogs@example.com"); - - // And it still closes cleanly on demand. - await page.getByRole("dialog", { name: "Change email address" }).getByRole("button", { name: "Cancel" }).click(); - await expect(page.getByRole("dialog", { name: "Change email address" })).not.toBeVisible(); -}); - -test("TOTP - disables authenticator app (requires TOTP confirmation)", async () => { - await page.goto("/settings"); - // The security-status fetch can get dropped under full-suite load, leaving - // the section without the button - reload and retry rather than hang. - const disableBtn = page.getByRole("button", { name: "Disable authenticator app" }); - await expect(async () => { - if (!(await disableBtn.isVisible().catch(() => false))) await page.reload(); - await expect(disableBtn).toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await disableBtn.click(); - - // use2FA dialog opens in TOTP mode (only TOTP is active on this account). - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // "Set up authenticator app" reappears after disabling. - await expect(page.getByRole("button", { name: "Set up authenticator app" })).toBeVisible({ timeout: 10000 }); - totpSecret = ""; // no longer valid -}); - -test("TOTP - login no longer requires a code after disabling", async () => { - await logout(page); - await loginWithPassword(page); - // Should go straight to the dashboard without a TOTP prompt. - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); - await expect(page.getByText(/two.factor authentication/i)).not.toBeVisible(); -}); - -// ════════════════════════════════════════════════════════════════════════════ -// WebAuthn (Playwright virtual authenticator) -// ════════════════════════════════════════════════════════════════════════════ - -test("WebAuthn - registers a virtual passkey", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - // Chrome DevTools Protocol is the current way to add a virtual authenticator - // (Playwright's high-level addVirtualAuthenticator wrapper is not available in - // this version). The RP ID and origin must match packages/auth/.dev.vars: - // WEBAUTHN_RP_ID=localhost / WEBAUTHN_ORIGIN=http://localhost:5173 - cdpSession = await context.newCDPSession(page); - await cdpSession.send("WebAuthn.enable", { enableUI: false }); - await cdpSession.send("WebAuthn.addVirtualAuthenticator", { - options: { - protocol: "ctap2", - transport: "internal", - hasResidentKey: true, - hasUserVerification: true, - isUserVerified: true, - }, - }); - - await page.goto("/settings"); - await page.getByRole("button", { name: "Add security key" }).click(); - await expect(page.getByLabel(/key name/i)).toBeVisible({ timeout: 3000 }); - await page.getByLabel(/key name/i).fill("Playwright Virtual Key"); - // TOTP was disabled above, so the passkey is a first factor too. - await page.locator("#key-enrollment-password").fill(PASSWORD); - - // "Register key" triggers startRegistration() in the browser; the virtual - // authenticator responds automatically. - await page.getByRole("button", { name: "Register key" }).click(); - - // The credential should appear in the key list. - await expect(page.getByText("Playwright Virtual Key")).toBeVisible({ timeout: 10000 }); -}); - -test("WebAuthn - login triggers the passkey ceremony", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - const finish = page.waitForResponse(r => r.url().includes("/api/webauthn/auth/finish") && r.request().method() === "POST"); - await loginWithPassword(page); - - // The server returns webauthn_required and the login page immediately starts - // the WebAuthn ceremony (startAuthentication). The virtual authenticator - // handles it silently, so we land on the dashboard without manual input. - expect((await finish).ok()).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); -}); - -test("WebAuthn - signs in with the passkey alone (no email or password)", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - await page.goto("/login"); - const finish = page.waitForResponse(r => r.url().includes("/api/webauthn/auth/passkey/finish") && r.request().method() === "POST"); - - // Empty allowCredentials: the virtual authenticator answers with the - // discoverable credential registered above, which names the account. - await page.getByRole("button", { name: "Sign in with a passkey" }).click(); - - expect((await finish).ok()).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); -}); - -test("WebAuthn - removes the passkey (requires WebAuthn confirmation)", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await page.goto("/settings"); - - const keyRow = page.locator("li", { hasText: "Playwright Virtual Key" }); - await expect(keyRow).toBeVisible({ timeout: 5000 }); - - // The delete button (Trash2 icon) is the only button inside the key row. - await keyRow.getByRole("button").click(); - - // use2FA fires a WebAuthn ceremony to confirm the deletion; the virtual - // authenticator handles it automatically. - await expect(page.getByText("Playwright Virtual Key")).not.toBeVisible({ timeout: 10000 }); -}); - -test("WebAuthn - login no longer requires a key after removal", async ({ browserName }) => { - test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); - await logout(page); - const login = page.waitForResponse(r => r.url().endsWith("/api/login") && r.request().method() === "POST"); - await loginWithPassword(page); - // webauthn_required comes back as ok: false - the password alone must succeed now. - expect(((await (await login).json()) as { ok: boolean }).ok).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); -}); - -// ── Cleanup: delete account (2FA-protected) ─────────────────────────────────── - -// Re-enable TOTP so the account deletion itself tests the 2FA confirmation gate. -test("re-enables TOTP before account deletion", async () => { - await page.goto("/settings"); - await page.getByRole("button", { name: "Set up authenticator app" }).click(); - - const secretEl = page.locator("code").first(); - await expect(secretEl).toBeVisible({ timeout: 5000 }); - totpSecret = (await secretEl.textContent())?.trim() ?? ""; - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - // The passkey was removed, so this is again the only factor. - await page.locator("#totp-enrollment-password").fill(PASSWORD); - await page.getByRole("button", { name: "Enable 2FA" }).click(); - await expect(page.getByRole("button", { name: "Disable authenticator app" })).toBeVisible({ timeout: 10000 }); -}); - -test("deletes the account - 2FA confirmation required", async () => { - // "Delete account" → confirmation dialog → "Yes, delete my account" - // → runWithTwoFA fires because TOTP is active → "Confirm identity" dialog - await page.getByRole("button", { name: /delete account/i }).click(); - await expect(page.getByRole("alertdialog")).toBeVisible({ timeout: 5000 }); - await page.getByLabel("Current password", { exact: true }).fill(PASSWORD); - await page.getByRole("button", { name: /yes.*delete.*account/i }).click(); - - // use2FA opens the TOTP confirmation dialog. - await expect(page.getByRole("dialog", { name: "Confirm identity" })).toBeVisible({ timeout: 5000 }); - - const code = await computeTOTP(totpSecret); - await fillOTP(page, code); - await page.getByRole("button", { name: "Confirm" }).click(); - - // After successful deletion the app navigates to /login. - await expect(page).toHaveURL(/\/(login|register)/, { timeout: 15000 }); -}); diff --git a/e2e/tests/admin.spec.ts b/e2e/tests/admin.spec.ts index a9d18407..fb4afb96 100644 --- a/e2e/tests/admin.spec.ts +++ b/e2e/tests/admin.spec.ts @@ -1,23 +1,22 @@ /** - * Admin panel e2e smoke: login handoff -> auto-loaded user search -> open a - * details sheet -> audited mutation visible in the audit log. + * Admin panel e2e smoke: sign in -> auto-loaded user search -> open a + * details sheet -> audited action visible in the audit log -> sign out. * * Needs the FULL dev stack (`pnpm dev` at the repo root): docs frontend 5173, - * api 8787, auth 8788, admin worker 8789, and the admin frontend on 5174. - * The whole file self-skips when the admin frontend isn't reachable, so the - * standard suite (which only assumes 5173/8787/8788) is unaffected. + * api 8787, admin worker 8789, and the admin frontend on 5174. The whole file + * self-skips when the admin frontend isn't reachable. * - * Auth: mints a dev admin via the auth worker's quick-login (DEV_QUICK_LOGIN), - * then drives the real handoff flow - POST /api/admin/handoff/start on the - * docs origin, follow redirectTo to the admin /auth/callback, and let the SPA - * exchange the single-use code. This exercises the handoff audit rows - * (admin.handoff.start/exchange) end-to-end. + * Auth: the admin panel signs in through auth.cubityfir.st (its own OIDC + * client). Locally the suite skips the identity service with the admin + * worker's localhost-only POST /api/dev/quick-login, which needs + * `DEV_QUICK_LOGIN=true` and `APP_ORIGIN=http://localhost:5174` in + * packages/admin/.dev.vars. It mints an admin dev user and an admin session. */ import { test, expect, request as pwRequest, type Page } from "@playwright/test"; const ADMIN_ORIGIN = "http://localhost:5174"; -const DOCS_ORIGIN = "http://localhost:5173"; +const RUN_ID = Date.now(); async function adminFrontendUp(): Promise { const ctx = await pwRequest.newContext(); @@ -31,44 +30,17 @@ async function adminFrontendUp(): Promise { } } -// Mint a fresh dev admin account and return its bearer token. -async function mintDevAdminToken(): Promise { - const ctx = await pwRequest.newContext({ baseURL: DOCS_ORIGIN }); - try { - const res = await ctx.post("/api/dev/quick-login", { - data: { variant: "admin-free" }, - }); - expect(res.ok(), "dev quick-login must be enabled locally (DEV_QUICK_LOGIN=true)").toBeTruthy(); - const json = (await res.json()) as { data?: { token?: string }; token?: string }; - const token = json.data?.token ?? json.token; - expect(token, "quick-login response should carry a token").toBeTruthy(); - return token!; - } finally { - await ctx.dispose(); - } -} - -// Drive the real handoff: start it as the signed-in docs user, then let the -// admin SPA consume the code at /auth/callback. -async function signInToAdmin(page: Page, token: string): Promise { - const ctx = await pwRequest.newContext({ baseURL: DOCS_ORIGIN }); - let redirectTo: string; - try { - const res = await ctx.post("/api/admin/handoff/start", { - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - data: { returnTo: `${ADMIN_ORIGIN}/auth/callback` }, - }); - expect(res.ok(), "handoff start should succeed for an admin session").toBeTruthy(); - const json = (await res.json()) as { data: { redirectTo: string } }; - redirectTo = json.data.redirectTo; - } finally { - await ctx.dispose(); - } - - await page.goto(redirectTo); - // The SPA exchanges the code, stores the (sessionStorage) token, and lands - // on the Users dashboard. +// Mints an admin session and hands it to the admin SPA, which keeps it in +// sessionStorage["admin_token"] (src/lib/auth.ts). +async function signInToAdmin(page: Page, email: string): Promise<{ token: string; userId: string }> { + const res = await page.request.post(`${ADMIN_ORIGIN}/api/dev/quick-login`, { data: { email, name: "E2E Admin" } }); + expect(res.ok(), "admin dev quick-login must be enabled locally (DEV_QUICK_LOGIN=true in packages/admin/.dev.vars)").toBeTruthy(); + const { data } = (await res.json()) as { data: { token: string; userId: string } }; + await page.goto(ADMIN_ORIGIN); + await page.evaluate(token => window.sessionStorage.setItem("admin_token", token), data.token); + await page.goto(ADMIN_ORIGIN); await expect(page.getByRole("heading", { name: "Users" })).toBeVisible({ timeout: 15_000 }); + return data; } test.describe("admin panel", () => { @@ -76,37 +48,38 @@ test.describe("admin panel", () => { test.skip(!(await adminFrontendUp()), "admin frontend (5174) is not running - start the full dev stack"); }); - test("handoff login → auto-loaded search → details sheet → audited actions in the log", async ({ page }) => { - const token = await mintDevAdminToken(); - await signInToAdmin(page, token); + test("sign in → auto-loaded search → details sheet → audited action in the log", async ({ page }) => { + const email = `e2e-admin-${RUN_ID}-a@example.com`; + const { userId } = await signInToAdmin(page, email); // AF-U1: the user list auto-loads without a search being submitted, and - // the freshly minted dev admin is newest-first on page 1. - const firstRow = page.locator("table tbody tr").first(); - await expect(firstRow).toBeVisible(); - await expect(page.getByText(/dev-[0-9a-f]+@localhost/).first()).toBeVisible(); + // the freshly minted dev admin is on page 1 (newest first). Address this + // run's row by its email: parallel specs mint users too. + const ownRow = page.locator("table tbody tr", { hasText: email }); + await expect(ownRow).toBeVisible(); - // Expand the newest user's row and open the details sheet. - await firstRow.click(); + // Expand this user's row (the only expanded one) and open the details sheet. + await ownRow.click(); await page.getByRole("button", { name: "User details" }).click(); - await expect(page.getByText("Moderation History")).toBeVisible({ timeout: 10_000 }); - await expect(page.getByText("Profile Badges")).toBeVisible(); + await expect(page.getByText("Profile Badges").first()).toBeVisible({ timeout: 10_000 }); await page.keyboard.press("Escape"); - // The handoff itself must be audited (AB-M2): the exchange that signed - // us in is the newest entry in the audit log. + // An audited action shows up in the audit log. + await page.getByRole("button", { name: "Resync display name" }).first().click(); + await expect(page.getByText(/Display name/).first()).toBeVisible({ timeout: 10_000 }); await page.getByRole("link", { name: "Audit" }).click(); await expect(page.getByRole("heading", { name: "Audit Log" })).toBeVisible(); - await expect(page.getByText("Admin · Handoff · Exchange").first()).toBeVisible({ timeout: 10_000 }); - await expect(page.getByText("Admin · Handoff · Start").first()).toBeVisible(); + // This run's entry: this actor, this target, this action. + const entry = page.locator("table tbody tr", { hasText: `user:${userId}` }) + .filter({ hasText: "User · Name · Resync" }) + .filter({ hasText: email }); + await expect(entry.first()).toBeVisible({ timeout: 10_000 }); }); test("sign out revokes the session server-side (AF-S3)", async ({ page }) => { - const token = await mintDevAdminToken(); - await signInToAdmin(page, token); + await signInToAdmin(page, `e2e-admin-${RUN_ID}-b@example.com`); - // Capture the admin token the SPA is actually using (sessionStorage now, - // not localStorage - AF-S1). + // The SPA keeps the admin token in sessionStorage, never localStorage (AF-S1). const adminToken = await page.evaluate(() => window.sessionStorage.getItem("admin_token")); expect(adminToken).toBeTruthy(); expect(await page.evaluate(() => window.localStorage.getItem("admin_token"))).toBeNull(); @@ -120,9 +93,7 @@ test.describe("admin panel", () => { // A copied token must be dead after sign-out, not valid until its TTL. const ctx = await pwRequest.newContext({ baseURL: ADMIN_ORIGIN }); try { - const res = await ctx.get("/api/verify", { - headers: { Authorization: `Bearer ${adminToken}` }, - }); + const res = await ctx.get("/api/verify", { headers: { Authorization: `Bearer ${adminToken}` } }); expect(res.status()).toBe(401); } finally { await ctx.dispose(); diff --git a/e2e/tests/app.spec.ts b/e2e/tests/app.spec.ts index 4baaa4e6..1159ec98 100644 --- a/e2e/tests/app.spec.ts +++ b/e2e/tests/app.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * The suite registers a fresh account, exercises the UI, then deletes both the * project and the account so it leaves no data behind. @@ -15,17 +15,17 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const EMAIL = `e2e-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Test User"; const PROJECT_NAME = `E2E Project ${RUN_ID}`; const PROJECT_DESCRIPTION = "Created by the Playwright E2E suite"; -// Unique fake IP so each run gets its own rate-limit bucket in the auth worker. +// Unique fake IP so each run gets its own rate-limit bucket in the api worker. const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${RUN_ID % 256}`; // ── Shared state ───────────────────────────────────────────────────────────── @@ -37,28 +37,6 @@ let projectSettingsUrl = ""; // ── Helpers ─────────────────────────────────────────────────────────────────── -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -73,7 +51,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -102,18 +79,7 @@ test.afterAll(async () => { // ── Registration ───────────────────────────────────────────────────────────── test("registers a new account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); }); // ── Dashboard ──────────────────────────────────────────────────────────────── diff --git a/e2e/tests/audio-permission-lock.spec.ts b/e2e/tests/audio-permission-lock.spec.ts index f8da0637..a91f349f 100644 --- a/e2e/tests/audio-permission-lock.spec.ts +++ b/e2e/tests/audio-permission-lock.spec.ts @@ -46,10 +46,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-audiolock-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E AudioLock User"; const PROJECT_A_NAME = `E2E AudioLock Site A ${RUN_ID}`; const PROJECT_B_NAME = `E2E AudioLock Site B ${RUN_ID}`; @@ -78,21 +78,6 @@ let fileAId = ""; let fileBId = ""; let docId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -150,7 +135,7 @@ async function uploadAudio(p: Page, projectId: string, name: string): Promise { for (let attempt = 0; attempt < 2; attempt++) { @@ -224,7 +209,6 @@ test.beforeAll(async ({ browser }) => { if (browser.browserType().name() === "chromium") { await context.grantPermissions(["clipboard-read", "clipboard-write"]); } - await mockTurnstile(context); await injectFakeIp(context); await mockExternalAudio(context); page = await context.newPage(); @@ -243,18 +227,7 @@ test.afterAll(async () => { }); test("registers, creates Site A + Site B, uploads audio to each, and a doc in Site B", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectAId = await createSite(page, PROJECT_A_NAME); fileAId = await uploadAudio(page, projectAId, FILE_A_NAME); diff --git a/e2e/tests/avatar-upload.spec.ts b/e2e/tests/avatar-upload.spec.ts index 9fd2b005..1bb161d6 100644 --- a/e2e/tests/avatar-upload.spec.ts +++ b/e2e/tests/avatar-upload.spec.ts @@ -10,17 +10,17 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars must contain DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 (e2e/signIn.ts devSignIn). */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const EMAIL = `e2e-avatar-${RUN_ID}@example.com`; -const PASSWORD = "AvatarTest-P@ssw0rd!"; const NAME = "Avatar Upload Test User"; // Offset +3 from app.spec to keep this run's rate-limit bucket separate from // other suites that may execute in parallel. @@ -69,23 +69,6 @@ let userId = ""; // ── Helpers ────────────────────────────────────────────────────────────────── -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -100,7 +83,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -113,18 +95,7 @@ test.afterAll(async () => { // ── Setup ──────────────────────────────────────────────────────────────────── test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); }); // ── Upload + verify ────────────────────────────────────────────────────────── diff --git a/e2e/tests/big-doc.spec.ts b/e2e/tests/big-doc.spec.ts index b5e15f09..1afecd60 100644 --- a/e2e/tests/big-doc.spec.ts +++ b/e2e/tests/big-doc.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-bigdoc-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Bigdoc User"; const PROJECT_NAME = `E2E Project Bigdoc ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 8) % 256}`; @@ -26,21 +26,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,7 +36,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -76,18 +60,7 @@ test.afterAll(async () => { }); test("creates a project and uploads a ~200 KB markdown doc", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/change-email.spec.ts b/e2e/tests/change-email.spec.ts deleted file mode 100644 index d247587b..00000000 --- a/e2e/tests/change-email.spec.ts +++ /dev/null @@ -1,176 +0,0 @@ -/** - * E2E tests for changing a user's email address from the settings page. - * - * Covers the flag-off (immediate apply) path only: the `email-verification` - * Flagship flag defaults off and local wrangler dev serves the real dashboard - * flag state. The confirm-first (flag-on) path is covered by the auth - * worker's unit tests. - * - * Prerequisites - run from the monorepo root before starting tests: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * - * A fresh account is registered at the start; globalTeardown wipes - * e2e-%@example.com users (both addresses used here match that pattern). - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-em-${RUN_ID}@example.com`; -const NEW_EMAIL = `e2e-em-${RUN_ID}-new@example.com`; -const PASSWORD = "ChangeEmailP@ssw0rd!"; -const NAME = "Email Change Test User"; -// Offset +4 from the other specs so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 4) % 256}`; - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // Real Turnstile re-runs the challenge on reset() and fires the render - // callback with a fresh token; the mock must replay the callback too. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { - setTimeout(() => verify?.("e2e-bypass-token"), 50); - }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function openChangeEmailDialog(p: Page) { - await p.goto("/settings"); - await p.getByRole("button", { name: "Change email address" }).click(); - await expect(p.getByRole("dialog", { name: "Change email address" })).toBeVisible({ timeout: 5000 }); -} - -const newEmailField = (p: Page) => p.getByLabel("New email address", { exact: true }); -const currentPasswordField = (p: Page) => p.getByLabel("Current password", { exact: true }); -const submitButton = (p: Page) => p.getByRole("button", { name: "Change email", exact: true }); - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. -test.afterAll(async () => { - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ── Change-email dialog ─────────────────────────────────────────────────────── - -test("change email button opens the dialog", async () => { - await openChangeEmailDialog(page); - await expect(newEmailField(page)).toBeVisible(); - await expect(currentPasswordField(page)).toBeVisible(); -}); - -test("submit is disabled while fields are empty", async () => { - // Dialog is still open from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows toast when current password is wrong", async () => { - await newEmailField(page).fill(NEW_EMAIL); - await currentPasswordField(page).fill("wrong-password"); - - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - // Dialog stays open after a failed attempt. - await expect(page.getByRole("dialog", { name: "Change email address" })).toBeVisible(); -}); - -test("successfully changes the email address", async () => { - // Retry on transient drops through the local wrangler chain: a failed PATCH - // leaves the dialog open with the fields intact. Success closes the dialog. - await expect(async () => { - await newEmailField(page).fill(NEW_EMAIL); - await currentPasswordField(page).fill(PASSWORD); - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - await expect(page.getByRole("dialog", { name: "Change email address" })).not.toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await expect(page.getByText("Email address updated", { exact: true })).toBeVisible({ timeout: 5000 }); - // The settings page now shows the new address in the (disabled) email field. - await expect(page.locator("#email")).toHaveValue(NEW_EMAIL); -}); - -// ── Verify the new email works for login ────────────────────────────────────── - -test("old email no longer logs in", async () => { - await logout(page); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - // Auth rejected. The page is already on /login, so wait for the error itself. - await expect(page.getByText("Invalid email or password.")).toBeVisible({ timeout: 8000 }); -}); - -test("new email logs in successfully", async () => { - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(NEW_EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); diff --git a/e2e/tests/change-password.spec.ts b/e2e/tests/change-password.spec.ts deleted file mode 100644 index 81030313..00000000 --- a/e2e/tests/change-password.spec.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * E2E tests for changing a user's password from the settings page. - * - * Prerequisites - run from the monorepo root before starting tests: - * pnpm dev - * - * packages/auth/.dev.vars must contain: - * TURNSTILE_SECRET=1x0000000000000000000000000000000AA - * - * A fresh account is registered at the start and deleted in afterAll so no - * data is left behind even if tests fail mid-way. - */ - -import { test, expect, type BrowserContext, type Page } from "@playwright/test"; - -// ── Unique-per-run values ──────────────────────────────────────────────────── - -const RUN_ID = Date.now(); -const EMAIL = `e2e-pw-${RUN_ID}@example.com`; -const PASSWORD = "OriginalP@ssw0rd!"; -const NEW_PASSWORD = "UpdatedP@ssw0rd!"; -const NAME = "Password Change Test User"; -// Offset +2 from app.spec so parallel runs don't share a rate-limit bucket. -const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 2) % 256}`; - -// ── Shared context ──────────────────────────────────────────────────────────── - -let context: BrowserContext; -let page: Page; - -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - // Real Turnstile re-runs the challenge on reset() and fires the render - // callback with a fresh token. The login form relies on that after a - // failed submit (submit stays disabled until a new token arrives), so the - // mock must replay the callback too - a no-op reset() dead-ends the form. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - verify = options.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { - setTimeout(() => verify?.("e2e-bypass-token"), 50); - }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - -async function injectFakeIp(ctx: BrowserContext) { - await ctx.route("**/api/**", async (route) => { - await route.continue({ - headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP }, - }); - }); -} - -async function logout(p: Page) { - await p.goto("/login?logout=1"); - await expect(p).toHaveURL(/\/login/, { timeout: 5000 }); -} - -async function openChangePasswordDialog(p: Page) { - await p.goto("/settings"); - await p.getByRole("button", { name: "Change password" }).click(); - await expect(p.getByRole("dialog", { name: "Change password" })).toBeVisible({ timeout: 5000 }); -} - -// Helpers scoped to the dialog to avoid label-substring ambiguity. -// "New password" is a substring of "Confirm new password", so exact is required. -const currentPasswordField = (p: Page) => p.getByLabel("Current password", { exact: true }); -const newPasswordField = (p: Page) => p.getByLabel("New password", { exact: true }); -const confirmPasswordField = (p: Page) => p.getByLabel("Confirm new password", { exact: true }); -const submitButton = (p: Page) => p.getByRole("button", { name: "Change password", exact: true }).last(); - -// ── Lifecycle ───────────────────────────────────────────────────────────────── - -test.describe.configure({ mode: "serial" }); - -test.beforeAll(async ({ browser }) => { - context = await browser.newContext(); - await mockTurnstile(context); - await injectFakeIp(context); - page = await context.newPage(); -}); - -// Account cleanup runs in globalTeardown. -test.afterAll(async () => { - await context.close(); -}); - -// ── Setup ───────────────────────────────────────────────────────────────────── - -test("registers a fresh account", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// ── Change-password dialog ──────────────────────────────────────────────────── - -test("change password button opens the dialog", async () => { - await openChangePasswordDialog(page); - await expect(currentPasswordField(page)).toBeVisible(); - await expect(newPasswordField(page)).toBeVisible(); - await expect(confirmPasswordField(page)).toBeVisible(); -}); - -test("submit is disabled while fields are empty", async () => { - // Dialog is still open from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows inline error when new password is too weak", async () => { - await newPasswordField(page).fill("weak"); - // Strength meter renders a "Very weak" / "Weak" label below the field for low-score passwords. - await expect(page.getByText(/^(Very weak|Weak)$/)).toBeVisible(); -}); - -test("shows inline error when confirm does not match", async () => { - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill("different-value"); - await expect(page.getByText("Passwords do not match.")).toBeVisible(); -}); - -test("submit is disabled when passwords do not match", async () => { - // New password is strong but confirm is still mismatched from the previous test. - await expect(submitButton(page)).toBeDisabled(); -}); - -test("shows toast when current password is wrong", async () => { - await currentPasswordField(page).fill("wrong-password"); - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill(NEW_PASSWORD); - - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - - await expect(page.getByText("Current password is incorrect", { exact: true })).toBeVisible({ timeout: 8000 }); - // Dialog stays open after a failed attempt. - await expect(page.getByRole("dialog", { name: "Change password" })).toBeVisible(); -}); - -test("successfully changes the password", async () => { - // Retry on transient drops through the local wrangler chain: a failed PATCH - // leaves the dialog open with the fields intact, so re-submitting is safe. - // Success closes the dialog. - await expect(async () => { - await currentPasswordField(page).fill(PASSWORD); - await newPasswordField(page).fill(NEW_PASSWORD); - await confirmPasswordField(page).fill(NEW_PASSWORD); - await expect(submitButton(page)).toBeEnabled({ timeout: 3000 }); - await submitButton(page).click(); - await expect(page.getByRole("dialog", { name: "Change password" })).not.toBeVisible({ timeout: 8000 }); - }).toPass({ timeout: 30000 }); - await expect(page.getByText("Password changed", { exact: true })).toBeVisible({ timeout: 5000 }); -}); - -// ── Verify new password works ───────────────────────────────────────────────── - -test("old password no longer works", async () => { - await logout(page); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - // Auth rejected. The page is already on /login, so wait for the error itself. - await expect(page.getByText("Invalid email or password.")).toBeVisible({ timeout: 8000 }); -}); - -test("new password logs in successfully", async () => { - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(NEW_PASSWORD); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); -}); - -// Account cleanup runs in globalTeardown (e2e/global-teardown.ts). -// The 2FA-gated delete path is covered by 2fa.spec.ts. diff --git a/e2e/tests/collab.spec.ts b/e2e/tests/collab.spec.ts index 04e746c7..f40958ba 100644 --- a/e2e/tests/collab.spec.ts +++ b/e2e/tests/collab.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Covers: * 1. Two pages on the same doc see each other's edits within the editor @@ -25,10 +25,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-collab-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Collab User"; // Prefix matches the "E2E Project %" pattern in global-teardown, so the // safety-net cleanup catches this project even if afterAll never runs. @@ -43,23 +43,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -86,7 +69,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); pageA = await context.newPage(); }); @@ -115,18 +97,7 @@ test.afterAll(async () => { test("sets up a project + doc with the realtime flag enabled", async () => { // Register - await pageA.goto("/register"); - await pageA.getByLabel("Name").fill(NAME); - await pageA.getByLabel("Email").fill(EMAIL); - await pageA.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(pageA.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await pageA.getByRole("button", { name: "Create account" }).click(); - await expect(pageA).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(pageA, { email: EMAIL, name: NAME }); // Create project await pageA.goto("/dashboard"); diff --git a/e2e/tests/excalidraw.spec.ts b/e2e/tests/excalidraw.spec.ts index e94834bf..0a4e829e 100644 --- a/e2e/tests/excalidraw.spec.ts +++ b/e2e/tests/excalidraw.spec.ts @@ -20,10 +20,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-excalidraw-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Excalidraw User"; const PROJECT_NAME = `E2E Excalidraw Site ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 37) % 256}`; @@ -33,21 +33,6 @@ let page: Page; let projectId = ""; let fileId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -100,7 +85,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -111,18 +95,7 @@ test.afterAll(async () => { }); test("registers and creates a site", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectId = await createSite(page, PROJECT_NAME); expect(projectId).toBeTruthy(); diff --git a/e2e/tests/export.spec.ts b/e2e/tests/export.spec.ts index c8937ec4..48bcf557 100644 --- a/e2e/tests/export.spec.ts +++ b/e2e/tests/export.spec.ts @@ -13,10 +13,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { readFile } from "node:fs/promises"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-exp-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Export User"; const PROJECT_NAME = `E2E Project Export ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 11) % 256}`; @@ -26,21 +26,6 @@ let page: Page; let projectId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,7 +36,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -76,18 +60,7 @@ test.afterAll(async () => { }); test("sets up a project with two docs (root + folder)", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/file-permission-lock.spec.ts b/e2e/tests/file-permission-lock.spec.ts index a199c2da..63832016 100644 --- a/e2e/tests/file-permission-lock.spec.ts +++ b/e2e/tests/file-permission-lock.spec.ts @@ -37,10 +37,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-filelock-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E FileLock User"; const PROJECT_A_NAME = `E2E FileLock Site A ${RUN_ID}`; const PROJECT_B_NAME = `E2E FileLock Site B ${RUN_ID}`; @@ -68,21 +68,6 @@ let fileAId = ""; let fileBId = ""; let docId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -140,7 +125,7 @@ async function uploadImage(p: Page, projectId: string, name: string): Promise { for (let attempt = 0; attempt < 2; attempt++) { @@ -214,7 +199,6 @@ test.beforeAll(async ({ browser }) => { if (isChromium) { await context.grantPermissions(["clipboard-read", "clipboard-write"]); } - await mockTurnstile(context); await injectFakeIp(context); await mockExternalImage(context); page = await context.newPage(); @@ -233,18 +217,7 @@ test.afterAll(async () => { }); test("registers, creates Site A + Site B, uploads an image to each, and a doc in Site B", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); projectAId = await createSite(page, PROJECT_A_NAME); fileAId = await uploadImage(page, projectAId, FILE_A_NAME); diff --git a/e2e/tests/file-settings.spec.ts b/e2e/tests/file-settings.spec.ts index bc1e3787..6c29f112 100644 --- a/e2e/tests/file-settings.spec.ts +++ b/e2e/tests/file-settings.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-docset-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E DocSettings User"; const PROJECT_NAME = `E2E Project DocSettings ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 12) % 256}`; @@ -26,21 +26,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -49,7 +34,7 @@ async function injectFakeIp(ctx: BrowserContext) { async function putDoc(p: Page, id: string, title: string, content: string) { // Local wrangler dev intermittently drops requests through the - // browser → vite → API worker → auth worker chain (per playwright.config.ts). + // browser → vite → API worker chain (per playwright.config.ts). // Retry once on 500 so transient infra hiccups don't cause spurious failures. const result = await p.evaluate(async ({ id, title, content }) => { for (let attempt = 0; attempt < 2; attempt++) { @@ -87,7 +72,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -112,18 +96,7 @@ test.afterAll(async () => { }); test("sets up a project + doc", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/image-paste.spec.ts b/e2e/tests/image-paste.spec.ts index cf8a57e4..12c702d5 100644 --- a/e2e/tests/image-paste.spec.ts +++ b/e2e/tests/image-paste.spec.ts @@ -12,10 +12,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-paste-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Paste User"; const PROJECT_NAME = `E2E Project Paste ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 7) % 256}`; @@ -29,21 +29,6 @@ let context: BrowserContext; let page: Page; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -54,7 +39,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -86,18 +70,7 @@ test("pastes a PNG into the editor, uploads to /api/files, inserts markdown, and test.skip(browserName === "firefox", "synthetic clipboard File payloads not supported in Firefox"); // Register + project + doc. - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/ink-features.spec.ts b/e2e/tests/ink-features.spec.ts index 75baee6d..be053f66 100644 --- a/e2e/tests/ink-features.spec.ts +++ b/e2e/tests/ink-features.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Strategy: the Ink section of /settings only renders when the user's plan * resolves to "ink". Two ways to get there in dev: @@ -21,10 +21,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-ink-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Ink User"; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 13) % 256}`; @@ -32,21 +32,6 @@ let context: BrowserContext; let page: Page; let userId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -55,14 +40,13 @@ async function injectFakeIp(ctx: BrowserContext) { function grantInk(uid: string) { const sql = `INSERT INTO user_billing (user_id, granted_plan, granted_plan_started_at) VALUES ('${uid}', 'ink', ${Date.now()}) ON CONFLICT(user_id) DO UPDATE SET granted_plan = 'ink', granted_plan_started_at = ${Date.now()};`; - d1Local("auth", sql); + d1Local("main", sql); } test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -72,18 +56,7 @@ test.afterAll(async () => { }); test("registers a fresh account and grants Annex Ink via the auth DB", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); // Grab the user id so we can write a granted_plan row keyed to it. userId = await page.evaluate(async () => { diff --git a/e2e/tests/invites.spec.ts b/e2e/tests/invites.spec.ts index 23e2809a..3ea93d0e 100644 --- a/e2e/tests/invites.spec.ts +++ b/e2e/tests/invites.spec.ts @@ -3,21 +3,22 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true + APP_ORIGIN=http://localhost:5173 (devSignIn) * * Three accounts are created: owner, email-invitee, link-invitee. * The project and all three accounts are deleted in afterAll even on failure. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── const RUN_ID = Date.now(); const PROJECT_NAME = `Invite Test ${RUN_ID}`; -const OWNER = { name: "Invite Owner", email: `e2e-inv-owner-${RUN_ID}@example.com`, password: "OwnerP@ssw0rd!" }; -const EMAIL_USER = { name: "Email Invitee", email: `e2e-inv-email-${RUN_ID}@example.com`, password: "InviteeP@ssw0rd!" }; +const OWNER = { name: "Invite Owner", email: `e2e-inv-owner-${RUN_ID}@example.com` }; +const EMAIL_USER = { name: "Email Invitee", email: `e2e-inv-email-${RUN_ID}@example.com` }; const LINK_USER = { name: "Link Invitee", email: `e2e-inv-link-${RUN_ID}@example.com`, password: "LinkP@ssw0rd!" }; // Offsets +3/+4/+5 keep each account in its own rate-limit bucket, @@ -39,25 +40,6 @@ let inviteLinkToken = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - verify = opts.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); @@ -65,32 +47,13 @@ async function setupContext(browser: Browser, ip: string): Promise<[BrowserConte } async function register(page: Page, user: typeof OWNER) { - await page.goto("/register"); - await page.getByLabel("Name").fill(user.name); - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } +// The same email always signs the same dev user back in (replacing any +// session this page had). async function login(page: Page, user: typeof OWNER) { - // /login?logout=1 clears any existing token first so this is always reliable. - await page.goto("/login?logout=1"); - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/limited-permissions.spec.ts b/e2e/tests/limited-permissions.spec.ts index b7a03810..2bd3eb0b 100644 --- a/e2e/tests/limited-permissions.spec.ts +++ b/e2e/tests/limited-permissions.spec.ts @@ -10,13 +10,14 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: TURNSTILE_SECRET=1x0000000000000000000000000000000AA + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true + APP_ORIGIN=http://localhost:5173 (devSignIn) * * Two accounts are created: owner, limited. Both accounts and the project * are cleaned up in afterAll / globalTeardown even on failure. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── @@ -26,7 +27,7 @@ const DOC_TITLE = "Limited Access Doc"; // A distinct phrase so we can assert the rendered body is what the owner wrote. const DOC_CONTENT_PHRASE = "Limited share content sentinel."; -const OWNER = { name: "Limited Perm Owner", email: `e2e-limited-owner-${RUN_ID}@example.com`, password: "OwnerP@ssw0rd!" }; +const OWNER = { name: "Limited Perm Owner", email: `e2e-limited-owner-${RUN_ID}@example.com` }; const LIMITED = { name: "Limited Perm User", email: `e2e-limited-user-${RUN_ID}@example.com`, password: "LimitedP@ssw0rd!" }; // Offsets +6/+7 keep these accounts in their own rate-limit buckets, separate @@ -47,25 +48,6 @@ let docId = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - // reset() must replay the callback like real Turnstile does - the login - // form clears its token after a failed submit and stays disabled until a - // fresh one arrives. - let verify: ((t: string) => void) | null = null; - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - verify = opts.callback; - setTimeout(() => verify?.("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() { setTimeout(() => verify?.("e2e-bypass-token"), 50); }, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); @@ -73,32 +55,13 @@ async function setupContext(browser: Browser, ip: string): Promise<[BrowserConte } async function register(page: Page, user: typeof OWNER) { - await page.goto("/register"); - await page.getByLabel("Name").fill(user.name); - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } +// The same email always signs the same dev user back in (replacing any +// session this page had). async function login(page: Page, user: typeof OWNER) { - // /login?logout=1 clears any existing token first so this is always reliable. - await page.goto("/login?logout=1"); - // Retry the whole attempt: the local wrangler chain can drop the login POST - // under full-suite load, which surfaces an error and re-arms the form. - await expect(async () => { - await page.getByLabel("Email").fill(user.email); - await page.getByLabel("Password").fill(user.password); - await expect(page.getByRole("button", { name: "Sign in" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page).not.toHaveURL(/\/login/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: user.email, name: user.name }); } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/markdown.spec.ts b/e2e/tests/markdown.spec.ts index 6b7273e0..41f77db8 100644 --- a/e2e/tests/markdown.spec.ts +++ b/e2e/tests/markdown.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Strategy: instead of typing each markdown element through the editor (which * is slow and surfaces typing-time autocomplete behaviours, not rendering), @@ -16,10 +16,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-md-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Markdown User"; const PROJECT_NAME = `E2E Project Markdown ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 6) % 256}`; @@ -31,22 +31,6 @@ let docId = ""; let linkedDocId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -81,7 +65,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -106,18 +89,7 @@ test.afterAll(async () => { }); test("sets up an account, project, and two docs (one as wikilink target)", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/orgs.spec.ts b/e2e/tests/orgs.spec.ts index 1f6d980b..c4f0f9f3 100644 --- a/e2e/tests/orgs.spec.ts +++ b/e2e/tests/orgs.spec.ts @@ -5,15 +5,14 @@ * * Prerequisites: * pnpm dev (from the monorepo root) - * packages/auth/.dev.vars: DEV_QUICK_LOGIN=true (+ APP_ORIGIN=http://localhost:5173) + * packages/api/.dev.vars: DEV_QUICK_LOGIN=true (+ APP_ORIGIN=http://localhost:5173) * - * Accounts are created via the dev quick-login panel on /login (the project's - * credential-free localhost dev shortcut) rather than the register form, so the - * suite is independent of the Flagship "signup" flag. Both accounts are removed - * in globalTeardown; the site is deleted by the test body / afterAll. + * Accounts are created with e2e/signIn.ts (devSignIn, the localhost-only dev + * quick login). Both accounts are removed in globalTeardown; the site is deleted by the test body / afterAll. */ import { test, expect, type Browser, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; // ── Unique-per-run values ──────────────────────────────────────────────────── @@ -39,42 +38,18 @@ let siteId = ""; async function setupContext(browser: Browser, ip: string): Promise<[BrowserContext, Page]> { const ctx = await browser.newContext(); - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); }); return [ctx, await ctx.newPage()]; } -// Logs in via the DEV-only quick-login panel and returns the freshly-minted dev -// user's email (decoded from the returned JWT — quick-login creates a random -// dev-@localhost account each time). +// Signs in a fresh dev user (localhost-only quick login) and returns its email. +let devUsers = 0; async function devLogin(page: Page): Promise { - await page.goto("/login?logout=1"); - const respPromise = page.waitForResponse( - r => r.url().includes("/api/dev/quick-login") && r.request().method() === "POST", - ); - // First "Free" button is the Standard (non-admin) row. - await page.getByRole("button", { name: "Free", exact: true }).first().click(); - const resp = await respPromise; - const body = await resp.json() as { ok: boolean; data: { token: string } }; - expect(body.ok).toBe(true); - await expect(page).not.toHaveURL(/\/login/, { timeout: 10000 }); - const payload = JSON.parse(Buffer.from(body.data.token.split(".")[1], "base64").toString()) as { email: string }; - return payload.email; + const email = `e2e-org-${RUN_ID}-${++devUsers}@example.com`; + await devSignIn(page, { email, name: `Org User ${devUsers}` }); + return email; } // ── Lifecycle ───────────────────────────────────────────────────────────────── diff --git a/e2e/tests/profile-card.spec.ts b/e2e/tests/profile-card.spec.ts index 6e407cd2..f06768b6 100644 --- a/e2e/tests/profile-card.spec.ts +++ b/e2e/tests/profile-card.spec.ts @@ -17,10 +17,10 @@ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; import { d1Local } from "../d1Local"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-prof-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Profile User"; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 14) % 256}`; @@ -28,21 +28,6 @@ let context: BrowserContext; let page: Page; let userId = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": FAKE_IP } }); @@ -51,14 +36,13 @@ async function injectFakeIp(ctx: BrowserContext) { function grantInk(uid: string) { const sql = `INSERT INTO user_billing (user_id, granted_plan, granted_plan_started_at) VALUES ('${uid}', 'ink', ${Date.now()}) ON CONFLICT(user_id) DO UPDATE SET granted_plan = 'ink', granted_plan_started_at = ${Date.now()};`; - d1Local("auth", sql); + d1Local("main", sql); } test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -68,22 +52,11 @@ test.afterAll(async () => { }); test("registers, grants Ink, and writes a bio + timezone", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); - // Right after register the token is in localStorage but the auth worker's + // Right after sign-in the token is in localStorage but the // session row may still be propagating; retry a few times so we don't race - // on the auth/api worker handshake. + // on the api worker. userId = await page.evaluate(async () => { for (let i = 0; i < 5; i++) { const token = localStorage.getItem("token"); diff --git a/e2e/tests/publishing.spec.ts b/e2e/tests/publishing.spec.ts index 57127c5d..2cacc94b 100644 --- a/e2e/tests/publishing.spec.ts +++ b/e2e/tests/publishing.spec.ts @@ -13,10 +13,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-pub-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Publish User"; const PROJECT_NAME = `E2E Project Publish ${RUN_ID}`; const FAKE_IP = `10.${Math.floor(RUN_ID / 1e10) % 256}.${Math.floor(RUN_ID / 1e7) % 256}.${(RUN_ID + 9) % 256}`; @@ -29,21 +29,6 @@ let projectId = ""; let docId = ""; let projectSettingsUrl = ""; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_c: unknown, opts: { callback: (t: string) => void }) { - setTimeout(() => opts.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, remove() {}, - }, - writable: true, configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext, ip: string) { await ctx.route("**/api/**", async (route) => { await route.continue({ headers: { ...route.request().headers(), "CF-Connecting-IP": ip } }); @@ -54,7 +39,6 @@ test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ browser }) => { context = await browser.newContext(); - await mockTurnstile(context); await injectFakeIp(context, FAKE_IP); page = await context.newPage(); }); @@ -80,18 +64,7 @@ test.afterAll(async () => { }); test("creates a project + doc and publishes the site", async () => { - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); await page.goto("/dashboard"); await page.getByText("New site").click(); diff --git a/e2e/tests/scroll-to-heading.spec.ts b/e2e/tests/scroll-to-heading.spec.ts index cedc0457..f98149f3 100644 --- a/e2e/tests/scroll-to-heading.spec.ts +++ b/e2e/tests/scroll-to-heading.spec.ts @@ -4,8 +4,8 @@ * Prerequisites - run from the monorepo root before starting tests: * pnpm dev * - * Also set TURNSTILE_SECRET=1x0000000000000000000000000000000AA in - * packages/auth/.dev.vars (Cloudflare's always-pass test secret). + * Signs in with e2e/signIn.ts (devSignIn): needs DEV_QUICK_LOGIN=true and + * APP_ORIGIN=http://localhost:5173 in packages/api/.dev.vars. * * Covers two flows on the published-doc page: * 1. Loading /s//# scrolls the article viewport @@ -22,10 +22,10 @@ */ import { test, expect, type BrowserContext, type Page } from "@playwright/test"; +import { devSignIn } from "../signIn"; const RUN_ID = Date.now(); const EMAIL = `e2e-scroll-${RUN_ID}@example.com`; -const PASSWORD = "E2eTest-P@ssw0rd!"; const NAME = "E2E Scroll User"; const PROJECT_NAME = `E2E Scroll ${RUN_ID}`; @@ -47,23 +47,6 @@ let appDocUrl = ""; const PUBLIC_SCROLLER = ".public-doc-scroller [data-radix-scroll-area-viewport]"; const APP_SCROLLER = ".app-main-scroller"; -async function mockTurnstile(ctx: BrowserContext) { - await ctx.addInitScript(() => { - Object.defineProperty(window, "turnstile", { - value: { - render(_container: unknown, options: { callback: (t: string) => void }) { - setTimeout(() => options.callback("e2e-bypass-token"), 50); - return "mock-widget-id"; - }, - reset() {}, - remove() {}, - }, - writable: true, - configurable: true, - }); - }); -} - async function injectFakeIp(ctx: BrowserContext) { await ctx.route("**/api/**", async (route) => { await route.continue({ @@ -115,7 +98,6 @@ test.beforeAll(async ({ browser }) => { // Outline rail only renders at the xl breakpoint (1280px+). 1440 gives it // plenty of room and matches a common laptop width. context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); - await mockTurnstile(context); await injectFakeIp(context); page = await context.newPage(); }); @@ -141,18 +123,7 @@ test.afterAll(async () => { test("sets up a published doc with multiple headings", async () => { // Register - await page.goto("/register"); - await page.getByLabel("Name").fill(NAME); - await page.getByLabel("Email").fill(EMAIL); - await page.getByLabel("Password").fill(PASSWORD); - // Retry the whole submit: the local wrangler chain can drop the register - // POST under full-suite load; the form keeps its Turnstile token, so - // re-clicking is safe. - await expect(async () => { - await expect(page.getByRole("button", { name: "Create account" })).toBeEnabled({ timeout: 5000 }); - await page.getByRole("button", { name: "Create account" }).click(); - await expect(page).not.toHaveURL(/\/register/, { timeout: 8000 }); - }).toPass({ timeout: 30000 }); + await devSignIn(page, { email: EMAIL, name: NAME }); // Create project await page.goto("/dashboard"); diff --git a/memories/Api-Keys.md b/memories/Api-Keys.md index 6b04eff5..8bff2a76 100644 --- a/memories/Api-Keys.md +++ b/memories/Api-Keys.md @@ -22,10 +22,9 @@ index = lookup index), `key_prefix` (display only), `scope` (`read|readwrite` CHECK), `can_invite` (0/1), `created_at`, `last_used_at`, `expires_at`, `revoked_at`. -**Why the API DB, not auth DB:** keys are project-scoped (real FK + cascade), and -management is a plain API-worker write - keeping them out of the read-only -`AUTH_DB` avoids a new auth-worker write path and the 3-package redeploy coupling -that auth-table schema changes carry. The owner is just a stored user id. +**Why the API DB:** keys are project-scoped (real FK + cascade), and management is +a plain API-worker write. The owner is just a stored user id (= the users +mirror id / OIDC `sub`). ## Security model - the load-bearing invariants @@ -40,8 +39,9 @@ that auth-table schema changes carry. The owner is just a stored user id. **live** `project_members` role (accepted only). A `readwrite` key still needs the owner to be editor+; a `can_invite` key still needs admin+. Removing the owner from the site **instantly neuters all their keys**. `authenticateApiKey` - also reads the owner's `users` row via `AUTH_DB`: a deleted, disabled, - suspended, or force-password-change account's keys 401, same as its JWTs. + also checks the owner's users-mirror row and live standing (identity + service, cached ~60s): a deleted, disabled or suspended account - or one + blocked by a pending admin deletion - gets 401, same as its sessions. 3. **Token discrimination.** Keys are prefixed `annx_`; JWTs are 3 dot-separated segments and never carry the prefix. `isApiKeyToken()` separates them. 4. **Hashing.** Store only `SHA-256(secret)` (fast hash is correct for diff --git a/memories/Collab.md b/memories/Collab.md index 9689848b..3c703a8b 100644 --- a/memories/Collab.md +++ b/memories/Collab.md @@ -20,7 +20,7 @@ Browser ↔ WebSocket `/api/docs/:id/collab?token=` ↔ API Worker (auth + ## WebSocket auth -Token passed as `?token=` (browsers can't set headers on WS); API worker re-wraps it as `Authorization: Bearer` and calls `authenticate()`, which verifies inline against `AUTH_DB` (see CLAUDE.md "Verification boundary"). +Token passed as `?token=` (browsers can't set headers on WS); API worker re-wraps it as `Authorization: Bearer` and calls `authenticate()`, which verifies the Annex session inline against cubedocs-main (see CLAUDE.md "Auth"). Live sockets are re-checked periodically (`revalidateAccess`): session row, admin-deletion block, and identity standing. The API worker hands identity to the DO via `X-User-Id` / `X-User-Name` (URI-encoded) / `X-Project-Id` / `X-Doc-Id` / `X-Session-Id`, always set with `Headers.set` so a client can't smuggle its own copies (a record spread of `request.headers` would *append* them). Sockets are authorized once at upgrade, so `DocCollabRoom.revalidateAccess` (throttled to `AUTH_RECHECK_MS`, driven by traffic) re-checks both effective role (editor+) and the socket's auth session (`sessionStillValid`: revoked / expired / force-password-change / disabled / suspended) and closes failures with 1008. Lookup errors fail open. diff --git a/memories/Identity-Client.md b/memories/Identity-Client.md new file mode 100644 index 00000000..75c35b49 --- /dev/null +++ b/memories/Identity-Client.md @@ -0,0 +1,148 @@ +# Identity: Annex as a client of auth.cubityfir.st + +Accounts live on the standalone identity service at **https://auth.cubityfir.st** +(worker `cubityfirst-auth`, its own repo and D1 `cubityfirst-auth`). It does +registration, sign-in (password, TOTP, passkeys with RP ID `cubityfir.st`), +email changes, sessions on its side, moderation (disable/suspend), the admin +role, account deletion, and OAuth client management (`/admin/clients`). Annex is +an OpenID Connect client like any other service. Annex keeps its own sessions, +a users mirror, and everything Annex-specific (Ink billing, preferences, +handles, badges, sites). + +## Bindings (api + admin workers) + +| Binding | Target | Used for | +| --- | --- | --- | +| `IDENTITY` | `cubityfirst-auth`, entrypoint `IdentityService` | `getUser` (standing, ~60s cache), `findUserByEmail` (invites), `listDeletedUsers` (deletion sync) | +| `IDENTITY_OIDC` | `cubityfirst-auth` default export | discovery, JWKS, token: **every server-side OIDC request** | + +Annex's workers share the cubityfir.st zone with auth.cubityfir.st. A Worker's +`fetch()` to another Worker's hostname on the same zone goes to the origin (a +placeholder record), not to that Worker, so server-side OIDC requests must use +`IDENTITY_OIDC` (`identityFetch` in `packages/api/src/account/oidc.ts`). Only +the browser redirects (authorize, logout) use the public URL. Requests over a +binding carry no `CF-Connecting-IP`, so the provider rate-limits them per +client_id (100/min for token, again for userinfo) - fine at current volume. + +Post-logout URIs are matched byte for byte: they're registered as the bare +origin (no trailing slash), which is the default `APP_ORIGIN` sends. + +Vars: `OIDC_ISSUER`, `OIDC_CLIENT_ID` (docs: `oidc_7369d6d5736d2bea35f1ab47`; +admin: `oidc_07c81f4a5aa63dd2bd0b15cc`), `APP_ORIGIN`; optional `OIDC_REDIRECT_URI`, +`OIDC_POST_LOGOUT_REDIRECT_URI`. Secret: `OIDC_CLIENT_SECRET`. + +## Registering the clients (auth.cubityfir.st/admin/clients) + +| Client | Redirect URI | Post-logout URI | Scopes | First-party | +| --- | --- | --- | --- | --- | +| docs app (`oidc_7369d6d5736d2bea35f1ab47`) | `https://docs.cubityfir.st/api/auth/callback` | `https://docs.cubityfir.st` | `openid profile email roles` | yes | +| admin panel (`oidc_07c81f4a5aa63dd2bd0b15cc`) | `https://admin.cubityfir.st/api/auth/callback` | `https://admin.cubityfir.st` | `openid profile email roles` | yes | + +Local dev clients: `http://localhost:5173/api/auth/callback` (docs) and +`http://localhost:5174/api/auth/callback` (admin), against a local identity +worker on :8790. + +## Flow (packages/api/src/routes/auth.ts, shared by admin via AuthFlow) + +1. `GET /api/auth/login?return_to=` - PKCE S256 verifier, state, nonce sealed + (HMAC with `JWT_SECRET`) into the HttpOnly `annex_oidc_` cookie (one + per sign-in, so two tabs don't clobber each other; path `/api/auth`, 10 min); 302 to the authorize endpoint from discovery. +2. `GET /api/auth/callback` - opens the cookie, `validateAuthResponse` (state, + `iss`), code exchange with `client_secret_basic`, + `processAuthorizationCodeResponse` (iss, aud, exp, nonce, RS256 pinned) and + `validateApplicationLevelSignature` (JWKS). Refuses ids in + `identity_deletions` (`account_deleted`) or `user_deletions` + (`account_disabled`), and non-admins for the admin client (`not_admin`). + Upserts the users mirror (+ member snapshots; every mirror write that + changes the email also updates the Stripe customer's, `refreshMirror`) and creates a session row with a single-use `handoff_hash`. +3. Sets the handoff code as the HttpOnly, SameSite=Strict + `annex_handoff_` cookie (60s; never in a URL, so a leaked/crafted + completion link signs no one in; one cookie per sign-in, so two finishing + at once in one browser don't swap) and 302s to + `/auth/complete#status=ok&attempt=&return_to=…` (or + `#error=`). +4. SPA `POST /api/auth/exchange?attempt=` (no body; the browser sends the cookie) - + redeems it once for the HS256 session JWT. The docs app keeps it in localStorage, the admin panel + in sessionStorage. +5. `POST /api/auth/logout` - revokes the session, returns the end-session URL + with `id_token_hint` + `post_logout_redirect_uri`. + +`loadCurrentSession(token, env, kind)` (`account/session.ts`) re-derives +everything per request; standing comes from `IDENTITY.getUser` (cache ~60s, +mirror fallback when unreachable). `kind` (`app`/`admin`) keeps docs and admin +tokens apart. Tokens last 1h on the provider and there are no refresh tokens; +Annex sessions last 7 days (admin 12h) independently. + +Local dev without the identity worker: `DEV_QUICK_LOGIN=true` + +`APP_ORIGIN=http://localhost:5173` enables `POST /api/dev/quick-login` (dev +users have ids `dev-…`; standing checks skip the RPC for them). + +## Deletion + +- **Identity deletion** (user deletes their account on auth.cubityfir.st, or + an operator does there): hourly api cron `23 * * * *` + (`lib/identityDeletions.ts`) records it in `identity_deletions`, deletes the + Stripe customer, memberships, API keys, shares, favourites, avatars and the + users mirror row. **Owned sites/orgs are kept** and shown on the admin + Projects page ("Owner account deleted") for an operator to resolve. +- **Admin-scheduled deletion** (Annex admin Users page): deletes Annex data + only after 7 days; the person stays blocked from Annex; the operator then + deletes the account on auth.cubityfir.st, and the sync finishes the rest. + +## Cutover (the user runs these; never automatic) + +The identity service went live 2026-11-18 (~16:33 UTC) with a fresh import of +cubedocs-auth and a new signing key. Until this branch ships, annex-auth still +serves Annex logins and **account changes drift** between the two stores. + +1. Ship `chore(auth): retire annex-auth's OIDC provider` before/with any + annex-auth deploy (removes the `auth.cubityfir.st` routes). +2. Register the two clients above on auth.cubityfir.st, **disabled** (they + stay disabled until step 7, so nobody can sign in to Annex before + reconciliation); set + `OIDC_CLIENT_SECRET` on annex-api and annex-admin (`npx wrangler secret put + OIDC_CLIENT_SECRET --name annex-api` / `--name annex-admin`), move + `STRIPE_SECRET_KEY` + `STRIPE_WEBHOOK_SECRET` to annex-api, and fix + `OIDC_CLIENT_ID` in the configs if the registered ids differ. +3. Apply api migration 0065 remotely (`node scripts/migrate.mjs remote`). +4. Freeze, then export and import. cubedocs-auth stays writable until the new + code is live, and anything written there after the export is lost, so keep + the window short and quiet (export, import and step 5 back to back, within + minutes, and not across :17 past the hour when the old admin cron runs + scheduled deletions): turn off sign-ups on the old Annex and let in-flight + registrations finish (an account made between the export and step 5 + misses this import), note the time, don't schedule or cancel admin + deletions or change grants/badges/handles in the admin panel, then + `npx wrangler d1 export cubedocs-auth --remote --output migration-data/cubedocs-auth.sql`, + `node scripts/import-auth-data.mjs migration-data/cubedocs-auth.sql`, + `npx wrangler d1 execute cubedocs-main --remote --file migration-data/annex-import.sql`. + Keep `migration-data/` for the reconciliation in step 7. +5. Deploy api, then admin, then frontend. Everyone signs in again (old Annex + JWTs don't validate against the new sessions table). +6. Replay Stripe: events the old worker handled between the export and the + deploy were applied to cubedocs-auth only. In the Stripe Dashboard + (Developers → Webhooks → the docs.cubityfir.st endpoint) resend every event + since the time noted in step 4. The handler is idempotent + (`webhook_events`), so overlap is harmless. +7. Reconcile, once nothing routes to the old login/register/delete-account + routes (after step 5): take a FINAL export of cubedocs-auth and compare its + user ids with the identity service's actual import snapshot (the + `import.sql` it was loaded from on 2026-11-18). Compare ids, not dates: + accounts created on auth.cubityfir.st since its import are never involved. + - **Deletions** - ids in the snapshot but absent from the final export were + deleted on the old Annex after that import and could otherwise sign back + in. Delete them at auth.cubityfir.st/admin/users. + - **Additions** - ids in the final export but absent from the snapshot + registered on the old Annex after that import. Step 4 already mirrored + them (with their sites and billing) under that id, but auth.cubityfir.st + has no such account: registering there would mint a new id and strand + their Annex data. Add them to cubityfirst-auth **with their original + ids** (users + recovery codes, from the final export). The identity + repo's `import-from-annex.mjs` replaces every user, so it can't be re-run + now; this needs an additions-only import from that repo. If an addition's + email has since been registered on auth.cubityfir.st under a new id, + resolve it by hand. + + Then **enable** the two Annex clients and delete `migration-data/`. +8. Retire annex-auth (`npx wrangler delete annex-auth`) once traffic is on the + new code, and later cubedocs-auth after a backup. diff --git a/memories/Ink-Stripe.md b/memories/Ink-Stripe.md index 898b6e4b..03804d99 100644 --- a/memories/Ink-Stripe.md +++ b/memories/Ink-Stripe.md @@ -44,7 +44,7 @@ Plus `webhook_events (event_id PRIMARY KEY, type, processed_at)` for idempotency ## Plan resolution -**Always go through `resolvePersonalPlan` in `packages/auth/src/plan.ts`.** Never read the columns directly to determine plan state. The resolver is a pure function with this precedence: +**Always go through `resolvePersonalPlan` in `packages/api/src/account/plan.ts`.** Never read the columns directly to determine plan state. The resolver is a pure function with this precedence: 1. `granted_plan` set AND (`granted_plan_expires_at` is NULL OR in the future) → `via: 'granted'`, `status: 'granted'` 2. `personal_plan` set AND `personal_plan_status` ∈ `{active, trialing, past_due}` → `via: 'paid'` @@ -56,13 +56,13 @@ The resolver's input row mixes columns from BOTH satellite tables (`personal_pla ## Cross-package consideration -The API worker reads `users`, `user_billing`, and `user_preferences` directly via the `AUTH_DB` binding (read-only by convention) for `loadCurrentSession`, member-list plan info, and `/users/:id` profile responses. The admin worker also reads them for the user details panel. +`users` (the identity mirror), `user_billing` and `user_preferences` live in cubedocs-main (api migration 0065; copied from the retired cubedocs-auth). The API worker reads them for `loadCurrentSession`, member-list plan info and `/users/:id`; the admin worker reads/writes them for the user details panel and grants. -**A schema change to any column the resolver touches requires redeploying auth + api + admin** in that order, AND every reader must continue to use LEFT JOIN so older code transitioning to a missing-satellite world still behaves. The migrations live in `packages/auth/migrations/` only. +**A schema change to any column the resolver touches requires redeploying api + admin** (api first), AND every reader must continue to use LEFT JOIN so a user without a satellite row still behaves. Migrations live in `packages/api/migrations/`. ## Stripe webhook flow -`packages/auth/src/routes/stripe-webhook.ts`. Public endpoint, signature-verified. Reached via `https://docs.cubityfir.st/stripe/webhook` - the frontend worker proxies `/stripe/webhook` to auth via service binding (see `packages/frontend/worker/index.ts`). Stripe doesn't see the auth worker directly because it has no public hostname. +`packages/api/src/routes/stripeWebhook.ts`. Public endpoint, signature-verified. Reached via `https://docs.cubityfir.st/stripe/webhook` - the frontend worker forwards `/stripe/webhook` verbatim to the api worker via service binding (see `packages/frontend/worker/index.ts`), so the URL registered in the Stripe Dashboard didn't change when billing moved off the retired auth worker. An event for a user Annex no longer has (FK failure on `user_billing`) is acknowledged, not retried. Handler contract (load-bearing): @@ -87,21 +87,21 @@ Admin worker calls Stripe REST directly with its own `STRIPE_SECRET_KEY` (set pe `.dev.vars` files (gitignored) hold local secrets: -- `packages/auth/.dev.vars` needs `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_INK_PRICE_ID`, `APP_ORIGIN=http://localhost:5173` +- `packages/api/.dev.vars` needs `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `STRIPE_INK_PRICE_ID`, `APP_ORIGIN=http://localhost:5173` - `packages/admin/.dev.vars` needs `STRIPE_SECRET_KEY` only -Forward Stripe webhook events to the local auth worker: +Forward Stripe webhook events to the local api worker: ``` -stripe listen --forward-to http://localhost:8788/stripe/webhook +stripe listen --forward-to http://localhost:8787/stripe/webhook ``` -The CLI prints a `whsec_...` at startup - that's what goes in `STRIPE_WEBHOOK_SECRET` for local dev. (Live mode uses a different `whsec_` from the registered webhook in Stripe Dashboard.) Restart the auth worker after editing `.dev.vars` - wrangler only reads it on startup. +The CLI prints a `whsec_...` at startup - that's what goes in `STRIPE_WEBHOOK_SECRET` for local dev. (Live mode uses a different `whsec_` from the registered webhook in Stripe Dashboard.) Restart the api worker after editing `.dev.vars` - wrangler only reads it on startup. ## Production setup -- `STRIPE_INK_PRICE_ID` is a `bindings.text` var in `packages/auth/cloudflare.config.ts` (live price id - committed). `.dev.vars` overrides locally to the test-mode price id. -- `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` set via `wrangler secret put` on the auth worker. `STRIPE_SECRET_KEY` also on admin worker. +- `STRIPE_INK_PRICE_ID` is a `bindings.text` var in `packages/api/cloudflare.config.ts` (live price id - committed). `.dev.vars` overrides locally to the test-mode price id. +- `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` set via `npx wrangler secret put` on annex-api (they used to be on annex-auth - move them at cutover). `STRIPE_SECRET_KEY` also on annex-admin. - Webhook endpoint URL in Stripe Dashboard: `https://docs.cubityfir.st/stripe/webhook`. Subscribed events: `checkout.session.completed`, `customer.subscription.created/updated/deleted`, `invoice.paid`, `invoice.payment_failed`. - Customer Portal must be configured separately in **live** mode (Settings → Billing → Customer portal). Test mode and live mode have different portal configs. diff --git a/memories/Worktree-Dev.md b/memories/Worktree-Dev.md index 43d7de2f..5b7799a9 100644 --- a/memories/Worktree-Dev.md +++ b/memories/Worktree-Dev.md @@ -7,9 +7,9 @@ browser on its own port - while a single shared backend serves them all. Driven ## The model ``` -main checkout G:\Scripts\cubedocs → pnpm dev (frontend 5173 + api 8787 + auth 8788 +main checkout G:\Scripts\cubedocs → pnpm dev (frontend 5173 + api 8787 + admin 8789 + the shared .wrangler/state D1) ── full - stack; the api/auth/admin here are the ONE backend + stack; the api/admin here are the ONE backend worktree A ..\cubedocs-worktrees\feat-x (branch feat-x) → vite --port 5200 ─┐ worktree B ..\cubedocs-worktrees\feat-y (branch feat-y) → vite --port 5201 ─┼─ all proxy /api → :8787 worktree C ... → vite --port 5202 ─┘ diff --git a/package.json b/package.json index 502a1a36..c57386cc 100644 --- a/package.json +++ b/package.json @@ -3,15 +3,15 @@ "private": true, "version": "0.0.2", "scripts": { - "dev": "concurrently \"pnpm --filter frontend dev\" \"pnpm --filter api dev\" \"pnpm --filter auth dev\" \"pnpm --filter @annex/admin dev\"", - "dev:stripe": "stripe listen --forward-to http://localhost:8788/stripe/webhook", - "build": "concurrently \"pnpm --filter frontend build\" \"pnpm --filter api build\" \"pnpm --filter auth build\" \"pnpm --filter @annex/admin build\"", - "deploy": "concurrently \"pnpm --filter frontend deploy\" \"pnpm --filter api deploy\" \"pnpm --filter auth deploy\" \"pnpm --filter @annex/admin deploy\"", - "typecheck": "concurrently \"pnpm --filter frontend typecheck\" \"pnpm --filter api typecheck\" \"pnpm --filter auth typecheck\" \"pnpm --filter @annex/admin typecheck\" \"pnpm --filter @annex/admin-frontend typecheck\" \"pnpm --filter @annex/mcp typecheck\"", - "migrate": "pnpm --filter api migrate && pnpm --filter auth migrate", + "dev": "concurrently \"pnpm --filter frontend dev\" \"pnpm --filter api dev\" \"pnpm --filter @annex/admin dev\"", + "dev:stripe": "stripe listen --forward-to http://localhost:8787/stripe/webhook", + "build": "concurrently \"pnpm --filter frontend build\" \"pnpm --filter api build\" \"pnpm --filter @annex/admin build\"", + "deploy": "concurrently \"pnpm --filter frontend deploy\" \"pnpm --filter api deploy\" \"pnpm --filter @annex/admin deploy\"", + "typecheck": "concurrently \"pnpm --filter frontend typecheck\" \"pnpm --filter api typecheck\" \"pnpm --filter @annex/admin typecheck\" \"pnpm --filter @annex/admin-frontend typecheck\" \"pnpm --filter @annex/mcp typecheck\"", + "migrate": "pnpm --filter api migrate", "migrations:local": "node scripts/migrate.mjs local", "migrations:remote": "node scripts/migrate.mjs remote", - "test": "concurrently \"pnpm --filter api test\" \"pnpm --filter auth test\" \"pnpm --filter frontend test\" \"pnpm --filter @annex/mcp test\" && pnpm test:e2e", + "test": "concurrently \"pnpm --filter api test\" \"pnpm --filter frontend test\" \"pnpm --filter @annex/admin test\" \"pnpm --filter @annex/admin-frontend test\" \"pnpm --filter @annex/mcp test\" && pnpm test:e2e", "test:e2e": "pnpm --filter cubedocs-e2e test", "test:e2e:ui": "pnpm --filter cubedocs-e2e test:ui" }, diff --git a/packages/admin/.dev.vars.example b/packages/admin/.dev.vars.example new file mode 100644 index 00000000..aeb504ca --- /dev/null +++ b/packages/admin/.dev.vars.example @@ -0,0 +1,23 @@ +# Copy to packages/admin/.dev.vars (gitignored). + +# Signs the admin panel's own session JWTs. Any random string locally. +JWT_SECRET=change-me + +# The admin SPA's origin (its Vite dev server proxies /api to :8789). +APP_ORIGIN=http://localhost:5174 + +# The admin panel is its own OIDC client of the identity service. With a local +# identity worker on :8790 (see packages/api/.dev.vars.example), register a +# client with redirect URI http://localhost:5174/api/auth/callback and +# post-logout URI http://localhost:5174 (no trailing slash), scopes `openid profile email roles`, +# first-party. Sign-in requires an account with the admin role. +OIDC_ISSUER=http://localhost:8790 +OIDC_CLIENT_ID=annex-admin-local +OIDC_CLIENT_SECRET= + +# Skip the identity service: POST /api/dev/quick-login mints an admin dev +# session (the e2e admin suite uses it). Localhost APP_ORIGIN only. +DEV_QUICK_LOGIN=true + +# Admin-driven Stripe actions (test mode). +# STRIPE_SECRET_KEY=sk_test_... diff --git a/packages/admin/cloudflare.config.ts b/packages/admin/cloudflare.config.ts index 8495fa58..28d9b14d 100644 --- a/packages/admin/cloudflare.config.ts +++ b/packages/admin/cloudflare.config.ts @@ -4,10 +4,10 @@ export default defineConfig({ accountId: "d843ae90cab33e54f4d284bc65d2fd6a", worker: { name: "annex-admin", - // Keep in lockstep with the auth worker's compatibilityDate: this worker - // imports auth source (session.ts/jwt.ts) cross-package, so runtime-behavior - // differences between dates would make shared code behave differently per - // worker. + // Keep in lockstep with the api worker's compatibilityDate: this worker + // imports api source (account/*, routes/auth.ts) cross-package, so + // runtime-behavior differences between dates would make shared code behave + // differently per worker. compatibilityDate: "2026-02-24", entrypoint: "src/index.ts", workersDev: false, @@ -21,8 +21,8 @@ export default defineConfig({ "admin.cubityfir.st", ], triggers: [ - // Hourly: performs account deletions scheduled from the Users page once - // their grace window has passed (src/lib/userDeletion.ts + // Hourly: performs Annex-data deletions scheduled from the Users page + // once their grace window has passed (src/lib/userDeletion.ts // runDueUserDeletions). triggers.scheduled({ schedule: "17 * * * *", @@ -41,25 +41,34 @@ export default defineConfig({ name: "cubedocs-main", id: "267490be-7141-4d00-ab23-152742f2f6ef", }), - // Read+write: unlike the API worker's read-only-by-convention AUTH_DB - // binding, the admin worker writes users (moderation/ - // force_password_change), user_moderation_events, user_preferences - // (badges), user_billing (grant columns), and admin_audit_log directly. - // Credential/session/oauth_clients writes still go through the AUTH - // service binding. Migrations live only in packages/auth/migrations/. - AUTH_DB: bindings.d1({ - name: "cubedocs-auth", - id: "db327d85-b8c2-4fed-adaa-25e748778c86", + // Sign in with auth.cubityfir.st: the admin panel is its own first-party + // OIDC client (scopes `openid profile email roles`, sign-in requires the + // admin role), registered with redirect URI APP_ORIGIN/api/auth/callback + // and post-logout redirect URI APP_ORIGIN (no trailing slash; matched byte + // for byte). OIDC_CLIENT_ID must be the id + // it was registered with at auth.cubityfir.st/admin/clients; + // OIDC_CLIENT_SECRET is a secret. + OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), + OIDC_CLIENT_ID: bindings.text("oidc_07c81f4a5aa63dd2bd0b15cc"), + APP_ORIGIN: bindings.text("https://admin.cubityfir.st"), + // Identity service RPC (live standing + admin role, user lookups). + IDENTITY: bindings.worker({ + worker: "cubityfirst-auth", + exportName: "IdentityService", + }), + // The identity worker's HTTP surface (default export) for server-side + // OIDC requests (discovery, JWKS, token). Required: a Worker's fetch() + // to auth.cubityfir.st from this same zone goes to the origin, not to + // the identity worker. Only the browser redirects use the public URL. + IDENTITY_OIDC: bindings.worker({ + worker: "cubityfirst-auth", }), ASSETS: bindings.r2({ name: "cubedocs-assets", }), - AUTH: bindings.worker({ - worker: "annex-auth", - }), - // GA ratelimit bindings - simulated locally in dev. See the auth - // worker's cloudflare.config.ts. - // IP-keyed coarse abuse cap across every authenticated admin API route. + // GA ratelimit bindings - simulated locally in dev. + // IP-keyed coarse abuse cap across every authenticated admin API route + // and the sign-in endpoints. // Generous enough for an operator clicking around the dashboard; only // bites scripted abuse with a stolen admin token. RATE_LIMITER_ADMIN: bindings.rateLimit({ @@ -69,15 +78,6 @@ export default defineConfig({ period: 60, }, }), - // Tighter, separate bucket for the unauthenticated handoff-exchange - // proxy (the only pre-auth endpoint that hits the auth worker + DB). - RATE_LIMITER_ADMIN_HANDOFF: bindings.rateLimit({ - namespace: "2002", - simple: { - limit: 10, - period: 60, - }, - }), // Separate budget for the public avatar route: a 25-row dashboard page // costs 25 avatar fetches, which previously drained the shared admin // API budget and started 429ing the operator after ~2 searches/min. @@ -91,12 +91,12 @@ export default defineConfig({ SITE_ASSETS: bindings.assets(), // Secrets (set via `npx wrangler secret put --name annex-admin`; // existing secrets are kept across `cf deploy`): - // JWT_SECRET (same value as the auth worker's JWT_SECRET - the - // admin worker verifies sessions inline against - // AUTH_DB instead of calling auth's /verify route) - // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - same value as auth - // worker; only used for admin-driven cancellations - // triggered from the user details panel) + // JWT_SECRET (signs this panel's own 'admin' session JWTs; + // Annex-only, not shared with the identity service) + // OIDC_CLIENT_SECRET (the annex-admin client's secret from + // auth.cubityfir.st) + // STRIPE_SECRET_KEY (sk_test_... or sk_live_... - same value as the api + // worker; used for admin-driven Stripe actions) // CF_API_TOKEN (same token as the api worker - zone-scoped, SSL // and Certificates: Edit; only used to release a // custom hostname on admin-driven site delete) diff --git a/packages/admin/frontend/src/App.test.tsx b/packages/admin/frontend/src/App.test.tsx index 91c2f180..ec203323 100644 --- a/packages/admin/frontend/src/App.test.tsx +++ b/packages/admin/frontend/src/App.test.tsx @@ -4,23 +4,21 @@ import { render, screen, waitFor } from "@testing-library/react"; vi.mock("@/lib/api", () => { class TransientVerifyError extends Error {} - class AdminHandoffError extends Error { + class AdminSignInError extends Error { constructor(public readonly code: string) { super(code); } } return { TransientVerifyError, - AdminHandoffError, + AdminSignInError, LIST_PAGE_SIZE: 25, verifyAdminSession: vi.fn(), - logoutAdminSession: vi.fn(async () => undefined), - exchangeAdminHandoff: vi.fn(), + logoutAdminSession: vi.fn(async () => null), + exchangeAdminCode: vi.fn(), searchUsers: vi.fn(async () => ({ users: [], nextCursor: null })), getUserDetails: vi.fn(), updateUserBadges: vi.fn(), - updateUserModeration: vi.fn(), - forceUserPasswordChange: vi.fn(), deleteUserAvatar: vi.fn(), exportUserData: vi.fn(), grantInk: vi.fn(), @@ -36,16 +34,11 @@ vi.mock("@/lib/api", () => { removeProjectDomain: vi.fn(), listAuditLog: vi.fn(async () => ({ entries: [], nextCursor: null })), listAuditActions: vi.fn(async () => []), - listOAuthClients: vi.fn(async () => []), - createOAuthClient: vi.fn(), - deleteOAuthClient: vi.fn(), - rotateOAuthClientSecret: vi.fn(), - setOAuthClientDisabled: vi.fn(), }; }); import { App } from "./App"; -import { TransientVerifyError, verifyAdminSession } from "@/lib/api"; +import { TransientVerifyError, exchangeAdminCode, verifyAdminSession } from "@/lib/api"; import { getToken, setToken } from "@/lib/auth"; const SESSION = { @@ -71,7 +64,7 @@ beforeEach(() => { describe("App session gating", () => { it("shows the login page with no token", async () => { renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(verifyAdminSession).not.toHaveBeenCalled(); }); @@ -87,7 +80,7 @@ describe("App session gating", () => { setToken("tok"); vi.mocked(verifyAdminSession).mockRejectedValue(new Error("Unauthorized")); renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(getToken()).toBeNull(); }); @@ -97,7 +90,7 @@ describe("App session gating", () => { renderApp(); expect(await screen.findByText(/Couldn't reach the admin API/)).toBeInTheDocument(); expect(screen.getByText("Retry")).toBeInTheDocument(); - expect(screen.queryByText(/Continue to Annex sign-in/)).not.toBeInTheDocument(); + expect(screen.queryByText(/Continue to sign-in/)).not.toBeInTheDocument(); expect(getToken()).toBe("tok"); }); @@ -105,7 +98,18 @@ describe("App session gating", () => { setToken("tok"); vi.mocked(verifyAdminSession).mockResolvedValue({ ...SESSION, expiresAt: Date.now() - 1000 }); renderApp(); - expect(await screen.findByText(/Continue to Annex sign-in/)).toBeInTheDocument(); + expect(await screen.findByText(/Continue to sign-in/)).toBeInTheDocument(); expect(getToken()).toBeNull(); }); + + it("lands a completed sign-in on its deep link, through the verification screen", async () => { + vi.mocked(exchangeAdminCode).mockResolvedValue({ token: "fresh" }); + // A real verify round-trips the network, so App's verification screen + // replaces (unmounts) the completion page meanwhile. + vi.mocked(verifyAdminSession).mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(SESSION), 30))); + window.history.replaceState(null, "", "/auth/complete#status=ok&return_to=%2Faudit"); + renderApp("/auth/complete"); + expect(await screen.findByRole("heading", { name: "Audit Log" })).toBeInTheDocument(); + expect(getToken()).toBe("fresh"); + }); }); diff --git a/packages/admin/frontend/src/App.tsx b/packages/admin/frontend/src/App.tsx index 0a86c381..d5b78b6f 100644 --- a/packages/admin/frontend/src/App.tsx +++ b/packages/admin/frontend/src/App.tsx @@ -1,16 +1,15 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { Link, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom"; -import { Flag, KeyRound, ScrollText, Users, Boxes } from "lucide-react"; +import { Flag, KeyRound, ScrollText, Users, Boxes, ExternalLink } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ADMIN_AUTH_INVALIDATED_EVENT, clearToken, getToken } from "@/lib/auth"; -import { buildDocsAdminLoginUrl } from "@/lib/handoff"; import { type AdminAuthSession, TransientVerifyError, logoutAdminSession, verifyAdminSession } from "@/lib/api"; import { AuthCallbackPage } from "./pages/AuthCallbackPage"; import { LoginPage } from "./pages/LoginPage"; +import { postSignInPath } from "@/lib/signIn"; import { ProjectsPage } from "./pages/ProjectsPage"; import { UsersPage } from "./pages/UsersPage"; import { AuditPage } from "./pages/AuditPage"; -import { OAuthClientsPage } from "./pages/OAuthClientsPage"; import { ReportsPage } from "./pages/ReportsPage"; function AdminLayout({ @@ -71,15 +70,14 @@ function AdminLayout({ Audit - @@ -99,7 +97,6 @@ function AdminLayout({ } /> } /> } /> - } /> } /> @@ -114,7 +111,7 @@ export function App() { const [checking, setChecking] = useState(true); // Set when the session couldn't be VERIFIED (network down, API 5xx) as // opposed to being invalid - the token is kept and the operator gets a - // retry instead of being bounced through a full re-handoff. + // retry instead of being bounced through a full re-sign-in. const [verifyBlocked, setVerifyBlocked] = useState(null); // Latest session for the stable refreshSession callback (its deps are // empty so the closed-over `session` would always be the initial null). @@ -183,7 +180,7 @@ export function App() { setSession(null); setChecking(false); - if (location.pathname === "/login" || location.pathname === "/auth/callback") { + if (location.pathname === "/login" || location.pathname === "/auth/complete") { return; } @@ -203,14 +200,17 @@ export function App() { // Revoke the session server-side FIRST (while the token still works): // clearing local state alone would leave any copy of the token valid // until its TTL. Best-effort - local sign-out proceeds regardless. + let logoutUrl: string | null = null; try { - await logoutAdminSession(); + logoutUrl = await logoutAdminSession(); } catch { /* offline / already-revoked - still sign out locally */ } clearToken(); setSession(null); - window.location.assign(buildDocsAdminLoginUrl("/", { logout: true })); + // Continue to the identity service's end-session URL so the sign-out + // covers auth.cubityfir.st too; it comes back to the panel. + window.location.assign(logoutUrl ?? "/login"); } if (checking) { @@ -239,7 +239,7 @@ export function App() { return ( } /> - } /> + } /> ; + } + if (location.pathname === "/login") { return ; } diff --git a/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx b/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx new file mode 100644 index 00000000..ef61e7e4 --- /dev/null +++ b/packages/admin/frontend/src/components/projects/OrphanedOwnershipCard.tsx @@ -0,0 +1,89 @@ +import { useEffect, useState } from "react"; +import { AlertTriangle } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { type OrphanedOwnership, listOrphanedOwnership } from "@/lib/api"; +import { formatDateTime } from "@/lib/format"; + +// Sites and orgs whose owner deleted their account on auth.cubityfir.st. The +// deletion sync keeps them (other members may still rely on them); an +// operator decides here whether to delete them. Renders nothing when there's +// nothing to review. +export function OrphanedOwnershipCard({ onFilterSite, refreshKey }: { onFilterSite: (name: string) => void; refreshKey: unknown }) { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + const controller = new AbortController(); + listOrphanedOwnership(controller.signal) + .then(d => { setData(d); setError(null); }) + .catch(e => { if (!controller.signal.aborted) setError(e instanceof Error ? e.message : "Failed to load"); }); + return () => controller.abort(); + }, [refreshKey]); + + if (error) { + return

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

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

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

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

{site.name}

+

{site.id}

+

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

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

{org.name} (organization)

+

{org.id}

+

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

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

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

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

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

{plan.sites.length > 0 && (

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

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