From 13288dfc245902e9d138620ea4fd32ee67a505b3 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Wed, 18 Nov 2026 16:50:09 +0000 Subject: [PATCH 1/3] 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. --- packages/admin/cloudflare.config.ts | 71 +-- packages/admin/frontend/src/App.test.tsx | 23 +- packages/admin/frontend/src/App.tsx | 35 +- .../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 | 187 ++---- .../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 | 43 ++ .../src/pages/AuthCallbackPage.test.tsx | 72 +-- .../frontend/src/pages/AuthCallbackPage.tsx | 73 +-- .../admin/frontend/src/pages/LoginPage.tsx | 9 +- .../src/pages/OAuthClientsPage.test.tsx | 44 -- .../frontend/src/pages/OAuthClientsPage.tsx | 603 ------------------ .../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 | 116 ++-- packages/admin/src/index.ts | 98 ++- .../admin/src/lib/userDeletion.sqlite.test.ts | 327 +++++----- packages/admin/src/lib/userDeletion.test.ts | 109 ++-- packages/admin/src/lib/userDeletion.ts | 77 ++- packages/admin/src/routes/audit.ts | 4 +- packages/admin/src/routes/oauth.test.ts | 124 ---- packages/admin/src/routes/oauth.ts | 108 ---- packages/admin/src/routes/projects.ts | 7 +- packages/admin/src/routes/reports.test.ts | 50 +- packages/admin/src/routes/reports.ts | 2 +- packages/admin/src/routes/users.test.ts | 337 +++++----- packages/admin/src/routes/users.ts | 381 ++++------- packages/admin/tsconfig.json | 2 +- packages/api/src/account/identity.ts | 11 +- packages/api/src/routes/auth.ts | 113 ++-- 42 files changed, 1175 insertions(+), 2705 deletions(-) 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 diff --git a/packages/admin/cloudflare.config.ts b/packages/admin/cloudflare.config.ts index 8495fa58..07c024d3 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,33 @@ 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/. OIDC_CLIENT_ID must be the id + // it was registered with at auth.cubityfir.st/admin/clients; + // OIDC_CLIENT_SECRET is a secret. + OIDC_ISSUER: bindings.text("https://auth.cubityfir.st"), + OIDC_CLIENT_ID: bindings.text("annex-admin"), + 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 +77,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 +90,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..e4adbd82 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,11 +34,6 @@ 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(), }; }); @@ -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,7 @@ 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(); }); }); diff --git a/packages/admin/frontend/src/App.tsx b/packages/admin/frontend/src/App.tsx index 0a86c381..08353907 100644 --- a/packages/admin/frontend/src/App.tsx +++ b/packages/admin/frontend/src/App.tsx @@ -1,16 +1,14 @@ 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 { 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 +69,14 @@ function AdminLayout({ Audit - @@ -99,7 +96,6 @@ function AdminLayout({ } /> } /> } /> - } /> } /> @@ -114,7 +110,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 +179,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 +199,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 +238,7 @@ export function App() { return ( } /> - } /> + } /> ; } 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.`} - - - -
- -