[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GG6GN4Y0XJSBR5YCG0ARQ":3,"skill-same:01M79GG6GN4Y0XJSBR5YCG0ARQ":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79GG6GN4Y0XJSBR5YCG0ARQ","saasaloy-admin",null,"Runbook for the admin capability — a role-gated TanStack Router + Vite SPA in apps\u002Fadmin. Use when adding an admin screen, composing an admin screen from the shell blocks and primitives (the reference is saasaloy-shell), adding a nav group or an area to the sidebar shell, changing the admin theme in admin.css or the dark-by-default rule, wiring the typed hc\u003CAppType> client and TanStack Query, gating a new admin api route with requireAdmin or requireAdminApp, changing the admin-role guard, the login screen or the admin session client (createAdminClient, \u002Fadmin\u002Fauth, x-auth-audience), debugging the :3001 → :4000 cookie and CORS flow, reading a typecheck error that points into apps\u002Fapi, managing admin members on the members screen, reading the audit log on the Activity page, adding an audited admin write route with adminWrite or adminAuthWrite, adding a provider around the shell or a search param to a module screen through the extend\u002F seed files, removing the module, or deploying the static bundle to Workers.","mimukit\u002Fsaasaloy","mimukit","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F11677026?v=4","01M79GFSERAQQ77QPQMC1N0Y6M","Mukitul Islam Mukit","01M79GFSFA4WMGEEBHA68N59WV",4,"MIT","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fadmin\u002Fskills\u002Fsaasaloy-admin\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-admin\ndescription: Runbook for the admin capability — a role-gated TanStack Router + Vite SPA in apps\u002Fadmin. Use when adding an admin screen, composing an admin screen from the shell blocks and primitives (the reference is saasaloy-shell), adding a nav group or an area to the sidebar shell, changing the admin theme in admin.css or the dark-by-default rule, wiring the typed hc\u003CAppType> client and TanStack Query, gating a new admin api route with requireAdmin or requireAdminApp, changing the admin-role guard, the login screen or the admin session client (createAdminClient, \u002Fadmin\u002Fauth, x-auth-audience), debugging the :3001 → :4000 cookie and CORS flow, reading a typecheck error that points into apps\u002Fapi, managing admin members on the members screen, reading the audit log on the Activity page, adding an audited admin write route with adminWrite or adminAuthWrite, adding a provider around the shell or a search param to a module screen through the extend\u002F seed files, removing the module, or deploying the static bundle to Workers.\n---\n\n# admin — the role-gated backoffice SPA\n\n`apps\u002Fadmin` (`@repo\u002Fadmin`) is a plain browser bundle: [TanStack Router](https:\u002F\u002Ftanstack.com\u002Frouter)\nover Vite, built to static assets and served by a Worker with a single-page-application fallback.\nIt carries **no server code and no Cloudflare bindings**. Everything it knows, it asks `apps\u002Fapi`\nfor over the credentialed CORS spine, which is why it `dependsOn: [\"api\", \"auth\"]`. Its frame,\nprimitives and blocks come from the `shell` module, its third dependency.\n\nThree conventions define it, and the first two are file drops rather than patches:\n\n- **A screen is a file** under `src\u002Froutes\u002F`. The router plugin regenerates `src\u002FrouteTree.gen.ts`\n  and the screen is live, guarded, and typed — no descriptor patch, the admin twin of the schema\n  barrel in `packages\u002Fdb`.\n- **A request is a `queryOptions` object**, prefetched in the route's `loader` and read in the\n  component with `useQuery`, over a single `hc\u003CAppType>` client.\n- **A screen composes the shell blocks and primitives** in `@repo\u002Fui`, which the `shell` module writes into `packages\u002Fui\u002Fsrc\u002F{components,blocks,containers,lib}\u002Fshell\u002F`. It writes no shell markup, no table markup, no page padding and no colours of its own. The `saasaloy-shell` skill is the reference for the set.\n\n## Add a screen\n\nDrop `src\u002Froutes\u002F\u003Cfeature>.tsx` with a `createFileRoute` whose id matches the file path:\n\n```tsx\n\u002F\u002F src\u002Froutes\u002Fwidgets.tsx  →  \u002Fwidgets\nimport { queryOptions, useQuery } from \"@tanstack\u002Freact-query\";\nimport { createFileRoute } from \"@tanstack\u002Freact-router\";\n\nimport { DataTable } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fdata-table\";\nimport { EmptyState } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fempty-state\";\nimport { PageHeader } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fpage-header\";\nimport { PageLayout } from \"@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fpage-layout\";\n\nimport { api } from \"@admin\u002Flib\u002Fapi\";\n\nconst widgetsQuery = queryOptions({\n  queryKey: [\"widgets\"],\n  queryFn: async () => {\n    const res = await api.widgets.$get();\n    if (!res.ok) throw new Error(`The api answered ${res.status}.`);\n    return res.json();\n  },\n});\n\nexport const Route = createFileRoute(\"\u002Fwidgets\")({\n  loader: ({ context }) => context.queryClient.ensureQueryData(widgetsQuery),\n  component: Widgets,\n});\n\nfunction Widgets() {\n  const { data } = useQuery(widgetsQuery);\n  \u002F\u002F `useQuery` types `data` as `T | undefined` and the repo compiles with `strict`, so read\n  \u002F\u002F it through `?.` even when the loader has already filled the cache.\n  return (\n    \u003CPageLayout>\n      \u003CPageHeader title=\"Widgets\" count={data?.total} \u002F>\n      \u003CDataTable\n        caption=\"Widgets\"\n        columns={COLUMNS}\n        rows={data?.widgets ?? []}\n        rowId={(widget) => widget.id}\n        emptyState={\u003CEmptyState title=\"No widgets yet\" \u002F>}\n      \u002F>\n    \u003C\u002FPageLayout>\n  );\n}\n```\n\n```\n\nThat is the whole registration. The file is a child of `src\u002Froutes\u002F__root.tsx`, so it inherits the\nshell and the access gate with no work of its own. `src\u002Froutes\u002Fusers.tsx` is the worked example in\nthe scaffold; copy from it.\n\nEvery route renders inside the page frame (`@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fpage-frame`), which the root route wraps around `\u003COutlet \u002F>`. The frame owns the height and the gutter: it sets `--page-gutter`, and `PageHeader`, `PageBody`, toolbar rows (`px-(--page-gutter)`) and the table's first and last columns pad with it. A route never sets its own page width, background or padding. A screen that reaches for `mx-auto max-w-3xl` or `p-6` is fighting the frame, and the next change to the gutter will skip it.\n\nThree things the plugin owns, so do not hand-write them:\n\n- **`src\u002FrouteTree.gen.ts`.** `@tanstack\u002Frouter-plugin` rewrites it whenever a file under\n  `src\u002Froutes\u002F` appears or disappears. It is committed rather than ignored, so `tsc --noEmit` and a\n  fresh `pnpm build` work on a clean checkout before Vite has ever run. Edit routes, not the tree.\n  A module that drops a route file leaves the committed tree one route behind, so the `typecheck`\n  script runs `tsr generate` before `tsc`. `tsr.config.json` holds the generator options, and the\n  plugin and the CLI both read it, so the two write the same file.\n- **The route id string.** `createFileRoute(\"\u002Fwidgets\")` is derived from the file's path. Rename the\n  file and let the plugin rewrite the call; changing one without the other breaks the build.\n- **Plugin order in `vite.config.ts`.** `tanstackRouter()` runs before `react()`. Reversed, the\n  code-split rewrite lands on already-transformed output and the generated tree goes stale.\n\nLoading, not-found and error handling come with the app as well:\n\n- `src\u002Fmain.tsx` sets `defaultPendingComponent` to the `PageSkeleton` block and `defaultErrorComponent` to `RouteError` (`src\u002Fcomponents\u002Froute-error.tsx`), which renders the shell `ErrorState` with a retry and the error's message. Every route gets a skeleton while its loader runs and an error screen when it throws, inside the frame, with no code of its own.\n- `__root.tsx` carries a `notFoundComponent` and an `errorComponent` that render the same shell `ErrorState`, so an unknown address shows the themed 404 inside the shell.\n\nA route sets its own `errorComponent` only when its words should differ, as `\u002Fusers` and the overview do. Never register a second `notFoundComponent`: it captures every miss below it. Change the words in `packages\u002Fui\u002Fsrc\u002Fcontent\u002Ferrors.ts`, not in a new component. The router types `error` as `unknown`, so read a message with `error instanceof Error ? error.message : undefined` and pass it as `detail`.\n\nPutting the screen in the sidebar is a separate, optional step. See [The shell](#the-shell) below.\n\n## The shell\n\nEvery route except `\u002Flogin` renders inside `src\u002Fcomponents\u002Fapp-shell.tsx`, and so does every screen except the refusal page (`AccessDenied`, see [The gate](#the-gate-a-session-is-never-enough)). That file reads the router and the session and hands them to `ShellLayout` in `@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fshell-layout`, which imports no router and no session:\n\n| Part | File | What it holds |\n|---|---|---|\n| Sidebar | `containers\u002Fshell\u002Fshell-sidebar.tsx` | the brand row (`BrandMark` and the product name), the organization picker's empty slot for #141, every area's nav groups, and the account menu at the foot with the name, the email and sign-out |\n| Content panel | `containers\u002Fshell\u002Fshell-layout.tsx` | a sticky header with the sidebar toggle and the page path, then the route inside the page frame |\n\nThe sidebar is the coss sidebar from the shell set, `variant=\"inset\"` and `collapsible=\"icon\"`. It sits on the canvas; the content panel is the one raised surface beside it. The header toggle and ⌘B \u002F Ctrl+B collapse it to a 56 px icon strip, where each row shows its label in a tooltip. Below `md` it opens as a sheet from the same toggle, and following a link closes the sheet. The open state is component state only, never storage, so a reload lands on the expanded sidebar.\n\nActive state is `aria-current`. `AppShell`'s link component wraps TanStack Router's `Link`, which sets `aria-current=\"page\"` on the active row, and the sidebar row styles that attribute. There is no second \"which page am I on\" comparison to keep in step. The page path in the header is the area's label and the label of the nav item whose `to` is the longest prefix of the current path.\n\n### Add a nav group or an area\n\n`NAV_AREAS` in `src\u002Fcomponents\u002Fnav.ts` is the one list to edit:\n\n```tsx\nexport const NAV_AREAS = [\n  {\n    label: \"Admin\",\n    to: \"\u002F\",\n    icon: LayoutDashboardIcon,\n    groups: [\n      {\n        label: \"Manage\",\n        items: [\n          { to: \"\u002F\", label: \"Overview\", icon: GaugeIcon, shortcut: \"G O\" },\n          { to: \"\u002Fusers\", label: \"Users\", icon: UsersIcon, shortcut: \"G U\" },\n        ],\n      },\n    ],\n  },\n] as const;\n```\n\n- **A new nav row** is one entry in an existing group's `items`. It needs `to`, `label` and `icon`, and takes an optional `count` and an optional `shortcut`, `G` then a letter written as `\"G R\"`. Pick the letter by hand and keep it unique; the tool repo's `commands.test.ts` fails on two rows with one shortcut, and the `command` module reports a conflict. A feature module adds its row with a `nav-entry` patch.\n- **A new group** is one entry in an area's `groups`, with a `label` and its own `items`. The sidebar renders it under the ones above it, with its label.\n- **A new area** is one entry in `NAV_AREAS`. The sidebar lists every area's groups in order, and `areaFor(pathname)` picks the area whose label starts the header's page path.\n\nKeep the `as const`. It is what holds every `to` at a literal type the router can check, so a nav entry naming a route that does not exist fails `pnpm typecheck` instead of 404-ing in the browser. The shell in `@repo\u002Fui` reads the entries through structural types with `to: string`; the one cast from that string back to a route lives in `AppShell`'s link component.\n\nEvery row becomes a \"Go to \u003Clabel>\" command in `src\u002Fcomponents\u002Fcommands.ts`, next to sign out and the three theme choices. `AppShell` declares them in the `global` scope, and a page declares its own with `useCommands(commands, { scope: \"route\", label })`, as `src\u002Froutes\u002Fusers.tsx` does for its filters. They do nothing until the `command` module is installed; see \"Declare a screen's commands\" in the `saasaloy-shell` skill. `src\u002Fcomponents\u002Fshell-extensions.ts` is the list a module such as `command` appends itself to; keep its `extensions` property even while it is empty.\n\n`nav.ts` holds the data and the rules that read it, and nothing else, so its rules stay unit-testable without React. Read an optional count through the `navCount(entry)` helper rather than `entry.count`.\n\n### Add a live count to a nav row\n\nA static `count` in `NAV_AREAS` is a number fixed at build time. A number that changes, such as how many payments wait for a review, is a live count. `NAV_COUNTS` in `src\u002Fcomponents\u002Fnav-counts.ts` lists them, one `{ to, path }` per row. `to` is the row's `to` in `NAV_AREAS`. `path` is an api path that answers `{ count: number }` behind the admin session.\n\nA module adds its entry with a `const-array` patch keyed on `to`. The payment module's patch is the example:\n\n```json\n{\n  \"file\": \"apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav-counts.ts\",\n  \"kind\": \"const-array\",\n  \"constName\": \"NAV_COUNTS\",\n  \"key\": \"to\",\n  \"entry\": { \"to\": \"\u002Fpayments\", \"path\": \"\u002Fadmin\u002Fpayment\u002Freview-count\" }\n}\n```\n\n`AppShell` runs one TanStack query per entry under the key `[\"nav-count\", to]`. Each query fetches `PUBLIC_API_URL` plus `path` with the session cookie and `x-auth-audience: admin`, the same `API_HEADERS` and `API_CREDENTIALS` that `src\u002Flib\u002Fapi.ts` gives the typed client. The queries refetch on window focus and every 60 s, and TanStack Query does not run the interval in a hidden tab. `AppShell` passes the numbers to `ShellLayout` as `counts`, keyed by `to`.\n\nThe sidebar applies `withLiveCounts` from `@repo\u002Fui\u002Flib\u002Fshell\u002Fnav-counts`:\n\n- A live count replaces the row's static `count`.\n- A live 0 hides the badge. A static 0 still renders.\n- Before the first successful fetch the static `count` stays.\n- A failed fetch (a network error, a non-OK answer or a body without a numeric `count`) throws, so TanStack Query keeps the last count it read. The badge never drops to 0 or disappears because of a failure, and a failed count shows no error.\n\nA screen whose action changes a count invalidates the key after the mutation, so the badge follows with no reload:\n\n```ts\nawait queryClient.invalidateQueries({ queryKey: [\"nav-count\", \"\u002Fpayments\"] });\n```\n\nKeep the route that answers the count cheap: the shell calls it on every focus and every minute while the tab is open.\n\n## The shell primitive set and the page blocks\n\nThe `shell` module writes the UI kit this app uses into `packages\u002Fui\u002Fsrc\u002F{components,blocks,containers,lib}\u002Fshell\u002F`, and admin code uses nothing else. The `saasaloy-shell` skill lists every primitive and block, their props, the `DataTable` column shape and the lint rule. Two admin-only facts sit here:\n\n- `ShellLayout` keeps its `subtitle` prop at the default, `\"Admin\"`, the line under the product name.\n- The router's defaults render the shell `ErrorState` and `PageSkeleton`, and `__root.tsx` mounts the toast provider for `toastManager` from `components\u002Fshell\u002Ftoast`.\n\n## The users screen, end to end\n\n`src\u002Froutes\u002Fusers.tsx` is the worked example, and every row in it is real data from `GET \u002Fadmin\u002Fusers`.\n\n- `usersQuery` in `src\u002Flib\u002Fusers-query.ts` is a `queryOptions` over `api.admin.users.$get({ query: {} })`, keyed `[\"admin\", \"users\"]`. `newestUsersQuery` beside it asks `?limit=5&sortBy=createdAt&sortDirection=desc` for the overview and is keyed `[\"admin\", \"users\", \"newest\"]`, so invalidating `usersQuery.queryKey` refreshes both.\n- `GET \u002Fadmin\u002Fusers` takes `limit` (1 to 100, default 100), `sortBy` (`createdAt` or `name`) and `sortDirection` (`asc` or `desc`), validated after `adminGate`, and passes them to `listUsers`. `total` is always the count of every account.\n- The row type is derived from the query's own return type, so a field dropped in `apps\u002Fapi` lands as a typecheck failure here.\n- `PageHeader` shows `data.total`, the api's count. The endpoint caps its answer at 100 users, so the loaded page and the real total can differ.\n- `FilterChips` narrows the loaded rows by role, in the component, with no refetch.\n- `DataTable` renders name with an avatar, email, role as a `StatusPill`, verified as an `ok` or `warn` `StatusPill`, and created. The columns are a module-scope constant.\n- An empty list shows one `EmptyState`, and a list filtered to nothing shows another with a \"Show all users\" button.\n- The selected user is `useState` in the route. The route builds the `DetailPanel`, with the role pill in its `status` slot, and hands it to `PageLayout` as `detail`.\n- `UsersError` is the worked example of a route overriding the router's default error screen.\n\nCopy that split when you add a screen: **the route owns the state and the data, the blocks own the pixels.**\n\n## The gate: a session is never enough\n\nThis app signs in on the **admin session**: `adminAuth` at `\u002Fadmin\u002Fauth`, cookie `admin.session_token`. A client signed in on another app in the same browser holds `client.session_token`, which this app never reads, so the two stay signed in side by side. See \"Two instances\" in the `saasaloy-auth` skill.\n\n`src\u002Froutes\u002F__root.tsx` decides access in `beforeLoad`, top-down, before any child route's `loader` fires. Three outcomes and no fourth:\n\n| Visitor | Outcome |\n|---|---|\n| No admin session (anonymous, or signed in only as a client) | `throw redirect({ to: \"\u002Flogin\", search: { redirect: location.href } })`, except on `\u002Flogin` itself |\n| Admin session, role not in `ADMIN_APP_ROLES` | `throw new NotAdminError(session)` → the root `errorComponent` renders `AccessDenied` **in place**, alone, without `AppShell` |\n| Admin session, role in `ADMIN_APP_ROLES` | the shell renders |\n\n`isAdmin` in `src\u002Flib\u002Fauth.ts` makes the check against `ADMIN_APP_ROLES`, the browser copy of the list in `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts`. A project that adds a role such as `support` to the admin group adds it to both copies; the `saasaloy-auth` skill has the recipe.\n\nThe middle row is rare. `adminAuth` refuses to open a session for an account outside `ADMIN_APP_ROLES`, with \"Invalid email or password\" on the login screen, so a client account never gets this far. The row is for an account whose role a superadmin removed after it signed in. It still holds a valid admin session, so redirecting it to `\u002Flogin` sends it straight back the moment the guard reads it, and the address bar ping-pongs. It gets a terminal panel with a sign-out button instead.\n\n`AccessDenied` (`src\u002Fcomponents\u002Faccess-denied.tsx`) renders on its own, centered on the login screen's card, with no sidebar, header or user menu. The shell names every screen this app has, which a refused account has no reason to learn. The panel is the page's `\u003Cmain>`, because no shell gives it one. `NotAdminError` keeps the session only so the panel can name the signed-in email.\n\n**Every deny is a throw, and that is load-bearing.** `beforeLoad` runs before any loader, but only a\nthrow ends the match; a `beforeLoad` that returns normally lets every matched route's `loader` run.\nSo the non-admin case is a thrown `NotAdminError` (exported from `__root.tsx`) that the root route's\n`errorComponent` turns into the panel, not a role check inside the component. Deny it in the\ncomponent instead and the loaders of the route the visitor asked for fire first, on their cookie,\nbefore the panel paints. Keep the check in `beforeLoad` and no child loader runs for anyone the\nguard turns away.\n\n### This guard is the second half of the gate\n\nThe first half is `requireAdmin` (or `requireAdminApp`) in `@repo\u002Fauth\u002Fserver`, and the api route is where it runs. Both read the admin session whatever the request's `x-auth-audience` header says. Use `requireAdmin` for admin-only work and `requireAdminApp` for a route every admin-app role may call, `support` included when a project adds it. `beforeLoad` stops this app from asking on a denied visitor's behalf; it cannot stop `curl`, a stale bundle, or a second client someone writes against the same api. Ship a new admin route and you wire both halves or you have shipped neither:\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Freports.ts — the server half\nimport { Hono } from \"hono\";\nimport { adminGate, requireAdmin } from \"@repo\u002Fauth\u002Fserver\";\n\nexport const reports = new Hono()\n  .get(\"\u002F\", adminGate, async (c) => {\n    await requireAdmin(c);\n    return c.json({ reports: await listReports() }, 200);\n  })\n  .post(\"\u002F\", adminGate, validReport, async (c) => {\n    const session = await requireAdmin(c);\n    return c.json(await createReport(c.req.valid(\"json\"), session.user.id), 201);\n  });\n```\n\n`adminGate` goes first on every admin route, before any validator. Hono runs a route's handlers in the order they are listed, so a validator listed first answers a caller with no session with a 400 that names the field it rejected, which tells a stranger what the route expects. With the gate first, every such caller gets the same 401. The handler still calls `requireAdmin` (or `requireAdminApp`) itself, because that call returns the session it needs. `adminGate` demands the `requireAdmin` roles; a route open to every admin-app role skips it and opens with `requireAdminApp`, and it must then take no validator before that call.\n\nThe shipped `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-gate.test.ts` holds the rule for you. It walks `app.routes`, sends every `\u002Fadmin\u002F*` route except `\u002Fadmin\u002Fauth\u002F*` a request with no cookie, a malformed body and a junk query, and fails on any answer but 401. A new route under `\u002Fadmin` is checked with no new test. Run it with `pnpm -C apps\u002Fapi test`.\n\nEvery admin write route also needs an audit action. `apps\u002Fapi\u002Fsrc\u002Froutes\u002Faudit-coverage.test.ts` walks `app.routes` the same way and fails on any `POST`, `PUT`, `PATCH` or `DELETE` under `\u002Fadmin\u002F` (outside `\u002Fadmin\u002Fauth\u002F*`) that no module's action file in `apps\u002Fapi\u002Fsrc\u002Faudit\u002F` names. The header of `apps\u002Fapi\u002Fsrc\u002Flib\u002Fadmin-write.ts` holds the recipe. The audited routes that ship today:\n\n| Module | Route | Actions |\n| --- | --- | --- |\n| `payment` | `POST \u002Fadmin\u002Fpayment\u002Fpayments\u002F:id\u002Freview` | `payment.review.confirm`, `payment.review.reject` |\n| `payment` | `POST \u002Fadmin\u002Fpayment\u002Fpayments\u002F:id\u002Frefunds` | `payment.refund.create` |\n| `feature-flags` | `PUT \u002Fadmin\u002Fflags\u002F:key` | `flag.value.set` |\n| `feature-flags` | `PUT \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.set` |\n| `feature-flags` | `DELETE \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.clear` |\n| `admin` | `POST \u002Fadmin\u002Fmembers` | `member.add` |\n| `admin` | `PATCH \u002Fadmin\u002Fmembers\u002F:id` | `member.profile.update` |\n| `admin` | `POST \u002Fadmin\u002Fmembers\u002F:id\u002Fpassword` | `member.password.set` |\n| `admin` | `DELETE \u002Fadmin\u002Fmembers\u002F:id` | `member.remove` |\n| `admin` | `POST \u002Fadmin\u002Fmembers\u002F:id\u002Frestore` | `member.restore` |\n\nThe `admin()` plugin's own endpoints answer 404 on `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` over HTTP, so a staff change to a user goes through an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.*` inside `adminAuthWrite`, never through `auth.admin.*` in the browser.\n\n```tsx\n\u002F\u002F apps\u002Fadmin\u002Fsrc\u002Froutes\u002Freports.tsx — the client half\nexport const Route = createFileRoute(\"\u002Freports\")({\n  loader: ({ context }) => context.queryClient.ensureQueryData(reportsQuery),\n  component: Reports,\n});\n```\n\nThe screen needs no guard of its own. It is a child of `__root.tsx`, so it inherits `beforeLoad`, and a non-admin never reaches its loader. That inheritance is exactly what makes the server half easy to forget: the screen behaves correctly while the endpoint behind it answers anyone.\n\n`GET \u002Fadmin\u002Fusers` is the shipped example. `modules\u002Fadmin\u002Ffiles\u002Fapi\u002Froutes\u002Fadmin-users.ts` lists `adminGate` and its query validator, calls `requireAdmin` for the session, then `adminAuth.api.listUsers` (the admin plugin's endpoints answer only on the admin instance, and only to server code: the forward answers 404 to `\u002Fadmin\u002Fauth\u002Fadmin\u002F*`), and answers `{ users, total }`. A `chained-route` patch registers it on api's exported chain, so `hc\u003CAppType>` types it here for free. `src\u002Froutes\u002Fusers.tsx` renders it, so both halves of the gate are live in the scaffold and the next route has a pattern to copy on each side.\n\nProve the server half yourself rather than trusting the screen. Sign in as a client through `POST \u002Fauth\u002Fsign-in\u002Femail`, take the cookie jar, and call the endpoint directly:\n\n```sh\ncurl -i -b \u002Ftmp\u002Fclient-cookies.txt http:\u002F\u002Flocalhost:4000\u002Fadmin\u002Fusers\n```\n\nThat answers `401` with `{\"error\":{\"code\":\"unauthorized\",\"message\":\"sign in first\"}}`, because a client cookie is no admin session at all. An admin session whose role was removed after sign-in gets `403` with `\"role required: admin or superadmin\"`. A `200` means the route skipped the gate, whatever the browser shows.\n\n`src\u002Flib\u002Fauth.ts` owns the read. `loadSession()` fetches once per page load and hands the same\npromise to every caller, so a burst of navigations costs one round trip; `forgetSession()` drops it.\nThe memo has no expiry by design — a session revoked elsewhere stays cached until a sign-out or a\nreload, which shows up as api calls answering 401 under a shell that still paints, never as access\na server denied. **Every code path that changes who is signed in calls `forgetSession()` before\n`router.invalidate()`** — invalidating first re-runs the guard against the stale cache and undoes\nthe sign-in or sign-out that just happened. `login.tsx` and `components\u002Fsign-out-button.tsx` both\nshow the order.\n\n`src\u002Flib\u002Fauth.ts` builds its client with `createAdminClient(apiBaseUrl)` from `@repo\u002Fauth\u002Fclient`, which talks to `\u002Fadmin\u002Fauth` with `credentials: \"include\"`. It keeps the export name `auth`, so a module screen that imports `auth` from `@admin\u002Flib\u002Fauth` reaches the admin session with no change. Never build this app's client with `createClient`: that is the client-group factory at `\u002Fauth`, and its session never opens this app.\n\nThe role string itself comes from better-auth's `admin()` plugin, which the `auth` module enables on both halves (`admin()` server-side, `adminClient()` in `adminAuthClientPlugins` in `packages\u002Fauth\u002Fsrc\u002Fclient.ts`). Drop the client half and `session.user.role` stops being typed.\n\n**The first account to sign up becomes the superadmin.** A `databaseHooks.user.create.before` hook in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` writes `role: \"superadmin\"` when the `users` table is still empty, so a fresh project reaches this shell without SQL. This app has no sign-up, and neither has the admin instance, so the first account signs up as a client on `\u002Fauth` (a client app's sign-up screen, or `POST \u002Fauth\u002Fsign-up\u002Femail`) and then signs in here with the same email and password. Every account after it keeps the plugin's `\"user\"` default, and this app's login refuses it until a superadmin grants an admin-group role. Client sign-up is open, so claim that first slot the moment the api answers; if somebody beat you to it, the recovery SQL in the `saasaloy-auth` skill flips the row. That skill owns the rule and the recovery path both.\n\n**A deep link survives the login hop.** The guard records the path it turned an anonymous visitor\naway from as `?redirect=` on `\u002Flogin`, and `login.tsx` navigates there after `forgetSession()` and\n`router.invalidate()`. `src\u002Flib\u002Fredirect.ts` decides whether that value may be used, and it has two\ngates: `toInternalPath` rejects anything a browser could read as another origin (`\u002F\u002Fhost`, `\u002F\\host`,\nan absolute url, a control character), and `resolveDestination` then asks the router itself, through\n`getMatchedRoutes(pathname)`, whether a route claims the path. Either failure falls back to `\u002F`. A\nnew screen needs nothing here — it is in the generated route tree, so it is already a valid\ndestination.\n\nThere is deliberately **no sign-up route** here, and `adminAuth` sets `disableSignUp: true`. An admin account is made by promoting an existing user, never by self-service at the backoffice door. Only a superadmin may grant `admin` or `superadmin` (the rank guard in the `saasaloy-auth` skill).\n\n## Add an admin write route, in four steps\n\n1. **Name the action.** Add an entry to your module's action file, `apps\u002Fapi\u002Fsrc\u002Faudit\u002F\u003Cmodule>.ts`: the route as `METHOD \u002Fadmin\u002F...` exactly as Hono lists it, the target type, the area, and a `label` such as \"Confirmed a payment\". Give one entry of a new area an `areaLabel`. A module ships that file with a `plugin-array` patch into `AUDIT_ACTIONS` in `apps\u002Fapi\u002Fsrc\u002Flib\u002Faudit-actions.ts`, the way `payment` and `feature-flags` do, so `saasaloy remove` takes the actions with the module.\n2. **Gate the route.** List `adminGate` first, then the validator, then a handler that opens with `adminWrite(c, async ({ db, actor, audit, afterCommit }) => ...)`. Use `db` for every query of the change. When Better Auth makes the change, use `adminAuthWrite(c, async ({ actor, audit }) => ...)` and call `adminAuth.api.*` with `headers: c.req.raw.headers`, so the plugin's permissions and `rank-guard` run as the caller.\n3. **Write the row.** Call `audit({ action, target: { id, label }, before, after })` once per change, with the fields the change touched. A create passes `after` only, a delete `before` only. Never pass a password: `adminWrite` throws on a key that matches `\u002Fpassword\u002Fi`, and `adminAuthWrite` drops it and logs at `error`. Put an email or any other side effect in `afterCommit`.\n4. **Prove it.** `audit-coverage.test.ts` fails until step 1 names the route, and `admin-gate.test.ts` fails if the validator runs before the gate. Neither proves the row is written, so add a route test beside the route that signs in a seeded admin, calls it, and reads `audit_events` for the row. `admin-members.test.ts` is the model.\n\n## What the D1 driver guarantees\n\nUnder `database-postgres`, `adminWrite` is one transaction. The change and its audit rows commit together, and a body that throws or answers 4xx keeps nothing.\n\nUnder `database-d1` there is no interactive transaction. Each statement of the body commits as it runs, and the audit rows go in one batch after it. A body that writes and then fails keeps its write and gets no row. A failed audit insert is logged at `error` and the change stands. Validate before you write, and a D1 route keeps nothing on a 4xx either. `adminAuthWrite` gives this weaker guarantee on both drivers, because Better Auth makes the change outside our transaction.\n\n## The members screen\n\n`src\u002Froutes\u002Fmembers.tsx` manages the admin group, the accounts in `ADMIN_ROLES`. Users lists every account; Members manages only the admin group. The api is `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-members.ts` at `\u002Fadmin\u002Fmembers`, and `membersQuery` in `src\u002Flib\u002Fmembers-query.ts` reads `GET \u002Fadmin\u002Fmembers`, which answers `{ me, members, removed }`. The route pages `listUsers` with a role filter until it has the whole group, so nothing is cut off at 100.\n\n- Active and Removed tabs. Removing a member bans the account and ends its sessions. The account keeps its id, so its audit rows still name a real person, and a restore unbans the same account with its password.\n- The Removed tab's \"Removed\" date and \"Removed by\" name come from the newest `member.remove` row. An account banned outside the screen falls back to `updatedAt` and no name.\n- \"Added by\" comes from the `member.add` row. \"Last sign-in\" is the newest admin session still on record. Better Auth deletes a session at sign-out, so the column shows a dash, never \"Never\".\n- A member changes their own name (`PATCH \u002F:id`, Better Auth's own `\u002Fupdate-user`) and password (`POST \u002F:id\u002Fpassword` with `currentPassword`, through `changePassword`; \"Sign out my other sessions\" is on by default, and the route passes the fresh session cookie back). A superadmin also adds members, resets another member's password (`setUserPassword`, then `revokeUserSessions`), removes, and restores. The route answers 403 for each of those before Better Auth runs, and self-removal answers 400.\n- The rank guard stands behind the route and is stricter: it refuses an `admin` any change to an admin-group account, so an `admin` who adds even an `admin` gets 403. The screen shows \"Add member\" and registers its command only for a superadmin; the 403 stays the server's rule.\n- Adding the email of a removed member answers 409 `member_removed` with the member, and the dialog offers a superadmin \"Restore \u003Cname>\".\n- The member panel lists the member's three newest changes as actor (`GET \u002Fadmin\u002Faudit-events?actor=\u003Cid>&limit=3`) and links to `\u002Factivity?actor=\u003Cid>`. The remove asks first in an alert dialog, and every save reports in a toast.\n\n## The Activity page\n\n`src\u002Froutes\u002Factivity.tsx` lists `audit_events` newest first, 50 rows a page, through `useInfiniteQuery` and a \"Load older\" button. The api is `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-audit.ts` at `\u002Fadmin\u002Faudit-events`, with `adminGate` before the validator on both routes.\n\n- `GET \u002Fadmin\u002Faudit-events` takes `actor`, `area`, `q`, `from`, `to`, `cursor` and `limit`, and answers `{ events, counts, areas, nextCursor }`. The cursor is `\u003CISO time>~\u003Cid>`, and any other cursor answers 400. `counts` holds `all` and each area under the filter minus the area, so a chip keeps its number when another chip is pressed.\n- `GET \u002Fadmin\u002Faudit-events\u002Fpeople` lists the person menu: the admin group plus every actor in the log, removed admins marked.\n- Each event carries `label`, the action's words from its action file, and `areas` carries each area's words. The page shows the label; the raw action key shows only in the detail panel. An action no module registers any more reads as its key.\n- The person, area and range live in the address through `validateSearch` (`activitySearch` in `src\u002Flib\u002Factivity.ts`). The search box narrows by target label 300 ms after the typing stops.\n- A row opens the detail panel with the exact time, the actor and role, the target, the action key, and a \"What changed\" table of each stored field before and after.\n\n## Extension seams\n\nSome module files take a project's own code through a seed file under `src\u002Fextend\u002F`. A seed file is written once and is then the project's: `saasaloy update` never changes it, and writes it again only when it is missing, because a managed file imports it. Put your change in the seed file and leave the managed file alone, and it keeps taking updates with no merge (ADR 0060).\n\n| Seed file | Shipped by | Read by | What goes in it |\n| --- | --- | --- | --- |\n| `src\u002Fextend\u002Froot.tsx` | `admin` | `src\u002Fcomponents\u002Fapp-shell.tsx` | `rootWrappers`, components that take `children`. AppShell renders `ShellLayout` inside each one, the first entry outermost, so the sidebar, the header and every page can read what a wrapper provides. They render inside the toast provider and only for a signed-in admin, never on `\u002Flogin` or the access-denied screen. |\n| `src\u002Fextend\u002Fpayments.ts` | `payment` | `src\u002Froutes\u002Fpayments.tsx` | `paymentsSearchExtension`, a zod object shape. `payments.tsx` spreads it into its `validateSearch` schema, so a key added here is typed on `Route.useSearch()` and on every link to `\u002Fpayments`. |\n\nA search key such as `payment: z.string().optional().catch(undefined)` keeps a malformed value in a pasted link from failing the screen. A key does nothing by itself: read it with `Route.useSearch()` in the screen, and that edit is the one change left in the managed file.\n\n`__root.tsx` takes no edit for a wrapper; `app-shell.tsx` applies them. The overview, `index.tsx`, has no seam yet.\n\n## The typed client\n\n`src\u002Flib\u002Fapi.ts` is the only place `hc` is called:\n\n```ts\nexport const api = hc\u003CAppType>(apiBaseUrl, {\n  headers: { \"x-auth-audience\": \"admin\" },\n  init: { credentials: \"include\" },\n});\n```\n\nFour properties are load-bearing:\n\n- **`AppType` is `apps\u002Fapi`'s route chain.** `api.health.$get()`, its path and its per-status\n  response shape all come from the route file. Change a response schema in `apps\u002Fapi` and this app\n  stops typechecking. Turbo runs `typecheck` across every workspace, so CI catches it.\n- **`apiBaseUrl` is imported from `src\u002Flib\u002Fauth.ts`**, not re-read from `import.meta.env`. The\n  session cookie is scoped to the api origin, so an api client bound elsewhere would send none.\n- **`init.credentials: \"include\"`** is why this file exists instead of a one-line `hc()` per call\n  site. `fetch` omits cookies cross-origin by default, so without it every request from `:3001`\n  arrives anonymous and the api answers 401.\n- **`x-auth-audience: admin`** names which of the browser's two sessions each call means. The browser sends both cookies to the api host, the client one included when a client is signed in on another app in the same browser. The `requireAdmin*` gates read the admin session whatever the header says, but a generic gate (`requireSession`, `requireTenant`, `authFor(c)`) reads the session the header names. Without it, a teams or subscription screen here would act as the client in the other tab. Any value other than `client` or `admin` gets 400.\n\n`@repo\u002Fapi\u002Fclient` is a **types-only** export (its `package.json` maps `.\u002Fclient` under a `types`\ncondition alone), which is why `@repo\u002Fapi` is a `devDependency`. No Worker code enters this bundle.\n\n### Why `@cloudflare\u002Fworkers-types` is in this app's `types`\n\n`tsconfig.json` lists `\"types\": [\"@cloudflare\u002Fworkers-types\", \"vite\u002Fclient\"]`, and the first entry\nlooks wrong in a browser-only SPA. It is not.\n\nImporting `AppType` makes `tsc` read **apps\u002Fapi's whole source graph**, because the type *is* that\ngraph. That graph includes the auth handler api mounts, which imports `cloudflare:workers` and\nannotates a `D1Database`. Without the ambient Workers types, those declarations fail to resolve and\nthe errors surface **here**, in `apps\u002Fadmin`, pointing at files in `apps\u002Fapi` that admin never\nbundles a byte of.\n\nSo: **an admin typecheck error whose path starts `apps\u002Fapi\u002F` is usually not an admin bug.** Add a\nWorker-only dependency to the api and read the error where it is reported, not where it is thrown.\nThe fix is nearly always in `apps\u002Fapi` (or in another ambient type this app must declare), never a\nchange to `src\u002Flib\u002Fapi.ts`. The entry is types only; there is no runtime dependency on the Workers\nruntime in this app.\n\n### Why the two TanStack Router pins carry different numbers\n\n`@tanstack\u002Freact-router` is pinned at `1.170.32` and `@tanstack\u002Frouter-plugin` at `1.168.35`, which reads like drift and is not. TanStack releases the two on independent version lines, and `router-plugin@1.168.35` names `\"@tanstack\u002Freact-router\": \"^1.170.32\"` in its own `peerDependencies` — the pins are the matching pair, they just do not share a number. Do not \"fix\" the mismatch by inventing a `router-plugin@1.170.32`; no such release exists. Check the plugin's `peerDependencies` against the router pin instead, and move both together when `pnpm deps:update` offers a bump.\n\n## Loader + Query, and why both\n\n`src\u002Fmain.tsx` creates one `QueryClient` at module scope and puts it on the **router context**, so a\nroute's `loader` prefetches through the same cache the component then reads:\n\n```tsx\nconst router = createRouter({ routeTree, context: { queryClient }, defaultPreload: \"intent\" });\n```\n\n`ensureQueryData` in the loader starts the request while the route resolves, and `defaultPreload:\n\"intent\"` starts it on hover, so the cache is warm before the component mounts. The component still\nreads through `useQuery` rather than the loader's return value, because `useQuery` **subscribes**:\nan invalidation anywhere in the app re-renders the screen.\n\nRefresh by **invalidating the key**, not by calling `refetch()`. `invalidateQueries({ queryKey })`\nrefreshes every screen holding that query, and it is the same call a mutation's `onSuccess` makes.\n\nThe scaffold's defaults are `retry: 1` and `staleTime: 30_000` — backoffice numbers, not universal\nones. An admin clicks between a handful of screens, so a short stale window keeps a revisit instant,\nand one retry absorbs a dropped packet without sitting on a down api for seconds.\n\nA data route needs no `errorComponent` of its own: the router's default renders the shell `ErrorState` for a loader's throw and for a render failure. Add one only when the words should say more, as `\u002Fusers` and the overview do.\n\nThe overview at `\u002F` is the exception to awaiting in the loader. Its loader calls `prefetchQuery` for `\u002Fhealth` and for `newestUsersQuery` and awaits neither, so the page paints at once, and each card renders its own skeleton, its data, or its own failure. A down api shows \"Unreachable\" in the health card and never swaps the page for an error screen. Copy that shape for a dashboard whose cards read separate requests; await in the loader for a screen that is one list.\n\n## Theme and font\n\n**The admin app carries its own theme file.** This module writes `packages\u002Fui\u002Fsrc\u002Fstyles\u002Fadmin.css`, beside the web app's `brand.css`. It imports the shared `globals.css`, which owns Tailwind's entrypoint, the `@source` globs and the base layer and holds no token values. `admin.css` then imports the `shell` module's `shell.css` and declares the `dark` custom variant, this app's `:root` and `.dark` values, and its own `@theme inline` colour mapping and radius scale. The variant and the mapping repeat `brand.css`'s on purpose: each theme file holds its own, so a shadcn preset aimed at `brand.css` never reaches this app.\n\nThat `shell.css` import is load-bearing. It holds the `@source` line for `components\u002Fshell\u002F`, the colour mapping for the status tokens, and the skeleton and toast motion. Drop it and every shell primitive renders unstyled with no error. See the `saasaloy-shell` skill.\n\n`src\u002Fmain.tsx` imports `@repo\u002Fui\u002Fstyles\u002Fadmin.css` and the Inter font package, and nothing else. That import needs the `\".\u002Fstyles\u002F*\": \".\u002Fsrc\u002Fstyles\u002F*\"` export in `packages\u002Fui\u002Fpackage.json`, which the base template ships from the theme split onward. A project made before the split lacks it, and the admin build then fails to resolve `@repo\u002Fui\u002Fstyles\u002Fadmin.css`. Run `saasaloy update` for the base and follow the steps in [Finish the theme split](https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fdocs\u002Fwiki\u002Frunbooks\u002Ffinish-the-theme-split.md) first. **No route imports a stylesheet.** Two Tailwind entrypoints in one bundle means two copies of the base layer and a token set whose winner depends on import order.\n\nThe palette is a three-step neutral ramp measured off the reference screenshots — canvas darkest, panel one step lighter, hover and selected one step lighter again — with alpha hairlines over it: white at 8 % on dark, black at 8 % on light, and inputs a step stronger. The measured values are written into the header comment of `admin.css` beside the roles they fill; change a value there and update the comment with it. Light is a mapped variant on a neutral grey canvas and is first-class, not a fallback.\n\n`apps\u002Fadmin\u002FDESIGN.md` records these tokens and the rules behind them, and fingerprints `admin.css`. After you change `admin.css`, run the `saasaloy-design` skill's `update` flow for the admin app. A theme preset never targets `admin.css`; it reaches the web app only.\n\nBeyond the shadcn set, `admin.css` sets this app's values for the tokens `shell.css` declares and maps: the status pairs the primitives read (`--success`, `--warning`, `--info` and `--destructive-foreground`, each a fill tone and a darker text tone) and two accents. Each one replaces a neutral default in `shell.css`, in `:root` and in `.dark`:\n\n- `--status-open` (and `--status-open-foreground`) — the muted blue of `StatusPill`'s `open` tone and of a primary circular action.\n- `--status-ok`, `--status-warn` and `--status-bad` (each with a `-foreground`) — `StatusPill`'s `ok`, `warn` and `bad` tones. They copy the `--success`, `--warning` and `--destructive` values, and they exist so a theme preset, which sets `--destructive` and `--destructive-foreground` with another meaning, never repaints a status. No preset sets a `status-*` key.\n- `--accent-sort` — the orange on `DataTable`'s active sort header. It is reserved for one indicator at a time and for an AI surface. It is never a section background, and `StatusPill` deliberately has no orange tone.\n\n**Dark by default, and every stored choice wins — `system` included.** `applyStartingTheme()` in `src\u002Fmain.tsx` runs above `createRoot` and is one line: `setTheme(hasChosenTheme() ? getStoredTheme() : \"dark\")`.\n\nThe `theme` key alone cannot carry this. `setTheme(\"system\")` DELETES it — that is how `@repo\u002Fui`'s state machine spells \"follow the OS\", and the landing page depends on it — so a first visit and a deliberate `system` both read as an absent key. `hasChosenTheme()` separates them by reading a second key, `theme-chosen`, which `installThemeToggle()` writes on every press and nothing clears. Never chosen means dark; chosen with no `theme` key means `system`, resolved against the OS.\n\n`index.html` emits no `THEME_INIT_SCRIPT` — that is the Astro host's mechanism, and there is no Vite plugin here. The trade is one frame of the light palette on an empty body before the entry module runs. `main.tsx` calls `installThemeToggle()` from `@repo\u002Fui\u002Flib\u002Ftheme` instead, for the OS listener that script would otherwise install. The Theme submenu below sets the theme itself.\n\n`ThemeMenuItem` is a \"Theme\" submenu (`MenuSub`, `MenuSubTrigger`, `MenuSubPopup`) with one `MenuRadioItem` per entry in its `THEME_OPTIONS` list. A pick calls `setTheme(value)` inside `revealTheme`, then writes `THEME_CHOICE_KEY`, so the starting-theme rule in `main.tsx` keeps the choice on the next load, `system` included. It does not use the delegated `[data-theme-toggle]` handler, because that handler only flips light and dark. The current choice is the `data-theme` attribute on `\u003Chtml>`, which `setTheme` writes, read through a `MutationObserver`. To add a theme, teach `@repo\u002Fui\u002Flib\u002Ftheme` to apply it, then add one entry to `THEME_OPTIONS`. `main.tsx` still calls `installThemeToggle()` for its OS listener, which repaints a visitor on `system` when the OS changes.\n\n### The font this app adds\n\n- **`@fontsource-variable\u002Finter`** is a runtime `dependency` of this app, imported from `src\u002Fmain.tsx` beside `admin.css`, and set as `--font-sans` in a `@theme` block in `admin.css`. The import stays in the app because Tailwind resolves a CSS `@import` from the stylesheet's own folder, and `packages\u002Fui` does not depend on the font. It is the app's only face; no mono font is loaded. The body enables Inter's `cv11` and `ss01` sets; `shell.css` adds `tabular-nums`.\n\nIt is exact-pinned. Template and module-descriptor dependencies are invisible to pnpm, so move it with `pnpm deps:update` and never by hand-typing a version. `@tanstack\u002Freact-table` belongs to the `shell` module now; see `saasaloy-shell`.\n\n## Ports and CORS\n\n| Service | Port | Pinned in |\n|---|---|---|\n| `apps\u002Fweb` (Astro) | **3000** | `astro.config.mjs` |\n| `apps\u002Fadmin` (this app) | **3001** | `vite.config.ts` (`server.port` + `strictPort`) |\n| `apps\u002Fapi` (Worker) | **4000** | `vite.config.ts` and `wrangler.jsonc` (`dev.port`) |\n\n`3001` is not cosmetic. The api's `DEV_ORIGINS` allowlist and better-auth's `trustedOrigins` both\nhardcode `http:\u002F\u002Flocalhost:3001` as the keyless dev fallback, so a drifting port turns into a CORS\nrejection that reads like a code bug. `strictPort` makes a busy port fail loudly instead of quietly\nshifting to `3002`, the port `apps\u002Fapp` holds.\n\nIn production the origin comes from `PUBLIC_API_URL`, and the api needs the admin origin in\n`CORS_ORIGINS`. The prefix is `PUBLIC_` rather than Vite's default `VITE_` (`envPrefix` in\n`vite.config.ts`), so the bundle only inlines a variable a human deliberately named `PUBLIC_*`, and\none env key spells the api origin for `web`, `admin` and `waitlist` alike. Unset or empty, it falls\nback to `http:\u002F\u002Flocalhost:4000`.\n\nCookie behaviour is the `auth` module's (ADR 0004). Cross-origin dev works because api's `cors()` sets `credentials: true` for the allowlisted origins and the cookie is host-only on `localhost`. Cookies ignore the port, so `:3000` and `:3001` see the same jar; the names `client.session_token` and `admin.session_token` are what keep a client sign-in on the web app from replacing this app's session. In\nproduction, put the api and the admin app on sibling subdomains and set `COOKIE_DOMAIN`.\n\n## Run it\n\n```sh\npnpm --filter @repo\u002Fapi dev    # :4000, the real workerd runtime\npnpm --filter @repo\u002Fadmin dev  # :3001\n```\n\nBoth, in two terminals. Admin on its own serves a login screen that cannot sign anyone in.\n\n## Deploy\n\nStatic assets on a Worker, exactly like `apps\u002Fweb`:\n\n```sh\npnpm --filter @repo\u002Fadmin build           # vite build → dist\u002F\npnpm --filter @repo\u002Fadmin exec wrangler deploy --dry-run\n```\n\n`wrangler.jsonc` declares `assets.directory: \".\u002Fdist\"` with\n`not_found_handling: \"single-page-application\"` and **no `main`**. The SPA fallback is what makes a\nhard reload of `\u002Flogin` work; without it the request 404s, because no such file exists in `dist\u002F`.\nThere are no bindings, and there should not be — the session and the database are reached through\n`apps\u002Fapi` over HTTP.\n\nSet `PUBLIC_API_URL` at **build** time, not on the Worker. Vite inlines it into the bundle, so a\nruntime variable would arrive too late to matter.\n\n`pnpm deploy:production` deploys this app with every other Worker. Its `deploy` script is\n`env-deploy admin`, which builds with the `admin` service's production values in the\nenvironment, so the bundle inlines the production `PUBLIC_API_URL` and the dev `.env` stays as it\nis. The app is assets-only, so it gets no secrets.\n\n`saasaloy add admin` appends `{ service: \"admin\", order: 20 }` to `DEPLOY_TARGETS` in `packages\u002Ftooling\u002Fsrc\u002Ftargets.ts`, so the admin deploys after the api it calls and before the web. It also appends the `admin-home` smoke check, `GET \u002F` with a 200, which runs once `apps\u002Fadmin\u002Fwrangler.jsonc` has a `routes[]` entry with `custom_domain: true`. `pnpm deploy:production --only admin` deploys this app alone after the gates. See the `saasaloy-deploy` skill.\n\n## Removing the module\n\n`saasaloy remove admin` deletes the files **this module** installed and prunes the directories that\nleaves empty. A route file another module dropped into `src\u002Froutes\u002F` is that module's, so it\nsurvives, and `apps\u002Fadmin\u002F` survives with it as a half-workspace: no `package.json`, no\n`vite.config.ts`, a stale `src\u002FrouteTree.gen.ts`, and the `@admin` alias still in `saasaloy.json`\nbecause its prefix directory did not vanish.\n\n**Remove the feature modules that dropped routes first, then `admin`.** Otherwise delete the\nleftovers by hand before re-adding, or the next `add admin` restores a workspace around orphaned\nfiles.\n\n## Conventions to honor\n\n- **A screen is a file drop** under `src\u002Froutes\u002F`, never a patch. Let the plugin rewrite\n  `src\u002FrouteTree.gen.ts`; never hand-edit it.\n- **`tanstackRouter()` stays ahead of `react()`** in `vite.config.ts`.\n- **A screen composes the shell blocks.** Start from `PageHeader` and `PageLayout` or `PageBody`; do not write shell markup, table markup, padding, or a page width of your own.\n- **Admin code imports the shell set only.** `@repo\u002Fui\u002Fcomponents\u002Fshell\u002F*`, `blocks\u002Fshell\u002F*` and `containers\u002Fshell\u002F*`; the lint rule fails a base primitive.\n- **A block takes plain props and callbacks.** Nothing in `@repo\u002Fui` imports `@repo\u002Fapi`, `hono\u002Fclient`, `@admin\u002Flib\u002Fapi`, a router, or reads `import.meta.env`.\n- **`@tanstack\u002Freact-table` is imported by `data-table.tsx` and by nothing else.** A route that imports a `ColumnDef` has skipped the wrapper the next screen depends on.\n- **Every mutation reports through a toast**, a destructive one confirms in an `AlertDialog` first, and a create flow opens in a `Dialog`.\n- **`NAV_AREAS` stays `as const`.** That literal type is what turns a nav entry for a missing route\n  into a typecheck failure instead of a 404.\n- **One theme file, `@repo\u002Fui\u002Fstyles\u002Fadmin.css`, imported once from `src\u002Fmain.tsx`.** A second Tailwind\n  entrypoint duplicates the base layer and makes the token set order-dependent.\n- **Dark is the default, and a stored choice wins.** Gate it on `hasChosenTheme()`. `getStoredTheme()`\n  alone cannot tell an unset key from a deliberate `system`, because `system` is spelled as no key.\n- **Orange is `--accent-sort` and nothing else.** One active sort indicator, or an AI surface. Never\n  a section background and never a status pill.\n- **Loading, not-found and error screens come from the app.** Inherit the router defaults and `__root.tsx`'s `notFoundComponent`; override a route's `errorComponent` only for better words, and do not write error markup outside the shell `ErrorState`.\n- **One `hc` call, in `src\u002Flib\u002Fapi.ts`.** Import `api`; do not build a second client, and do not drop its `x-auth-audience: admin` header.\n- **The auth client is `createAdminClient`.** `src\u002Flib\u002Fauth.ts` exports it as `auth`; never swap in `createClient`.\n- **`\u002Fadmin\u002Fauth\u002F*` belongs to the admin auth instance.** An api route or middleware this app adds under `\u002Fadmin\u002F*` must not claim or gate it.\n- **One origin for api and auth**, from `src\u002Flib\u002Fauth.ts`'s `apiBaseUrl`. A split origin loses the\n  session cookie.\n- **The guard lives in `__root.tsx`'s `beforeLoad`**, and it is default-deny. A per-route session\n  check is redundant, because every deny there is a throw and no child loader runs after one. Keep\n  it that way: a deny that returns instead of throwing silently re-opens the loaders it was meant to\n  stop. Do not turn `AccessDenied` into a redirect either.\n- **`adminGate` comes before every validator on an admin route.** A validator listed first answers a signed-out caller with a 400 that describes the input. `admin-gate.test.ts` fails on it.\n- **Project code goes in `src\u002Fextend\u002F`, not in a managed file.** A wrapper goes in `rootWrappers`, a payments search key in `paymentsSearchExtension`. An edit in place sends the file to the merge plan on every update.\n- **Every admin endpoint calls `requireAdmin` or `requireAdminApp`**, whatever the guard in `__root.tsx` does. The screen inheriting `beforeLoad` is not authorization; it is the reason a missing server check looks fine in a browser.\n- **`forgetSession()` before `router.invalidate()`**, on every sign-in and sign-out path.\n- **Describe a request once with `queryOptions`**, prefetch in the loader, read with `useQuery`,\n  refresh by invalidating the key.\n- **Browser env vars are `PUBLIC_*`.** A `VITE_*` name is not exposed here.\n- **No bindings and no Worker entry.** Anything needing D1, R2 or a secret belongs in `apps\u002Fapi`.\n\n## Next\n\nRun `saasaloy-feature` to build the first product entity end to end, with its list on an admin screen.\n","# admin — the role-gated backoffice SPA\n\n`apps\u002Fadmin` (`@repo\u002Fadmin`) is a plain browser bundle: [TanStack Router](https:\u002F\u002Ftanstack.com\u002Frouter)\nover Vite, built to static assets and served by a Worker with a single-page-application fallback.\nIt carries **no server code and no Cloudflare bindings**. Everything it knows, it asks `apps\u002Fapi`\nfor over the credentialed CORS spine, which is why it `dependsOn: [\"api\", \"auth\"]`. Its frame,\nprimitives and blocks come from the `shell` module, its third dependency.\n\nThree conventions define it, and the first two are file drops rather than patches:\n\n- **A screen is a file** under `src\u002Froutes\u002F`. The router plugin regenerates `src\u002FrouteTree.gen.ts`\n  and the screen is live, guarded, and typed — no descriptor patch, the admin twin of the schema\n  barrel in `packages\u002Fdb`.\n- **A request is a `queryOptions` object**, prefetched in the route's `loader` and read in the\n  component with `useQuery`, over a single `hc\u003CAppType>` client.\n- **A screen composes the shell blocks and primitives** in `@repo\u002Fui`, which the `shell` module writes into `packages\u002Fui\u002Fsrc\u002F{components,blocks,containers,lib}\u002Fshell\u002F`. It writes no shell markup, no table markup, no page padding and no colours of its own. The `saasaloy-shell` skill is the reference for the set.\n\n## Add a screen\n\nDrop `src\u002Froutes\u002F\u003Cfeature>.tsx` with a `createFileRoute` whose id matches the file path:\n\n```tsx\n\u002F\u002F src\u002Froutes\u002Fwidgets.tsx  →  \u002Fwidgets\nimport { queryOptions, useQuery } from \"@tanstack\u002Freact-query\";\nimport { createFileRoute } from \"@tanstack\u002Freact-router\";\n\nimport { DataTable } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fdata-table\";\nimport { EmptyState } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fempty-state\";\nimport { PageHeader } from \"@repo\u002Fui\u002Fblocks\u002Fshell\u002Fpage-header\";\nimport { PageLayout } from \"@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fpage-layout\";\n\nimport { api } from \"@admin\u002Flib\u002Fapi\";\n\nconst widgetsQuery = queryOptions({\n  queryKey: [\"widgets\"],\n  queryFn: async () => {\n    const res = await api.widgets.$get();\n    if (!res.ok) throw new Error(`The api answered ${res.status}.`);\n    return res.json();\n  },\n});\n\nexport const Route = createFileRoute(\"\u002Fwidgets\")({\n  loader: ({ context }) => context.queryClient.ensureQueryData(widgetsQuery),\n  component: Widgets,\n});\n\nfunction Widgets() {\n  const { data } = useQuery(widgetsQuery);\n  \u002F\u002F `useQuery` types `data` as `T | undefined` and the repo compiles with `strict`, so read\n  \u002F\u002F it through `?.` even when the loader has already filled the cache.\n  return (\n    \u003CPageLayout>\n      \u003CPageHeader title=\"Widgets\" count={data?.total} \u002F>\n      \u003CDataTable\n        caption=\"Widgets\"\n        columns={COLUMNS}\n        rows={data?.widgets ?? []}\n        rowId={(widget) => widget.id}\n        emptyState={\u003CEmptyState title=\"No widgets yet\" \u002F>}\n      \u002F>\n    \u003C\u002FPageLayout>\n  );\n}\n```\n\n```\n\nThat is the whole registration. The file is a child of `src\u002Froutes\u002F__root.tsx`, so it inherits the\nshell and the access gate with no work of its own. `src\u002Froutes\u002Fusers.tsx` is the worked example in\nthe scaffold; copy from it.\n\nEvery route renders inside the page frame (`@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fpage-frame`), which the root route wraps around `\u003COutlet \u002F>`. The frame owns the height and the gutter: it sets `--page-gutter`, and `PageHeader`, `PageBody`, toolbar rows (`px-(--page-gutter)`) and the table's first and last columns pad with it. A route never sets its own page width, background or padding. A screen that reaches for `mx-auto max-w-3xl` or `p-6` is fighting the frame, and the next change to the gutter will skip it.\n\nThree things the plugin owns, so do not hand-write them:\n\n- **`src\u002FrouteTree.gen.ts`.** `@tanstack\u002Frouter-plugin` rewrites it whenever a file under\n  `src\u002Froutes\u002F` appears or disappears. It is committed rather than ignored, so `tsc --noEmit` and a\n  fresh `pnpm build` work on a clean checkout before Vite has ever run. Edit routes, not the tree.\n  A module that drops a route file leaves the committed tree one route behind, so the `typecheck`\n  script runs `tsr generate` before `tsc`. `tsr.config.json` holds the generator options, and the\n  plugin and the CLI both read it, so the two write the same file.\n- **The route id string.** `createFileRoute(\"\u002Fwidgets\")` is derived from the file's path. Rename the\n  file and let the plugin rewrite the call; changing one without the other breaks the build.\n- **Plugin order in `vite.config.ts`.** `tanstackRouter()` runs before `react()`. Reversed, the\n  code-split rewrite lands on already-transformed output and the generated tree goes stale.\n\nLoading, not-found and error handling come with the app as well:\n\n- `src\u002Fmain.tsx` sets `defaultPendingComponent` to the `PageSkeleton` block and `defaultErrorComponent` to `RouteError` (`src\u002Fcomponents\u002Froute-error.tsx`), which renders the shell `ErrorState` with a retry and the error's message. Every route gets a skeleton while its loader runs and an error screen when it throws, inside the frame, with no code of its own.\n- `__root.tsx` carries a `notFoundComponent` and an `errorComponent` that render the same shell `ErrorState`, so an unknown address shows the themed 404 inside the shell.\n\nA route sets its own `errorComponent` only when its words should differ, as `\u002Fusers` and the overview do. Never register a second `notFoundComponent`: it captures every miss below it. Change the words in `packages\u002Fui\u002Fsrc\u002Fcontent\u002Ferrors.ts`, not in a new component. The router types `error` as `unknown`, so read a message with `error instanceof Error ? error.message : undefined` and pass it as `detail`.\n\nPutting the screen in the sidebar is a separate, optional step. See [The shell](#the-shell) below.\n\n## The shell\n\nEvery route except `\u002Flogin` renders inside `src\u002Fcomponents\u002Fapp-shell.tsx`, and so does every screen except the refusal page (`AccessDenied`, see [The gate](#the-gate-a-session-is-never-enough)). That file reads the router and the session and hands them to `ShellLayout` in `@repo\u002Fui\u002Fcontainers\u002Fshell\u002Fshell-layout`, which imports no router and no session:\n\n| Part | File | What it holds |\n|---|---|---|\n| Sidebar | `containers\u002Fshell\u002Fshell-sidebar.tsx` | the brand row (`BrandMark` and the product name), the organization picker's empty slot for #141, every area's nav groups, and the account menu at the foot with the name, the email and sign-out |\n| Content panel | `containers\u002Fshell\u002Fshell-layout.tsx` | a sticky header with the sidebar toggle and the page path, then the route inside the page frame |\n\nThe sidebar is the coss sidebar from the shell set, `variant=\"inset\"` and `collapsible=\"icon\"`. It sits on the canvas; the content panel is the one raised surface beside it. The header toggle and ⌘B \u002F Ctrl+B collapse it to a 56 px icon strip, where each row shows its label in a tooltip. Below `md` it opens as a sheet from the same toggle, and following a link closes the sheet. The open state is component state only, never storage, so a reload lands on the expanded sidebar.\n\nActive state is `aria-current`. `AppShell`'s link component wraps TanStack Router's `Link`, which sets `aria-current=\"page\"` on the active row, and the sidebar row styles that attribute. There is no second \"which page am I on\" comparison to keep in step. The page path in the header is the area's label and the label of the nav item whose `to` is the longest prefix of the current path.\n\n### Add a nav group or an area\n\n`NAV_AREAS` in `src\u002Fcomponents\u002Fnav.ts` is the one list to edit:\n\n```tsx\nexport const NAV_AREAS = [\n  {\n    label: \"Admin\",\n    to: \"\u002F\",\n    icon: LayoutDashboardIcon,\n    groups: [\n      {\n        label: \"Manage\",\n        items: [\n          { to: \"\u002F\", label: \"Overview\", icon: GaugeIcon, shortcut: \"G O\" },\n          { to: \"\u002Fusers\", label: \"Users\", icon: UsersIcon, shortcut: \"G U\" },\n        ],\n      },\n    ],\n  },\n] as const;\n```\n\n- **A new nav row** is one entry in an existing group's `items`. It needs `to`, `label` and `icon`, and takes an optional `count` and an optional `shortcut`, `G` then a letter written as `\"G R\"`. Pick the letter by hand and keep it unique; the tool repo's `commands.test.ts` fails on two rows with one shortcut, and the `command` module reports a conflict. A feature module adds its row with a `nav-entry` patch.\n- **A new group** is one entry in an area's `groups`, with a `label` and its own `items`. The sidebar renders it under the ones above it, with its label.\n- **A new area** is one entry in `NAV_AREAS`. The sidebar lists every area's groups in order, and `areaFor(pathname)` picks the area whose label starts the header's page path.\n\nKeep the `as const`. It is what holds every `to` at a literal type the router can check, so a nav entry naming a route that does not exist fails `pnpm typecheck` instead of 404-ing in the browser. The shell in `@repo\u002Fui` reads the entries through structural types with `to: string`; the one cast from that string back to a route lives in `AppShell`'s link component.\n\nEvery row becomes a \"Go to \u003Clabel>\" command in `src\u002Fcomponents\u002Fcommands.ts`, next to sign out and the three theme choices. `AppShell` declares them in the `global` scope, and a page declares its own with `useCommands(commands, { scope: \"route\", label })`, as `src\u002Froutes\u002Fusers.tsx` does for its filters. They do nothing until the `command` module is installed; see \"Declare a screen's commands\" in the `saasaloy-shell` skill. `src\u002Fcomponents\u002Fshell-extensions.ts` is the list a module such as `command` appends itself to; keep its `extensions` property even while it is empty.\n\n`nav.ts` holds the data and the rules that read it, and nothing else, so its rules stay unit-testable without React. Read an optional count through the `navCount(entry)` helper rather than `entry.count`.\n\n### Add a live count to a nav row\n\nA static `count` in `NAV_AREAS` is a number fixed at build time. A number that changes, such as how many payments wait for a review, is a live count. `NAV_COUNTS` in `src\u002Fcomponents\u002Fnav-counts.ts` lists them, one `{ to, path }` per row. `to` is the row's `to` in `NAV_AREAS`. `path` is an api path that answers `{ count: number }` behind the admin session.\n\nA module adds its entry with a `const-array` patch keyed on `to`. The payment module's patch is the example:\n\n```json\n{\n  \"file\": \"apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav-counts.ts\",\n  \"kind\": \"const-array\",\n  \"constName\": \"NAV_COUNTS\",\n  \"key\": \"to\",\n  \"entry\": { \"to\": \"\u002Fpayments\", \"path\": \"\u002Fadmin\u002Fpayment\u002Freview-count\" }\n}\n```\n\n`AppShell` runs one TanStack query per entry under the key `[\"nav-count\", to]`. Each query fetches `PUBLIC_API_URL` plus `path` with the session cookie and `x-auth-audience: admin`, the same `API_HEADERS` and `API_CREDENTIALS` that `src\u002Flib\u002Fapi.ts` gives the typed client. The queries refetch on window focus and every 60 s, and TanStack Query does not run the interval in a hidden tab. `AppShell` passes the numbers to `ShellLayout` as `counts`, keyed by `to`.\n\nThe sidebar applies `withLiveCounts` from `@repo\u002Fui\u002Flib\u002Fshell\u002Fnav-counts`:\n\n- A live count replaces the row's static `count`.\n- A live 0 hides the badge. A static 0 still renders.\n- Before the first successful fetch the static `count` stays.\n- A failed fetch (a network error, a non-OK answer or a body without a numeric `count`) throws, so TanStack Query keeps the last count it read. The badge never drops to 0 or disappears because of a failure, and a failed count shows no error.\n\nA screen whose action changes a count invalidates the key after the mutation, so the badge follows with no reload:\n\n```ts\nawait queryClient.invalidateQueries({ queryKey: [\"nav-count\", \"\u002Fpayments\"] });\n```\n\nKeep the route that answers the count cheap: the shell calls it on every focus and every minute while the tab is open.\n\n## The shell primitive set and the page blocks\n\nThe `shell` module writes the UI kit this app uses into `packages\u002Fui\u002Fsrc\u002F{components,blocks,containers,lib}\u002Fshell\u002F`, and admin code uses nothing else. The `saasaloy-shell` skill lists every primitive and block, their props, the `DataTable` column shape and the lint rule. Two admin-only facts sit here:\n\n- `ShellLayout` keeps its `subtitle` prop at the default, `\"Admin\"`, the line under the product name.\n- The router's defaults render the shell `ErrorState` and `PageSkeleton`, and `__root.tsx` mounts the toast provider for `toastManager` from `components\u002Fshell\u002Ftoast`.\n\n## The users screen, end to end\n\n`src\u002Froutes\u002Fusers.tsx` is the worked example, and every row in it is real data from `GET \u002Fadmin\u002Fusers`.\n\n- `usersQuery` in `src\u002Flib\u002Fusers-query.ts` is a `queryOptions` over `api.admin.users.$get({ query: {} })`, keyed `[\"admin\", \"users\"]`. `newestUsersQuery` beside it asks `?limit=5&sortBy=createdAt&sortDirection=desc` for the overview and is keyed `[\"admin\", \"users\", \"newest\"]`, so invalidating `usersQuery.queryKey` refreshes both.\n- `GET \u002Fadmin\u002Fusers` takes `limit` (1 to 100, default 100), `sortBy` (`createdAt` or `name`) and `sortDirection` (`asc` or `desc`), validated after `adminGate`, and passes them to `listUsers`. `total` is always the count of every account.\n- The row type is derived from the query's own return type, so a field dropped in `apps\u002Fapi` lands as a typecheck failure here.\n- `PageHeader` shows `data.total`, the api's count. The endpoint caps its answer at 100 users, so the loaded page and the real total can differ.\n- `FilterChips` narrows the loaded rows by role, in the component, with no refetch.\n- `DataTable` renders name with an avatar, email, role as a `StatusPill`, verified as an `ok` or `warn` `StatusPill`, and created. The columns are a module-scope constant.\n- An empty list shows one `EmptyState`, and a list filtered to nothing shows another with a \"Show all users\" button.\n- The selected user is `useState` in the route. The route builds the `DetailPanel`, with the role pill in its `status` slot, and hands it to `PageLayout` as `detail`.\n- `UsersError` is the worked example of a route overriding the router's default error screen.\n\nCopy that split when you add a screen: **the route owns the state and the data, the blocks own the pixels.**\n\n## The gate: a session is never enough\n\nThis app signs in on the **admin session**: `adminAuth` at `\u002Fadmin\u002Fauth`, cookie `admin.session_token`. A client signed in on another app in the same browser holds `client.session_token`, which this app never reads, so the two stay signed in side by side. See \"Two instances\" in the `saasaloy-auth` skill.\n\n`src\u002Froutes\u002F__root.tsx` decides access in `beforeLoad`, top-down, before any child route's `loader` fires. Three outcomes and no fourth:\n\n| Visitor | Outcome |\n|---|---|\n| No admin session (anonymous, or signed in only as a client) | `throw redirect({ to: \"\u002Flogin\", search: { redirect: location.href } })`, except on `\u002Flogin` itself |\n| Admin session, role not in `ADMIN_APP_ROLES` | `throw new NotAdminError(session)` → the root `errorComponent` renders `AccessDenied` **in place**, alone, without `AppShell` |\n| Admin session, role in `ADMIN_APP_ROLES` | the shell renders |\n\n`isAdmin` in `src\u002Flib\u002Fauth.ts` makes the check against `ADMIN_APP_ROLES`, the browser copy of the list in `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts`. A project that adds a role such as `support` to the admin group adds it to both copies; the `saasaloy-auth` skill has the recipe.\n\nThe middle row is rare. `adminAuth` refuses to open a session for an account outside `ADMIN_APP_ROLES`, with \"Invalid email or password\" on the login screen, so a client account never gets this far. The row is for an account whose role a superadmin removed after it signed in. It still holds a valid admin session, so redirecting it to `\u002Flogin` sends it straight back the moment the guard reads it, and the address bar ping-pongs. It gets a terminal panel with a sign-out button instead.\n\n`AccessDenied` (`src\u002Fcomponents\u002Faccess-denied.tsx`) renders on its own, centered on the login screen's card, with no sidebar, header or user menu. The shell names every screen this app has, which a refused account has no reason to learn. The panel is the page's `\u003Cmain>`, because no shell gives it one. `NotAdminError` keeps the session only so the panel can name the signed-in email.\n\n**Every deny is a throw, and that is load-bearing.** `beforeLoad` runs before any loader, but only a\nthrow ends the match; a `beforeLoad` that returns normally lets every matched route's `loader` run.\nSo the non-admin case is a thrown `NotAdminError` (exported from `__root.tsx`) that the root route's\n`errorComponent` turns into the panel, not a role check inside the component. Deny it in the\ncomponent instead and the loaders of the route the visitor asked for fire first, on their cookie,\nbefore the panel paints. Keep the check in `beforeLoad` and no child loader runs for anyone the\nguard turns away.\n\n### This guard is the second half of the gate\n\nThe first half is `requireAdmin` (or `requireAdminApp`) in `@repo\u002Fauth\u002Fserver`, and the api route is where it runs. Both read the admin session whatever the request's `x-auth-audience` header says. Use `requireAdmin` for admin-only work and `requireAdminApp` for a route every admin-app role may call, `support` included when a project adds it. `beforeLoad` stops this app from asking on a denied visitor's behalf; it cannot stop `curl`, a stale bundle, or a second client someone writes against the same api. Ship a new admin route and you wire both halves or you have shipped neither:\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Freports.ts — the server half\nimport { Hono } from \"hono\";\nimport { adminGate, requireAdmin } from \"@repo\u002Fauth\u002Fserver\";\n\nexport const reports = new Hono()\n  .get(\"\u002F\", adminGate, async (c) => {\n    await requireAdmin(c);\n    return c.json({ reports: await listReports() }, 200);\n  })\n  .post(\"\u002F\", adminGate, validReport, async (c) => {\n    const session = await requireAdmin(c);\n    return c.json(await createReport(c.req.valid(\"json\"), session.user.id), 201);\n  });\n```\n\n`adminGate` goes first on every admin route, before any validator. Hono runs a route's handlers in the order they are listed, so a validator listed first answers a caller with no session with a 400 that names the field it rejected, which tells a stranger what the route expects. With the gate first, every such caller gets the same 401. The handler still calls `requireAdmin` (or `requireAdminApp`) itself, because that call returns the session it needs. `adminGate` demands the `requireAdmin` roles; a route open to every admin-app role skips it and opens with `requireAdminApp`, and it must then take no validator before that call.\n\nThe shipped `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-gate.test.ts` holds the rule for you. It walks `app.routes`, sends every `\u002Fadmin\u002F*` route except `\u002Fadmin\u002Fauth\u002F*` a request with no cookie, a malformed body and a junk query, and fails on any answer but 401. A new route under `\u002Fadmin` is checked with no new test. Run it with `pnpm -C apps\u002Fapi test`.\n\nEvery admin write route also needs an audit action. `apps\u002Fapi\u002Fsrc\u002Froutes\u002Faudit-coverage.test.ts` walks `app.routes` the same way and fails on any `POST`, `PUT`, `PATCH` or `DELETE` under `\u002Fadmin\u002F` (outside `\u002Fadmin\u002Fauth\u002F*`) that no module's action file in `apps\u002Fapi\u002Fsrc\u002Faudit\u002F` names. The header of `apps\u002Fapi\u002Fsrc\u002Flib\u002Fadmin-write.ts` holds the recipe. The audited routes that ship today:\n\n| Module | Route | Actions |\n| --- | --- | --- |\n| `payment` | `POST \u002Fadmin\u002Fpayment\u002Fpayments\u002F:id\u002Freview` | `payment.review.confirm`, `payment.review.reject` |\n| `payment` | `POST \u002Fadmin\u002Fpayment\u002Fpayments\u002F:id\u002Frefunds` | `payment.refund.create` |\n| `feature-flags` | `PUT \u002Fadmin\u002Fflags\u002F:key` | `flag.value.set` |\n| `feature-flags` | `PUT \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.set` |\n| `feature-flags` | `DELETE \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.clear` |\n| `admin` | `POST \u002Fadmin\u002Fmembers` | `member.add` |\n| `admin` | `PATCH \u002Fadmin\u002Fmembers\u002F:id` | `member.profile.update` |\n| `admin` | `POST \u002Fadmin\u002Fmembers\u002F:id\u002Fpassword` | `member.password.set` |\n| `admin` | `DELETE \u002Fadmin\u002Fmembers\u002F:id` | `member.remove` |\n| `admin` | `POST \u002Fadmin\u002Fmembers\u002F:id\u002Frestore` | `member.restore` |\n\nThe `admin()` plugin's own endpoints answer 404 on `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` over HTTP, so a staff change to a user goes through an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.*` inside `adminAuthWrite`, never through `auth.admin.*` in the browser.\n\n```tsx\n\u002F\u002F apps\u002Fadmin\u002Fsrc\u002Froutes\u002Freports.tsx — the client half\nexport const Route = createFileRoute(\"\u002Freports\")({\n  loader: ({ context }) => context.queryClient.ensureQueryData(reportsQuery),\n  component: Reports,\n});\n```\n\nThe screen needs no guard of its own. It is a child of `__root.tsx`, so it inherits `beforeLoad`, and a non-admin never reaches its loader. That inheritance is exactly what makes the server half easy to forget: the screen behaves correctly while the endpoint behind it answers anyone.\n\n`GET \u002Fadmin\u002Fusers` is the shipped example. `modules\u002Fadmin\u002Ffiles\u002Fapi\u002Froutes\u002Fadmin-users.ts` lists `adminGate` and its query validator, calls `requireAdmin` for the session, then `adminAuth.api.listUsers` (the admin plugin's endpoints answer only on the admin instance, and only to server code: the forward answers 404 to `\u002Fadmin\u002Fauth\u002Fadmin\u002F*`), and answers `{ users, total }`. A `chained-route` patch registers it on api's exported chain, so `hc\u003CAppType>` types it here for free. `src\u002Froutes\u002Fusers.tsx` renders it, so both halves of the gate are live in the scaffold and the next route has a pattern to copy on each side.\n\nProve the server half yourself rather than trusting the screen. Sign in as a client through `POST \u002Fauth\u002Fsign-in\u002Femail`, take the cookie jar, and call the endpoint directly:\n\n```sh\ncurl -i -b \u002Ftmp\u002Fclient-cookies.txt http:\u002F\u002Flocalhost:4000\u002Fadmin\u002Fusers\n```\n\nThat answers `401` with `{\"error\":{\"code\":\"unauthorized\",\"message\":\"sign in first\"}}`, because a client cookie is no admin session at all. An admin session whose role was removed after sign-in gets `403` with `\"role required: admin or superadmin\"`. A `200` means the route skipped the gate, whatever the browser shows.\n\n`src\u002Flib\u002Fauth.ts` owns the read. `loadSession()` fetches once per page load and hands the same\npromise to every caller, so a burst of navigations costs one round trip; `forgetSession()` drops it.\nThe memo has no expiry by design — a session revoked elsewhere stays cached until a sign-out or a\nreload, which shows up as api calls answering 401 under a shell that still paints, never as access\na server denied. **Every code path that changes who is signed in calls `forgetSession()` before\n`router.invalidate()`** — invalidating first re-runs the guard against the stale cache and undoes\nthe sign-in or sign-out that just happened. `login.tsx` and `components\u002Fsign-out-button.tsx` both\nshow the order.\n\n`src\u002Flib\u002Fauth.ts` builds its client with `createAdminClient(apiBaseUrl)` from `@repo\u002Fauth\u002Fclient`, which talks to `\u002Fadmin\u002Fauth` with `credentials: \"include\"`. It keeps the export name `auth`, so a module screen that imports `auth` from `@admin\u002Flib\u002Fauth` reaches the admin session with no change. Never build this app's client with `createClient`: that is the client-group factory at `\u002Fauth`, and its session never opens this app.\n\nThe role string itself comes from better-auth's `admin()` plugin, which the `auth` module enables on both halves (`admin()` server-side, `adminClient()` in `adminAuthClientPlugins` in `packages\u002Fauth\u002Fsrc\u002Fclient.ts`). Drop the client half and `session.user.role` stops being typed.\n\n**The first account to sign up becomes the superadmin.** A `databaseHooks.user.create.before` hook in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` writes `role: \"superadmin\"` when the `users` table is still empty, so a fresh project reaches this shell without SQL. This app has no sign-up, and neither has the admin instance, so the first account signs up as a client on `\u002Fauth` (a client app's sign-up screen, or `POST \u002Fauth\u002Fsign-up\u002Femail`) and then signs in here with the same email and password. Every account after it keeps the plugin's `\"user\"` default, and this app's login refuses it until a superadmin grants an admin-group role. Client sign-up is open, so claim that first slot the moment the api answers; if somebody beat you to it, the recovery SQL in the `saasaloy-auth` skill flips the row. That skill owns the rule and the recovery path both.\n\n**A deep link survives the login hop.** The guard records the path it turned an anonymous visitor\naway from as `?redirect=` on `\u002Flogin`, and `login.tsx` navigates there after `forgetSession()` and\n`router.invalidate()`. `src\u002Flib\u002Fredirect.ts` decides whether that value may be used, and it has two\ngates: `toInternalPath` rejects anything a browser could read as another origin (`\u002F\u002Fhost`, `\u002F\\host`,\nan absolute url, a control character), and `resolveDestination` then asks the router itself, through\n`getMatchedRoutes(pathname)`, whether a route claims the path. Either failure falls back to `\u002F`. A\nnew screen needs nothing here — it is in the generated route tree, so it is already a valid\ndestination.\n\nThere is deliberately **no sign-up route** here, and `adminAuth` sets `disableSignUp: true`. An admin account is made by promoting an existing user, never by self-service at the backoffice door. Only a superadmin may grant `admin` or `superadmin` (the rank guard in the `saasaloy-auth` skill).\n\n## Add an admin write route, in four steps\n\n1. **Name the action.** Add an entry to your module's action file, `apps\u002Fapi\u002Fsrc\u002Faudit\u002F\u003Cmodule>.ts`: the route as `METHOD \u002Fadmin\u002F...` exactly as Hono lists it, the target type, the area, and a `label` such as \"Confirmed a payment\". Give one entry of a new area an `areaLabel`. A module ships that file with a `plugin-array` patch into `AUDIT_ACTIONS` in `apps\u002Fapi\u002Fsrc\u002Flib\u002Faudit-actions.ts`, the way `payment` and `feature-flags` do, so `saasaloy remove` takes the actions with the module.\n2. **Gate the route.** List `adminGate` first, then the validator, then a handler that opens with `adminWrite(c, async ({ db, actor, audit, afterCommit }) => ...)`. Use `db` for every query of the change. When Better Auth makes the change, use `adminAuthWrite(c, async ({ actor, audit }) => ...)` and call `adminAuth.api.*` with `headers: c.req.raw.headers`, so the plugin's permissions and `rank-guard` run as the caller.\n3. **Write the row.** Call `audit({ action, target: { id, label }, before, after })` once per change, with the fields the change touched. A create passes `after` only, a delete `before` only. Never pass a password: `adminWrite` throws on a key that matches `\u002Fpassword\u002Fi`, and `adminAuthWrite` drops it and logs at `error`. Put an email or any other side effect in `afterCommit`.\n4. **Prove it.** `audit-coverage.test.ts` fails until step 1 names the route, and `admin-gate.test.ts` fails if the validator runs before the gate. Neither proves the row is written, so add a route test beside the route that signs in a seeded admin, calls it, and reads `audit_events` for the row. `admin-members.test.ts` is the model.\n\n## What the D1 driver guarantees\n\nUnder `database-postgres`, `adminWrite` is one transaction. The change and its audit rows commit together, and a body that throws or answers 4xx keeps nothing.\n\nUnder `database-d1` there is no interactive transaction. Each statement of the body commits as it runs, and the audit rows go in one batch after it. A body that writes and then fails keeps its write and gets no row. A failed audit insert is logged at `error` and the change stands. Validate before you write, and a D1 route keeps nothing on a 4xx either. `adminAuthWrite` gives this weaker guarantee on both drivers, because Better Auth makes the change outside our transaction.\n\n## The members screen\n\n`src\u002Froutes\u002Fmembers.tsx` manages the admin group, the accounts in `ADMIN_ROLES`. Users lists every account; Members manages only the admin group. The api is `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-members.ts` at `\u002Fadmin\u002Fmembers`, and `membersQuery` in `src\u002Flib\u002Fmembers-query.ts` reads `GET \u002Fadmin\u002Fmembers`, which answers `{ me, members, removed }`. The route pages `listUsers` with a role filter until it has the whole group, so nothing is cut off at 100.\n\n- Active and Removed tabs. Removing a member bans the account and ends its sessions. The account keeps its id, so its audit rows still name a real person, and a restore unbans the same account with its password.\n- The Removed tab's \"Removed\" date and \"Removed by\" name come from the newest `member.remove` row. An account banned outside the screen falls back to `updatedAt` and no name.\n- \"Added by\" comes from the `member.add` row. \"Last sign-in\" is the newest admin session still on record. Better Auth deletes a session at sign-out, so the column shows a dash, never \"Never\".\n- A member changes their own name (`PATCH \u002F:id`, Better Auth's own `\u002Fupdate-user`) and password (`POST \u002F:id\u002Fpassword` with `currentPassword`, through `changePassword`; \"Sign out my other sessions\" is on by default, and the route passes the fresh session cookie back). A superadmin also adds members, resets another member's password (`setUserPassword`, then `revokeUserSessions`), removes, and restores. The route answers 403 for each of those before Better Auth runs, and self-removal answers 400.\n- The rank guard stands behind the route and is stricter: it refuses an `admin` any change to an admin-group account, so an `admin` who adds even an `admin` gets 403. The screen shows \"Add member\" and registers its command only for a superadmin; the 403 stays the server's rule.\n- Adding the email of a removed member answers 409 `member_removed` with the member, and the dialog offers a superadmin \"Restore \u003Cname>\".\n- The member panel lists the member's three newest changes as actor (`GET \u002Fadmin\u002Faudit-events?actor=\u003Cid>&limit=3`) and links to `\u002Factivity?actor=\u003Cid>`. The remove asks first in an alert dialog, and every save reports in a toast.\n\n## The Activity page\n\n`src\u002Froutes\u002Factivity.tsx` lists `audit_events` newest first, 50 rows a page, through `useInfiniteQuery` and a \"Load older\" button. The api is `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-audit.ts` at `\u002Fadmin\u002Faudit-events`, with `adminGate` before the validator on both routes.\n\n- `GET \u002Fadmin\u002Faudit-events` takes `actor`, `area`, `q`, `from`, `to`, `cursor` and `limit`, and answers `{ events, counts, areas, nextCursor }`. The cursor is `\u003CISO time>~\u003Cid>`, and any other cursor answers 400. `counts` holds `all` and each area under the filter minus the area, so a chip keeps its number when another chip is pressed.\n- `GET \u002Fadmin\u002Faudit-events\u002Fpeople` lists the person menu: the admin group plus every actor in the log, removed admins marked.\n- Each event carries `label`, the action's words from its action file, and `areas` carries each area's words. The page shows the label; the raw action key shows only in the detail panel. An action no module registers any more reads as its key.\n- The person, area and range live in the address through `validateSearch` (`activitySearch` in `src\u002Flib\u002Factivity.ts`). The search box narrows by target label 300 ms after the typing stops.\n- A row opens the detail panel with the exact time, the actor and role, the target, the action key, and a \"What changed\" table of each stored field before and after.\n\n## Extension seams\n\nSome module files take a project's own code through a seed file under `src\u002Fextend\u002F`. A seed file is written once and is then the project's: `saasaloy update` never changes it, and writes it again only when it is missing, because a managed file imports it. Put your change in the seed file and leave the managed file alone, and it keeps taking updates with no merge (ADR 0060).\n\n| Seed file | Shipped by | Read by | What goes in it |\n| --- | --- | --- | --- |\n| `src\u002Fextend\u002Froot.tsx` | `admin` | `src\u002Fcomponents\u002Fapp-shell.tsx` | `rootWrappers`, components that take `children`. AppShell renders `ShellLayout` inside each one, the first entry outermost, so the sidebar, the header and every page can read what a wrapper provides. They render inside the toast provider and only for a signed-in admin, never on `\u002Flogin` or the access-denied screen. |\n| `src\u002Fextend\u002Fpayments.ts` | `payment` | `src\u002Froutes\u002Fpayments.tsx` | `paymentsSearchExtension`, a zod object shape. `payments.tsx` spreads it into its `validateSearch` schema, so a key added here is typed on `Route.useSearch()` and on every link to `\u002Fpayments`. |\n\nA search key such as `payment: z.string().optional().catch(undefined)` keeps a malformed value in a pasted link from failing the screen. A key does nothing by itself: read it with `Route.useSearch()` in the screen, and that edit is the one change left in the managed file.\n\n`__root.tsx` takes no edit for a wrapper; `app-shell.tsx` applies them. The overview, `index.tsx`, has no seam yet.\n\n## The typed client\n\n`src\u002Flib\u002Fapi.ts` is the only place `hc` is called:\n\n```ts\nexport const api = hc\u003CAppType>(apiBaseUrl, {\n  headers: { \"x-auth-audience\": \"admin\" },\n  init: { credentials: \"include\" },\n});\n```\n\nFour properties are load-bearing:\n\n- **`AppType` is `apps\u002Fapi`'s route chain.** `api.health.$get()`, its path and its per-status\n  response shape all come from the route file. Change a response schema in `apps\u002Fapi` and this app\n  stops typechecking. Turbo runs `typecheck` across every workspace, so CI catches it.\n- **`apiBaseUrl` is imported from `src\u002Flib\u002Fauth.ts`**, not re-read from `import.meta.env`. The\n  session cookie is scoped to the api origin, so an api client bound elsewhere would send none.\n- **`init.credentials: \"include\"`** is why this file exists instead of a one-line `hc()` per call\n  site. `fetch` omits cookies cross-origin by default, so without it every request from `:3001`\n  arrives anonymous and the api answers 401.\n- **`x-auth-audience: admin`** names which of the browser's two sessions each call means. The browser sends both cookies to the api host, the client one included when a client is signed in on another app in the same browser. The `requireAdmin*` gates read the admin session whatever the header says, but a generic gate (`requireSession`, `requireTenant`, `authFor(c)`) reads the session the header names. Without it, a teams or subscription screen here would act as the client in the other tab. Any value other than `client` or `admin` gets 400.\n\n`@repo\u002Fapi\u002Fclient` is a **types-only** export (its `package.json` maps `.\u002Fclient` under a `types`\ncondition alone), which is why `@repo\u002Fapi` is a `devDependency`. No Worker code enters this bundle.\n\n### Why `@cloudflare\u002Fworkers-types` is in this app's `types`\n\n`tsconfig.json` lists `\"types\": [\"@cloudflare\u002Fworkers-types\", \"vite\u002Fclient\"]`, and the first entry\nlooks wrong in a browser-only SPA. It is not.\n\nImporting `AppType` makes `tsc` read **apps\u002Fapi's whole source graph**, because the type *is* that\ngraph. That graph includes the auth handler api mounts, which imports `cloudflare:workers` and\nannotates a `D1Database`. Without the ambient Workers types, those declarations fail to resolve and\nthe errors surface **here**, in `apps\u002Fadmin`, pointing at files in `apps\u002Fapi` that admin never\nbundles a byte of.\n\nSo: **an admin typecheck error whose path starts `apps\u002Fapi\u002F` is usually not an admin bug.** Add a\nWorker-only dependency to the api and read the error where it is reported, not where it is thrown.\nThe fix is nearly always in `apps\u002Fapi` (or in another ambient type this app must declare), never a\nchange to `src\u002Flib\u002Fapi.ts`. The entry is types only; there is no runtime dependency on the Workers\nruntime in this app.\n\n### Why the two TanStack Router pins carry different numbers\n\n`@tanstack\u002Freact-router` is pinned at `1.170.32` and `@tanstack\u002Frouter-plugin` at `1.168.35`, which reads like drift and is not. TanStack releases the two on independent version lines, and `router-plugin@1.168.35` names `\"@tanstack\u002Freact-router\": \"^1.170.32\"` in its own `peerDependencies` — the pins are the matching pair, they just do not share a number. Do not \"fix\" the mismatch by inventing a `router-plugin@1.170.32`; no such release exists. Check the plugin's `peerDependencies` against the router pin instead, and move both together when `pnpm deps:update` offers a bump.\n\n## Loader + Query, and why both\n\n`src\u002Fmain.tsx` creates one `QueryClient` at module scope and puts it on the **router context**, so a\nroute's `loader` prefetches through the same cache the component then reads:\n\n```tsx\nconst router = createRouter({ routeTree, context: { queryClient }, defaultPreload: \"intent\" });\n```\n\n`ensureQueryData` in the loader starts the request while the route resolves, and `defaultPreload:\n\"intent\"` starts it on hover, so the cache is warm before the component mounts. The component still\nreads through `useQuery` rather than the loader's return value, because `useQuery` **subscribes**:\nan invalidation anywhere in the app re-renders the screen.\n\nRefresh by **invalidating the key**, not by calling `refetch()`. `invalidateQueries({ queryKey })`\nrefreshes every screen holding that query, and it is the same call a mutation's `onSuccess` makes.\n\nThe scaffold's defaults are `retry: 1` and `staleTime: 30_000` — backoffice numbers, not universal\nones. An admin clicks between a handful of screens, so a short stale window keeps a revisit instant,\nand one retry absorbs a dropped packet without sitting on a down api for seconds.\n\nA data route needs no `errorComponent` of its own: the router's default renders the shell `ErrorState` for a loader's throw and for a render failure. Add one only when the words should say more, as `\u002Fusers` and the overview do.\n\nThe overview at `\u002F` is the exception to awaiting in the loader. Its loader calls `prefetchQuery` for `\u002Fhealth` and for `newestUsersQuery` and awaits neither, so the page paints at once, and each card renders its own skeleton, its data, or its own failure. A down api shows \"Unreachable\" in the health card and never swaps the page for an error screen. Copy that shape for a dashboard whose cards read separate requests; await in the loader for a screen that is one list.\n\n## Theme and font\n\n**The admin app carries its own theme file.** This module writes `packages\u002Fui\u002Fsrc\u002Fstyles\u002Fadmin.css`, beside the web app's `brand.css`. It imports the shared `globals.css`, which owns Tailwind's entrypoint, the `@source` globs and the base layer and holds no token values. `admin.css` then imports the `shell` module's `shell.css` and declares the `dark` custom variant, this app's `:root` and `.dark` values, and its own `@theme inline` colour mapping and radius scale. The variant and the mapping repeat `brand.css`'s on purpose: each theme file holds its own, so a shadcn preset aimed at `brand.css` never reaches this app.\n\nThat `shell.css` import is load-bearing. It holds the `@source` line for `components\u002Fshell\u002F`, the colour mapping for the status tokens, and the skeleton and toast motion. Drop it and every shell primitive renders unstyled with no error. See the `saasaloy-shell` skill.\n\n`src\u002Fmain.tsx` imports `@repo\u002Fui\u002Fstyles\u002Fadmin.css` and the Inter font package, and nothing else. That import needs the `\".\u002Fstyles\u002F*\": \".\u002Fsrc\u002Fstyles\u002F*\"` export in `packages\u002Fui\u002Fpackage.json`, which the base template ships from the theme split onward. A project made before the split lacks it, and the admin build then fails to resolve `@repo\u002Fui\u002Fstyles\u002Fadmin.css`. Run `saasaloy update` for the base and follow the steps in [Finish the theme split](https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fdocs\u002Fwiki\u002Frunbooks\u002Ffinish-the-theme-split.md) first. **No route imports a stylesheet.** Two Tailwind entrypoints in one bundle means two copies of the base layer and a token set whose winner depends on import order.\n\nThe palette is a three-step neutral ramp measured off the reference screenshots — canvas darkest, panel one step lighter, hover and selected one step lighter again — with alpha hairlines over it: white at 8 % on dark, black at 8 % on light, and inputs a step stronger. The measured values are written into the header comment of `admin.css` beside the roles they fill; change a value there and update the comment with it. Light is a mapped variant on a neutral grey canvas and is first-class, not a fallback.\n\n`apps\u002Fadmin\u002FDESIGN.md` records these tokens and the rules behind them, and fingerprints `admin.css`. After you change `admin.css`, run the `saasaloy-design` skill's `update` flow for the admin app. A theme preset never targets `admin.css`; it reaches the web app only.\n\nBeyond the shadcn set, `admin.css` sets this app's values for the tokens `shell.css` declares and maps: the status pairs the primitives read (`--success`, `--warning`, `--info` and `--destructive-foreground`, each a fill tone and a darker text tone) and two accents. Each one replaces a neutral default in `shell.css`, in `:root` and in `.dark`:\n\n- `--status-open` (and `--status-open-foreground`) — the muted blue of `StatusPill`'s `open` tone and of a primary circular action.\n- `--status-ok`, `--status-warn` and `--status-bad` (each with a `-foreground`) — `StatusPill`'s `ok`, `warn` and `bad` tones. They copy the `--success`, `--warning` and `--destructive` values, and they exist so a theme preset, which sets `--destructive` and `--destructive-foreground` with another meaning, never repaints a status. No preset sets a `status-*` key.\n- `--accent-sort` — the orange on `DataTable`'s active sort header. It is reserved for one indicator at a time and for an AI surface. It is never a section background, and `StatusPill` deliberately has no orange tone.\n\n**Dark by default, and every stored choice wins — `system` included.** `applyStartingTheme()` in `src\u002Fmain.tsx` runs above `createRoot` and is one line: `setTheme(hasChosenTheme() ? getStoredTheme() : \"dark\")`.\n\nThe `theme` key alone cannot carry this. `setTheme(\"system\")` DELETES it — that is how `@repo\u002Fui`'s state machine spells \"follow the OS\", and the landing page depends on it — so a first visit and a deliberate `system` both read as an absent key. `hasChosenTheme()` separates them by reading a second key, `theme-chosen`, which `installThemeToggle()` writes on every press and nothing clears. Never chosen means dark; chosen with no `theme` key means `system`, resolved against the OS.\n\n`index.html` emits no `THEME_INIT_SCRIPT` — that is the Astro host's mechanism, and there is no Vite plugin here. The trade is one frame of the light palette on an empty body before the entry module runs. `main.tsx` calls `installThemeToggle()` from `@repo\u002Fui\u002Flib\u002Ftheme` instead, for the OS listener that script would otherwise install. The Theme submenu below sets the theme itself.\n\n`ThemeMenuItem` is a \"Theme\" submenu (`MenuSub`, `MenuSubTrigger`, `MenuSubPopup`) with one `MenuRadioItem` per entry in its `THEME_OPTIONS` list. A pick calls `setTheme(value)` inside `revealTheme`, then writes `THEME_CHOICE_KEY`, so the starting-theme rule in `main.tsx` keeps the choice on the next load, `system` included. It does not use the delegated `[data-theme-toggle]` handler, because that handler only flips light and dark. The current choice is the `data-theme` attribute on `\u003Chtml>`, which `setTheme` writes, read through a `MutationObserver`. To add a theme, teach `@repo\u002Fui\u002Flib\u002Ftheme` to apply it, then add one entry to `THEME_OPTIONS`. `main.tsx` still calls `installThemeToggle()` for its OS listener, which repaints a visitor on `system` when the OS changes.\n\n### The font this app adds\n\n- **`@fontsource-variable\u002Finter`** is a runtime `dependency` of this app, imported from `src\u002Fmain.tsx` beside `admin.css`, and set as `--font-sans` in a `@theme` block in `admin.css`. The import stays in the app because Tailwind resolves a CSS `@import` from the stylesheet's own folder, and `packages\u002Fui` does not depend on the font. It is the app's only face; no mono font is loaded. The body enables Inter's `cv11` and `ss01` sets; `shell.css` adds `tabular-nums`.\n\nIt is exact-pinned. Template and module-descriptor dependencies are invisible to pnpm, so move it with `pnpm deps:update` and never by hand-typing a version. `@tanstack\u002Freact-table` belongs to the `shell` module now; see `saasaloy-shell`.\n\n## Ports and CORS\n\n| Service | Port | Pinned in |\n|---|---|---|\n| `apps\u002Fweb` (Astro) | **3000** | `astro.config.mjs` |\n| `apps\u002Fadmin` (this app) | **3001** | `vite.config.ts` (`server.port` + `strictPort`) |\n| `apps\u002Fapi` (Worker) | **4000** | `vite.config.ts` and `wrangler.jsonc` (`dev.port`) |\n\n`3001` is not cosmetic. The api's `DEV_ORIGINS` allowlist and better-auth's `trustedOrigins` both\nhardcode `http:\u002F\u002Flocalhost:3001` as the keyless dev fallback, so a drifting port turns into a CORS\nrejection that reads like a code bug. `strictPort` makes a busy port fail loudly instead of quietly\nshifting to `3002`, the port `apps\u002Fapp` holds.\n\nIn production the origin comes from `PUBLIC_API_URL`, and the api needs the admin origin in\n`CORS_ORIGINS`. The prefix is `PUBLIC_` rather than Vite's default `VITE_` (`envPrefix` in\n`vite.config.ts`), so the bundle only inlines a variable a human deliberately named `PUBLIC_*`, and\none env key spells the api origin for `web`, `admin` and `waitlist` alike. Unset or empty, it falls\nback to `http:\u002F\u002Flocalhost:4000`.\n\nCookie behaviour is the `auth` module's (ADR 0004). Cross-origin dev works because api's `cors()` sets `credentials: true` for the allowlisted origins and the cookie is host-only on `localhost`. Cookies ignore the port, so `:3000` and `:3001` see the same jar; the names `client.session_token` and `admin.session_token` are what keep a client sign-in on the web app from replacing this app's session. In\nproduction, put the api and the admin app on sibling subdomains and set `COOKIE_DOMAIN`.\n\n## Run it\n\n```sh\npnpm --filter @repo\u002Fapi dev    # :4000, the real workerd runtime\npnpm --filter @repo\u002Fadmin dev  # :3001\n```\n\nBoth, in two terminals. Admin on its own serves a login screen that cannot sign anyone in.\n\n## Deploy\n\nStatic assets on a Worker, exactly like `apps\u002Fweb`:\n\n```sh\npnpm --filter @repo\u002Fadmin build           # vite build → dist\u002F\npnpm --filter @repo\u002Fadmin exec wrangler deploy --dry-run\n```\n\n`wrangler.jsonc` declares `assets.directory: \".\u002Fdist\"` with\n`not_found_handling: \"single-page-application\"` and **no `main`**. The SPA fallback is what makes a\nhard reload of `\u002Flogin` work; without it the request 404s, because no such file exists in `dist\u002F`.\nThere are no bindings, and there should not be — the session and the database are reached through\n`apps\u002Fapi` over HTTP.\n\nSet `PUBLIC_API_URL` at **build** time, not on the Worker. Vite inlines it into the bundle, so a\nruntime variable would arrive too late to matter.\n\n`pnpm deploy:production` deploys this app with every other Worker. Its `deploy` script is\n`env-deploy admin`, which builds with the `admin` service's production values in the\nenvironment, so the bundle inlines the production `PUBLIC_API_URL` and the dev `.env` stays as it\nis. The app is assets-only, so it gets no secrets.\n\n`saasaloy add admin` appends `{ service: \"admin\", order: 20 }` to `DEPLOY_TARGETS` in `packages\u002Ftooling\u002Fsrc\u002Ftargets.ts`, so the admin deploys after the api it calls and before the web. It also appends the `admin-home` smoke check, `GET \u002F` with a 200, which runs once `apps\u002Fadmin\u002Fwrangler.jsonc` has a `routes[]` entry with `custom_domain: true`. `pnpm deploy:production --only admin` deploys this app alone after the gates. See the `saasaloy-deploy` skill.\n\n## Removing the module\n\n`saasaloy remove admin` deletes the files **this module** installed and prunes the directories that\nleaves empty. A route file another module dropped into `src\u002Froutes\u002F` is that module's, so it\nsurvives, and `apps\u002Fadmin\u002F` survives with it as a half-workspace: no `package.json`, no\n`vite.config.ts`, a stale `src\u002FrouteTree.gen.ts`, and the `@admin` alias still in `saasaloy.json`\nbecause its prefix directory did not vanish.\n\n**Remove the feature modules that dropped routes first, then `admin`.** Otherwise delete the\nleftovers by hand before re-adding, or the next `add admin` restores a workspace around orphaned\nfiles.\n\n## Conventions to honor\n\n- **A screen is a file drop** under `src\u002Froutes\u002F`, never a patch. Let the plugin rewrite\n  `src\u002FrouteTree.gen.ts`; never hand-edit it.\n- **`tanstackRouter()` stays ahead of `react()`** in `vite.config.ts`.\n- **A screen composes the shell blocks.** Start from `PageHeader` and `PageLayout` or `PageBody`; do not write shell markup, table markup, padding, or a page width of your own.\n- **Admin code imports the shell set only.** `@repo\u002Fui\u002Fcomponents\u002Fshell\u002F*`, `blocks\u002Fshell\u002F*` and `containers\u002Fshell\u002F*`; the lint rule fails a base primitive.\n- **A block takes plain props and callbacks.** Nothing in `@repo\u002Fui` imports `@repo\u002Fapi`, `hono\u002Fclient`, `@admin\u002Flib\u002Fapi`, a router, or reads `import.meta.env`.\n- **`@tanstack\u002Freact-table` is imported by `data-table.tsx` and by nothing else.** A route that imports a `ColumnDef` has skipped the wrapper the next screen depends on.\n- **Every mutation reports through a toast**, a destructive one confirms in an `AlertDialog` first, and a create flow opens in a `Dialog`.\n- **`NAV_AREAS` stays `as const`.** That literal type is what turns a nav entry for a missing route\n  into a typecheck failure instead of a 404.\n- **One theme file, `@repo\u002Fui\u002Fstyles\u002Fadmin.css`, imported once from `src\u002Fmain.tsx`.** A second Tailwind\n  entrypoint duplicates the base layer and makes the token set order-dependent.\n- **Dark is the default, and a stored choice wins.** Gate it on `hasChosenTheme()`. `getStoredTheme()`\n  alone cannot tell an unset key from a deliberate `system`, because `system` is spelled as no key.\n- **Orange is `--accent-sort` and nothing else.** One active sort indicator, or an AI surface. Never\n  a section background and never a status pill.\n- **Loading, not-found and error screens come from the app.** Inherit the router defaults and `__root.tsx`'s `notFoundComponent`; override a route's `errorComponent` only for better words, and do not write error markup outside the shell `ErrorState`.\n- **One `hc` call, in `src\u002Flib\u002Fapi.ts`.** Import `api`; do not build a second client, and do not drop its `x-auth-audience: admin` header.\n- **The auth client is `createAdminClient`.** `src\u002Flib\u002Fauth.ts` exports it as `auth`; never swap in `createClient`.\n- **`\u002Fadmin\u002Fauth\u002F*` belongs to the admin auth instance.** An api route or middleware this app adds under `\u002Fadmin\u002F*` must not claim or gate it.\n- **One origin for api and auth**, from `src\u002Flib\u002Fauth.ts`'s `apiBaseUrl`. A split origin loses the\n  session cookie.\n- **The guard lives in `__root.tsx`'s `beforeLoad`**, and it is default-deny. A per-route session\n  check is redundant, because every deny there is a throw and no child loader runs after one. Keep\n  it that way: a deny that returns instead of throwing silently re-opens the loaders it was meant to\n  stop. Do not turn `AccessDenied` into a redirect either.\n- **`adminGate` comes before every validator on an admin route.** A validator listed first answers a signed-out caller with a 400 that describes the input. `admin-gate.test.ts` fails on it.\n- **Project code goes in `src\u002Fextend\u002F`, not in a managed file.** A wrapper goes in `rootWrappers`, a payments search key in `paymentsSearchExtension`. An edit in place sends the file to the merge plan on every update.\n- **Every admin endpoint calls `requireAdmin` or `requireAdminApp`**, whatever the guard in `__root.tsx` does. The screen inheriting `beforeLoad` is not authorization; it is the reason a missing server check looks fine in a browser.\n- **`forgetSession()` before `router.invalidate()`**, on every sign-in and sign-out path.\n- **Describe a request once with `queryOptions`**, prefetch in the loader, read with `useQuery`,\n  refresh by invalidating the key.\n- **Browser env vars are `PUBLIC_*`.** A `VITE_*` name is not exposed here.\n- **No bindings and no Worker entry.** Anything needing D1, R2 or a secret belongs in `apps\u002Fapi`.\n\n## Next\n\nRun `saasaloy-feature` to build the first product entity end to end, with its list on an admin screen.\n",{"name":5,"description":7},"main","5ecf3d110b216ef678e06a1630f6b63a8e730bb5","modules\u002Fadmin\u002Fskills\u002Fsaasaloy-admin",0,"https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy","https:\u002F\u002Fsaasaloy.com","https:\u002F\u002Fgithub.com\u002Fmimukit","https:\u002F\u002Fmimukit.com","Senior Software Engineer · 9+ yrs Fullstack (TS\u002FNode\u002FReact) · AI integrations, distributed systems · Building @saasaloy & @codealoy · Bangladesh 🇧🇩 \u002F Remote","2026-11-13 20:39:28",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mimukit\u002Fsaasaloy --skill saasaloy-admin",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-admin",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-admin","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fadmin\u002Fskills\u002Fsaasaloy-admin\u002FSKILL.md",true,[],[49,56,63,70,77,83],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7BE75C34XHSPVJNQC8FY4Q0","saasaloy-subscription","Runbook for the subscription capability — provider-agnostic subscriptions in packages\u002Fsubscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fsubscription\u002Fskills\u002Fsaasaloy-subscription\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7BE68MJ8H47JZKTBDFYR6JD","saasaloy-notification","Runbook for the notification module, in-app notifications for apps\u002Fapp. It owns the notifications and notification_opt_outs tables, notify() in apps\u002Fapi\u002Fsrc\u002Flib\u002Fnotify.ts, the \u002Fnotifications api routes, the bell in the app header, the sidebar badge, the \u002Fnotifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fnotification\u002Fskills\u002Fsaasaloy-notification\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7BE53PDQV0YDPG8RNVGTPEQ","saasaloy-cms","Runbook for the cms module, the in-house CMS behind apps\u002Fadmin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps\u002Fweb and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fcms\u002Fskills\u002Fsaasaloy-cms\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79GQ03M63V5EKSST92B3S5X","saasaloy-beta","The beta module's own procedure.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-clean\u002Fbeta\u002Fsaasaloy-beta\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79GPXV3K8YF3M4VA0KGVE0B","helper","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-broken\u002Fbad-skill\u002Fhelper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79GPR8EVS1YX0W8X33Q9YD8","saasaloy-update","Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says \"update saasaloy\", \"upgrade the CLI\", \"pull the latest modules\", \"update the base template\", \"work the merge plan\", \"clear the update notes\", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy\u002Fmerge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and \"Notes that may apply\", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftemplates\u002Fbase\u002F_agents\u002Fskills\u002Fsaasaloy-update\u002FSKILL.md",[],[]]