[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GGZPAJAY0WJ7DB1D3F4ZX":3,"skill-same:01M79GGZPAJAY0WJ7DB1D3F4ZX":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},"01M79GGZPAJAY0WJ7DB1D3F4ZX","saasaloy-auth",null,"Runbook for the auth capability — Better Auth with httpOnly session cookies in packages\u002Fauth, as two instances on one set of tables (the client session at \u002Fauth and the admin session at \u002Fadmin\u002Fauth). Use when wiring sign-up\u002Fsign-in or rendering the SignInCard and SignUpCard blocks on an app route, gating an api route with requireSession\u002FrequireRole\u002FrequireAdmin\u002FrequireAdminApp or reading one with getSession\u002FauthFor, choosing which session a route reads with x-auth-audience, adding a role such as support to the admin group, promoting the first superadmin or checking a user's role, signing in as a seed user with the dev password, re-verifying the schema snapshot after a better-auth bump, enabling social OAuth or email verification, the password reset mail and the 12-character password rule, patching the plugin arrays (subscription\u002Fteams), upgrading a project made before the client\u002Fadmin split, rotating the auth secret, debugging cookie\u002FCORS\u002Fsession issues, or working out why a call throws about a database client read outside `withAuthScope`.","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\u002Fauth\u002Fskills\u002Fsaasaloy-auth\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-auth\ndescription: Runbook for the auth capability — Better Auth with httpOnly session cookies in packages\u002Fauth, as two instances on one set of tables (the client session at \u002Fauth and the admin session at \u002Fadmin\u002Fauth). Use when wiring sign-up\u002Fsign-in or rendering the SignInCard and SignUpCard blocks on an app route, gating an api route with requireSession\u002FrequireRole\u002FrequireAdmin\u002FrequireAdminApp or reading one with getSession\u002FauthFor, choosing which session a route reads with x-auth-audience, adding a role such as support to the admin group, promoting the first superadmin or checking a user's role, signing in as a seed user with the dev password, re-verifying the schema snapshot after a better-auth bump, enabling social OAuth or email verification, the password reset mail and the 12-character password rule, patching the plugin arrays (subscription\u002Fteams), upgrading a project made before the client\u002Fadmin split, rotating the auth secret, debugging cookie\u002FCORS\u002Fsession issues, or working out why a call throws about a database client read outside `withAuthScope`.\n---\n\n# auth — Better Auth, httpOnly cookies + subdomains\n\n`packages\u002Fauth` (`@repo\u002Fauth`) owns [Better Auth](https:\u002F\u002Fbetter-auth.com) outright (ADR 0020), and no other workspace depends on `better-auth` directly. `apps\u002Fapi` gets a thin `routes\u002Fauth.ts` that forwards to the two instances' handlers; `packages\u002Fdb` gets a hand-authored schema snapshot. Sessions are **DB-backed httpOnly cookies**, not JWTs (build-spec §2.5 \u002F ADR 0004): one database read per request is negligible, and sessions are instantly revocable by deleting the row.\n\n## Two instances: the client session and the admin session\n\nA project has two user groups. The **client** group is the shopper, the customer, the app user, and its only site role is `user`. The **admin** group is every role in `ADMIN_APP_ROLES` (`superadmin` and `admin` ship). Each group signs in on its own Better Auth instance, both built in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` on the same four tables:\n\n| Export | Group | `basePath` | Cookie | Sign-up |\n|---|---|---|---|---|\n| `auth` | client | `\u002Fauth` | `client.session_token` | open |\n| `adminAuth` | admin | `\u002Fadmin\u002Fauth` | `admin.session_token` | none (`disableSignUp: true`) |\n\nIn production both cookies carry the `__Secure-` prefix. `advanced.cookiePrefix` sets the name, so a client and an admin stay signed in together in two tabs of one browser, and a sign-out in one tab leaves the other signed in. The decision record is [ADR 0050](..\u002F..\u002F..\u002F..\u002Fdocs\u002Fadr\u002F0050-adr-client-and-admin-sessions-are-two-auth-instances-2026-10-23.md).\n\nEverything the two share (the adapter, the secret, `trustedOrigins`, the first-user hook, `advanced`) lives in `sharedOptions(group)`. Each `betterAuth({...})` spreads it and keeps its own literal `plugins: [...]`.\n\n**The audience column keeps the two apart.** `sessions.audience` is `client` or `admin`, not null, default `'client'`, in both driver schemas. The `audience(name)` plugin in `packages\u002Fauth\u002Fsrc\u002Fplugins\u002Faudience.ts` declares the field with `input: false` (no endpoint can set it) and writes the instance's name into every new row. Each instance wraps its `drizzleAdapter` in `scopeSessionsTo(adapter, group)` from `packages\u002Fauth\u002Fsrc\u002Fscoped-adapter.ts`, so a session lookup by token finds only rows of its own audience. A token copied into the other cookie is no session at all: every endpoint, middleware and `api.*` call on that instance sees `null`. `decide()` in `authorize.ts` checks the audience a second time behind the adapter.\n\n**`adminAuth` refuses a user outside the admin group.** The admin instance registers `audience(\"admin\", { roles: ADMIN_APP_ROLES })`, whose `session.create.before` hook refuses to open a session for a user whose role is not in the list. The answer is Better Auth's own `INVALID_EMAIL_OR_PASSWORD` (\"Invalid email or password\"), so the admin login tells an attacker nothing about which addresses hold an account. The `accounts` table is shared, so an admin signs in on the admin app with the same email and password the account uses on the client side.\n\n**The client instance refuses every admin endpoint.** Both instances keep the `admin()` plugin, because it writes the default `\"user\"` role, types `user.role` and refuses a banned account at sign-in. On `auth`, `clientAdminGuard()` (`packages\u002Fauth\u002Fsrc\u002Fplugins\u002Fclient-admin-guard.ts`) answers 403 `ADMIN_SESSION_REQUIRED` on every `\u002Fauth\u002Fadmin\u002F*` path. It matches the path prefix, so an endpoint a Better Auth bump adds is refused too.\n\n**The admin forward closes the same endpoints over HTTP.** `adminAuthRoute` in `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` answers 404 on every `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` path, reads and impersonation included, before it forwards to `adminAuth.handler`. It decodes the path and folds case and repeated slashes, so an encoded path gets the same 404. No browser code calls these endpoints, and an open `set-role` or `ban-user` would be a staff write with no audit row, under `\u002Fadmin\u002Fauth\u002F*` where the `admin` module's audit coverage test cannot see it (issue #310). Server code still reaches them: an api route under `\u002Fadmin\u002F` calls `adminAuth.api.*` with the caller's headers inside `withAuthScope`, and `adminAuthWrite` from the `admin` module when it changes something. That call runs the admin session check and the rank guard below.\n\n**`\u002Fadmin\u002Fauth\u002F*` is reserved.** The `auth` module mounts `adminAuthRoute` at `\u002Fadmin\u002Fauth` with a second `chained-route` patch on `base`, beside `authRoute` at `\u002Fauth`. The path sits under `\u002Fadmin` so one edge rule (WAF, Access, a log filter) covers the whole admin group on the api. A middleware a project adds on `\u002Fadmin\u002F*` must skip `\u002Fadmin\u002Fauth\u002F*`, or the sign-in endpoint itself demands a session. A project without the `admin` module still has the `\u002Fadmin\u002Fauth` route; nothing calls it.\n\n## Either database driver\n\nThis module installs against `database-d1` or `database-postgres`, and picks the right files for\nwhichever one the project holds. It depends on `api` and `database`, and names no driver:\n`database`'s own `requiresOneOf` is what guarantees one is present.\n\nTwo files ship twice, and nothing else does:\n\n| Source in the module | Installs when | What differs |\n|---|---|---|\n| `files\u002Fdb\u002Fschema\u002Fauth.sqlite.ts` | `onlyWith: \"database-d1\"` | `sqliteTable`, `drizzle-orm\u002Fsqlite-core`, millisecond-integer dates |\n| `files\u002Fdb\u002Fschema\u002Fauth.pg.ts` | `onlyWith: \"database-postgres\"` | `pgTable`, `drizzle-orm\u002Fpg-core`, `timestamptz` dates, `boolean` flags |\n| `files\u002Fsrc\u002Fdb-provider.d1.ts` | `onlyWith: \"database-d1\"` | `provider: \"sqlite\"`, and `withAuthScope` runs the body |\n| `files\u002Fsrc\u002Fdb-provider.pg.ts` | `onlyWith: \"database-postgres\"` | `provider: \"pg\"`, and `withAuthScope` wraps `withDb` |\n\nEach pair names one `target` — `packages\u002Fdb\u002Fsrc\u002Fschema\u002Fauth.ts` and\n`packages\u002Fauth\u002Fsrc\u002Fdb-provider.ts` — so exactly one of the two lands and the other is filtered out\nbefore the plan is built. `saasaloy add auth --dry-run` prints which source it chose.\n\n`auth.ts`, `env.ts`, `server.ts`, `client.ts` and `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` are single files\nunder both drivers. The dialect reaches the table declarations and the four lines of\n`db-provider.ts`, and stops there.\n\nThe two schema variants are the same four tables, so keep them in step. They differ only where each\ndialect is idiomatic. A row comes back the same shape either way.\n\n**Switching driver is remove-then-add, and it takes this module with it.** The unchosen variant is\nfiltered before planning, so a project that swaps drivers keeps the schema it already installed.\nRemove `auth` and add it again after the driver switch to get the other variant. There is no data\nmigration; see ADR 0026.\n\n## The database client is request-scoped\n\n`auth` and `adminAuth` are module-scope singletons whose database client belongs to a single request. That split is the one thing to understand before writing a call against `auth.api.*` or `adminAuth.api.*`.\n\nWhy it exists: a Workers isolate outlives the request that created it, but an open socket does not.\nUnder `database-postgres`, a client bound once at module scope serves the first request and then\nthrows `Cannot perform I\u002FO on behalf of a different request` on the second. A single manual sign-in\ndoes not catch it; it takes two requests into one worker.\n\nHow it works: `drizzleAdapter` is handed `authDb`, a proxy holding no client of its own. It reads\nthe current request's client out of an `AsyncLocalStorage` in `packages\u002Fauth\u002Fsrc\u002Fdb-scope.ts`.\n`withAuthScope(c, fn)` in `packages\u002Fauth\u002Fsrc\u002Fdb-provider.ts` is what puts it there — under\nPostgres by wrapping the driver's `withDb`, which also closes the socket on\n`c.executionCtx.waitUntil`; under D1 by opening a binding stub and running the body.\n\n**The adapter runs with `usePlural: true`.** Better Auth asks for singular models (`user`, `session`), and the tables here are plural (`users`, `sessions`). The Drizzle adapter finds a table by its export key in the schema object, never by its SQL name, and `usePlural` appends an `s` to every model name, a custom `modelName` included. Keep the flag and the plural export keys together: remove one and every auth call throws `The model \"user\" was not found in the schema object`, which `pnpm typecheck` does not catch. A plugin with `modelName: \"X\"` needs the export key `Xs`. The naming rule is in the `saasaloy-database` skill under `## Table names`, and ADR 0038 records it.\n\n**Every `handler` and `api.*` call on either instance runs inside `withAuthScope`.** `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` already wraps both handlers, and `getSession(c)` and the gates already wrap their own reads, so ordinary use needs nothing. Reach for the wrapper by hand only when calling an instance yourself:\n\n```ts\nimport { adminAuth, withAuthScope } from \"@repo\u002Fauth\u002Fserver\";\n\nconst users = await withAuthScope(c, () => adminAuth.api.listUsers({ query: {}, headers: c.req.raw.headers }));\n```\n\nForget it and the read throws with a message naming `withAuthScope` — **on both drivers**, D1\nincluded. That is deliberate. D1 is the default driver, so most development happens there, and a\npermissive D1 path would let the mistake pass every local test and surface only after a project\nswitched to Postgres. The cost on D1 is one property lookup per call. See ADR 0029.\n\n## The plugin-array patch points (read this before adding subscription\u002Fteams)\n\n`packages\u002Fauth\u002Fsrc\u002Fauth.ts` exports two **module-scope singletons**, each with its own literal plugin array:\n\n```ts\nexport const auth = betterAuth({\n  ...sharedOptions(CLIENT_AUDIENCE),\n  basePath: \"\u002Fauth\",\n  \u002F\u002F ...\n  plugins: [audience(CLIENT_AUDIENCE), siteRoles(), clientAdminGuard()],\n});\n\nexport const adminAuth = betterAuth({\n  ...sharedOptions(ADMIN_AUDIENCE),\n  basePath: \"\u002Fadmin\u002Fauth\",\n  \u002F\u002F ...\n  plugins: [audience(ADMIN_AUDIENCE, { roles: ADMIN_APP_ROLES }), siteRoles(), rankGuard()],\n});\n```\n\nThis is deliberately a top-level `export const`, not a per-request `c.env`-scoped factory (every other capability's convention): the plugin arrays must exist at module scope for the codemod to patch. Keep `audience(...)` first in each array, so the session row carries its audience before any other plugin reads it.\n\n**A feature module that adds a Better Auth plugin patches both instances.** The admin app hosts every self-service screen (teams, roles, keys, subscription), so the admin session needs the same feature plugins as the client session. `teams`, `api-keys` and `subscription-stripe` each declare one `plugin-array` patch with `\"exportName\": \"auth\"` and a second with `\"exportName\": \"adminAuth\"`:\n\n```json\n\"patches\": [\n  { \"file\": \"packages\u002Fauth\u002Fsrc\u002Fauth.ts\", \"kind\": \"plugin-array\", \"exportName\": \"auth\", \"arrayProp\": \"plugins\", \"call\": \"stripe\", \"import\": { \"name\": \"stripe\", \"from\": \"@better-auth\u002Fstripe\" } },\n  { \"file\": \"packages\u002Fauth\u002Fsrc\u002Fauth.ts\", \"kind\": \"plugin-array\", \"exportName\": \"adminAuth\", \"arrayProp\": \"plugins\", \"call\": \"stripe\", \"import\": { \"name\": \"stripe\", \"from\": \"@better-auth\u002Fstripe\" } }\n]\n```\n\nA module that ships a client plugin does the same in `packages\u002Fauth\u002Fsrc\u002Fclient.ts`, once for `authClientPlugins` and once for `adminAuthClientPlugins`.\n\nThe existing codemod (`packages\u002Fcli\u002Fsrc\u002Flib\u002Fpatch\u002Fts-module.ts`) inserts the call into each array and adds the import once. It is idempotent and formatting-preserving, and it finds `plugins` next to the `...sharedOptions(...)` spread. When the named export does not exist (a project whose `auth.ts` predates `adminAuth`), the patch is a refusal, not a silent no-op: `saasaloy add` and `saasaloy update` print a warning that names the missing export, and `update` keeps the module's lock entry so a later `update` retries it. See \"Upgrading a project made before the client\u002Fadmin split\" below.\n\nThe plugin's own vendor dep (`@better-auth\u002Fstripe`) merges into `packages\u002Fauth\u002Fpackage.json` (ADR 0020: vendor plugin deps land in the capability that owns the vendor package), never into the feature's own files.\n\n## Env checklist (`add auth` prints this)\n\n| Var | What | Prod | Local |\n|---|---|---|---|\n| `BETTER_AUTH_SECRET` | Signs sessions | **Required** — generate a real secret | Optional, but only when `BETTER_AUTH_URL` is a loopback origin |\n| `BETTER_AUTH_URL` | The API's own origin | `https:\u002F\u002Fapi.x.com` | `http:\u002F\u002Flocalhost:4000` (the api Worker's pinned dev port) — **set it**, it is what opens the keyless path |\n| `COOKIE_DOMAIN` | Explicit cookie domain | `.x.com` (cross-subdomain) | Leave unset (host-only) |\n\n### The secret fails closed\n\n`packages\u002Fauth\u002Fsrc\u002Fenv.ts` reads `BETTER_AUTH_SECRET` at module load and **throws** when it is\nunset. Better Auth's fallback key is published in its own source, so a Worker signing sessions with\nit accepts a cookie anyone can forge, and the only signal is one console warning printed on a cold\nstart. Throwing takes the Worker down on its first request instead.\n\nThe one way out is narrow and explicit: `BETTER_AUTH_URL` must name a loopback host (`localhost`,\n`127.0.0.1`, `[::1]`). The match is exact, so `localhost.attacker.example` and `127.0.0.1.nip.io`\ndo not open it. An **unset** `BETTER_AUTH_URL` does not open it either — a production Worker whose\nsecrets were never set looks exactly like that, which is the case this rule exists to catch.\n\nSo local dev is keyless but not configless: `BETTER_AUTH_URL=http:\u002F\u002Flocalhost:4000` is the\nlocal default in `packages\u002Fenv\u002F.env.example`, `pnpm env:setup` writes it into `apps\u002Fapi\u002F.env`,\nand `wrangler dev` then runs with no secret. Everywhere else,\nset the secret with `wrangler secret put BETTER_AUTH_SECRET`.\n\nMisconfigured prod fails **visibly** rather than silently: an origin missing from\n`CORS_ORIGINS` gets no `Access-Control-Allow-Origin` header, so the browser refuses to hand the\nresponse to the page, and Better Auth's `trustedOrigins` (fed from the same var) additionally\nanswers `403 INVALID_ORIGIN` on state-changing calls. Two independent layers — see below.\n\n### The cookie-domain rule\n\n1. `COOKIE_DOMAIN` set → used verbatim, `advanced.crossSubDomainCookies.enabled: true`.\n2. Unset, `BETTER_AUTH_URL` host is a loopback host (`localhost`\u002F`127.0.0.1`\u002F`[::1]`) → host-only\n   cookie (no `Domain` attr).\n3. Unset, host starts `api.` **and the remainder still contains a dot** → strips to the apex\n   (`api.x.com` → `.x.com`), cross-subdomain. A host like `api.dev`, whose apex would strip to a\n   bare TLD, falls through to rule 4 instead — browsers reject a TLD-only cookie domain outright.\n4. Unset, anything else → **host-only** (conservative — never guess a domain shape that isn't one\n   of the two recognized shapes; a wrong guess breaks login silently, host-only always works).\n\n## CORS lives in `api`, not here\n\n`auth`'s `trustedOrigins` reads the **same** `CORS_ORIGINS` env var as `modules\u002Fapi`'s `cors()`\nmiddleware — one origin list, two readers, no drift. If a credentialed cross-origin call is\nfailing, check `CORS_ORIGINS` on the api Worker first; auth carries zero CORS code of its own.\n\nThe two readers enforce different things, and it's worth not confusing them:\n\n| Layer | Who enforces | What an unlisted origin gets |\n|---|---|---|\n| `cors()` in api's spine | the **browser** | The Worker still runs the handler and returns a body; it just omits `Access-Control-Allow-Origin`, so the browser won't let the calling page read the response. A non-browser client (`curl`) sees the body regardless. |\n| `trustedOrigins` in Better Auth | the **server** | State-changing auth calls are rejected outright with `403 INVALID_ORIGIN` (and `403 MISSING_OR_NULL_ORIGIN` when the header is absent) — before any session work happens. |\n\nSo CORS is a read gate, not a request gate. When you need a request genuinely refused rather than\nmerely unreadable, that's `trustedOrigins` or an explicit origin check — don't rely on the CORS\nheaders to prove it.\n\n## Protect a route: the gates, never `better-auth` directly\n\n`@repo\u002Fauth\u002Fserver` exports two reads, one instance picker and five gates. The reads answer *who*; the gates answer *whether they may act*. Each one reads a fixed session or the session the request names:\n\n| Helper | Session it reads | Returns | Throws |\n|---|---|---|---|\n| `getSession(c)` | the one `x-auth-audience` names | the session, or `null` | 400 for an unknown header value |\n| `getAdminSession(c)` | always the admin session | the session, or `null` | never |\n| `authFor(c)` | the one `x-auth-audience` names | the instance, `auth` or `adminAuth` | 400 for an unknown header value |\n| `requireSession(c)` | the one `x-auth-audience` names | the session | `HTTPException(401, \"sign in first\")` |\n| `requireRole(c, role)` | always the admin session | the session | 401 as above, then `HTTPException(403, \"role required: \u003Crole>\")` |\n| `requireAdmin(c)` | always the admin session | the session | as `requireRole(c, ADMIN_ROLES)` |\n| `requireAdminApp(c)` | always the admin session | the session | as `requireRole(c, ADMIN_APP_ROLES)` |\n| `requireSuperadmin(c)` | always the admin session | the session | as `requireRole(c, \"superadmin\")` |\n\n**The `x-auth-audience` header picks the session for the generic helpers.** Its values are `client` and `admin`. No header means `client`. Any other value, the empty string included, gets 400 `x-auth-audience must be \"client\" or \"admin\"` rather than a quiet fallback to the client session. The admin app's `api` client sends `x-auth-audience: admin` on every request, so a teams or subscription screen there reads the admin who is signed in, not a client signed in on another tab. The header picks between the caller's own two cookies, so it grants nothing. Hono's `cors()` with no `allowHeaders` echoes the preflight's headers, so CORS needs no change for it.\n\n**The role gates ignore the header.** `requireRole`, `requireAdmin`, `requireAdminApp` and `requireSuperadmin` read `adminAuth` through `getAdminSession`, whatever the request says. Every site role lives in the admin group, so a client session never passes a role gate, even one that belongs to a `superadmin`. A request with only a client cookie gets 401 from them, not 403.\n\n**A route that calls Better Auth itself uses `authFor(c)`.** `authFor(c).api.getActiveMember({ headers })` reads the session the request names, so the same route serves the client app and the admin app. Calling `auth.api.*` directly reads only the client session, which is the bug `subscription`, `entitlements` and `multitenant` had before the split. Wrap the call in `withAuthScope` as above.\n\nAll of them take the whole Hono context, not `c.req.raw`. They need `c.env` to open this request's database client and `c.executionCtx` to close it, and they enter `withAuthScope` for you. See \"Either database driver\" below.\n\nReach for a gate first. A route that reads `getSession` and branches by hand is writing the same two error bodies again, and one typo in either is a hole.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fwidgets.ts\nimport { Hono } from \"hono\";\nimport { requireAdmin } from \"@repo\u002Fauth\u002Fserver\";\nimport type { AuthDbBindings } from \"@repo\u002Fauth\u002Fserver\";\n\nexport const widgets = new Hono\u003C{ Bindings: AuthDbBindings }>().get(\"\u002F\", async (c) => {\n  const session = await requireAdmin(c);\n  return c.json({ userId: session.user.id }, 200);\n});\n```\n\nThere is no `if` and no error body in that route, and that is the point. The gates throw a Hono `HTTPException`, `apps\u002Fapi`'s `onError` catches it, and `ERROR_CODES` renders it as the one envelope the api publishes: `{ \"error\": { \"code\": \"forbidden\", \"message\": \"role required: admin\" } }` on a 403, `\"unauthorized\"` on a 401. Write the check by hand and you own that shape yourself, in every route, forever.\n\nEach gate returns the session, so the caller reads `session.user.id` without a second round trip. `requireRole` takes any string, and it also takes an array to demand any one of several roles. `requireAdmin` uses that form against the exported `ADMIN_ROLES` and `requireAdminApp` against `ADMIN_APP_ROLES`, so `admin` and `superadmin` pass both today, and `requireSuperadmin` demands `superadmin` exactly. Every comparison is `===`, so `\"Admin\"` and `\"administrator\"` are not admins. Pick `requireAdmin` for admin-only work and `requireAdminApp` for a route every admin-app user may call; \"Two role lists\" below says why the two differ.\n\n`AuthDbBindings` is whichever binding shape the installed driver declares, so this route is one file under both drivers.\n\n**One role per user is the contract here, and it is narrower than better-auth's.** The plugin reads `user.role` as a comma-separated list (`has-permission.mjs` splits it on `,`), so a row holding `\"admin,support\"` is an admin to `adminAuth.api.listUsers` and gets a 403 from `requireAdmin`. `apps\u002Fadmin`'s browser guard compares with `===` too, so both halves of the gate agree with each other and both refuse the joined string. Nothing a scaffolded project writes produces one: the first-user hook writes `\"superadmin\"`, and `adminAuth.api.setRole({ body: { userId, role: \"admin\" }, headers })` writes one value. If you want stacked roles, change `hasRole` in `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` and `isAdmin` in `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` together, never one alone.\n\nKeep `getSession` for the case it was written for: a route whose answer *changes* for a signed-in caller but is still served to an anonymous one. A public page that shows a \"you already voted\" badge reads the session; it does not gate on it.\n\n```ts\nconst session = await getSession(c);\nreturn c.json({ voted: session ? await hasVoted(session.user.id) : false }, 200);\n```\n\nIf you do hand-write a deny, write the body out rather than importing a helper: `auth` depends on `api` and `database` only, so `@repo\u002Fvalidators` may not resolve. In a project that has it, `errorBody(\"unauthorized\", \"sign in first\")` from `@repo\u002Fvalidators\u002Fcommon` produces the identical shape.\n\nEvery helper wraps `getSession({ headers })` on the instance it reads, so both httpOnly cookies ride along on `c.req.raw` automatically and the instance reads only its own. No route imports `better-auth` (ADR 0020); everything goes through `@repo\u002Fauth\u002Fserver`.\n\nNote the route shape: one named `export const`, one chained expression, an explicit status on every `c.json`. That is what `hc\u003CAppType>` reads. Register it with a `chained-route` patch on the exported chain (`\"exportName\": \"default\"`), never by dropping the file and hoping (ADR 0028). `modules\u002Fadmin`'s `GET \u002Fadmin\u002Fusers` is the worked example of a gated route registered that way: it lists `adminGate` before its query validator, so a signed-out caller with a bad `?limit=` gets 401, not 400.\n\n**The gate is the api's, not the browser's.** `apps\u002Fadmin` also refuses an account outside `ADMIN_APP_ROLES`, in `beforeLoad`. That guard stops the SPA from asking; it cannot stop `curl`. A route that skips `requireAdmin` because the admin app already checks is open to anyone holding any session cookie.\n\n## Roles and the first user\n\nBetter Auth's `admin` plugin is on from the start, on both instances (`siteRoles()` in `auth.ts`). It gives `user` a `role` column, writes `\"user\"` into it for every new sign-up (except the first one, see below), refuses a banned account at sign-in, and treats the roles in `adminRoles` as privileged. Its `\u002Fadmin\u002F*` endpoints answer only on `adminAuth`.\n\n**The role strings live in `packages\u002Fconfig\u002Fsrc\u002Fsections\u002Fauth.ts`, which this module installs, and they have exactly one home.** `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` reads `config.auth.adminRole`, `config.auth.superadminRole` and `config.auth.adminAppExtraRoles`, and `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` reads the same three — a browser bundle cannot import `@repo\u002Fauth\u002Fserver`, but `@repo\u002Fconfig` has no dependencies at all, so both sides read one copy. `siteRoleMap` in `authorize.ts` keys the `admin()` plugin's statements by the same strings, so a renamed role keeps its `\u002Fadmin\u002F*` permissions. Rename either role in `packages\u002Fconfig\u002Fsrc\u002Fproject.ts`; rows already written keep the old string, so an existing project needs the `update users set role = ...` to match.\n\nThere are two site roles, and they are not interchangeable. `admin` runs `apps\u002Fadmin` for the client accounts. `superadmin` does everything `admin` does, owns the admin group (see \"Rank\" below), and is the only role that may act inside an organization it does not belong to, through the `x-organization-id` header the `multitenant` module reads. That bypass needs the superadmin signed in on the admin session; a superadmin's client session gets the ordinary 403. Inside an organization an `admin` is an ordinary member: the site role grants nothing on a tenant route, which asks `requireTenant` and reads the caller's membership instead.\n\n`adminRoles` names both, so the plugin's own endpoints admit a `superadmin` as well as an `admin`. Leaving it at the default `[\"admin\"]` would let `requireAdmin` pass a caller the plugin then refused.\n\n### Two role lists\n\n`packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` exports two lists, and they answer different questions:\n\n| List | Question | Gate | Ships with |\n|---|---|---|---|\n| `ADMIN_APP_ROLES` | Who is in the admin group: who may sign in on the admin session and open `apps\u002Fadmin`? | `requireAdminApp` | `admin`, `superadmin` |\n| `ADMIN_ROLES` | Who may do admin-only work? | `requireAdmin` | `admin`, `superadmin` |\n\nThey hold the same roles today and stay separate on purpose. `adminAuth`'s sign-in hook and the rank guard read `ADMIN_APP_ROLES`; the `admin()` plugin's `adminRoles` reads `ADMIN_ROLES`. `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` builds its own `ADMIN_APP_ROLES` from the same `config.auth` section, because a bundle cannot import from `@repo\u002Fauth\u002Fserver`, and its guard reads that list:\n\n```ts\nconst { data } = await auth.getSession();\nif (!ADMIN_APP_ROLES.some((role) => data?.user.role === role)) { \u002F* denied *\u002F }\n```\n\n`role` is typed on the admin client because `adminAuthClientPlugins` in `packages\u002Fauth\u002Fsrc\u002Fclient.ts` holds `adminClient()`, the client half of the server plugin. Keep the pair: drop the client half and `session.user.role` goes back to being an unchecked cast.\n\n### Adding a `support` role to the admin group\n\nA support agent who may sign in on the admin app but may not run admin-only routes is one role added to the group list only:\n\n1. In `packages\u002Fconfig\u002Fsrc\u002Fproject.ts`, set `auth: { adminAppExtraRoles: [\"support\"] }`. `ADMIN_APP_ROLES` on the api and in `apps\u002Fadmin` both pick it up. Leave `ADMIN_ROLES` alone.\n2. If support should reach an `admin()` plugin endpoint (for example `list-users`), give it a statement set in `siteRoles()` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`. Without one, the plugin refuses every `\u002Fadmin\u002F*` call from support. Do not add `support` to `adminRoles`, which would give it every plugin permission. A read-only set looks like this; check the statement names against the pinned better-auth's `better-auth\u002Fplugins\u002Fadmin\u002Faccess`:\n\n```ts\nimport { createAccessControl } from \"better-auth\u002Fplugins\u002Faccess\";\nimport { adminAc, defaultRoles, defaultStatements } from \"better-auth\u002Fplugins\u002Fadmin\u002Faccess\";\n\nconst ac = createAccessControl(defaultStatements);\nconst support = ac.newRole({ user: [\"list\", \"get\"], session: [\"list\"] });\n\nfunction siteRoles() {\n  return admin({\n    ac,\n    adminRoles: [...ADMIN_ROLES],\n    roles: { ...siteRoleMap({ admin: adminAc, user: defaultRoles.user }), support },\n  });\n}\n```\n\n3. Open each api route support may call with `requireAdminApp(c)`. Every `requireAdmin` route keeps refusing support with 403.\n4. Grant the role as a superadmin, through an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.setRole({ body: { userId, role: \"support\" }, headers: c.req.raw.headers })` inside `adminAuthWrite`. Only a superadmin may grant a role in `ADMIN_APP_ROLES`. The browser cannot call `\u002Fadmin\u002Fauth\u002Fadmin\u002Fset-role`: the forward answers 404.\n\nSupport is then in the admin group for the rank guard too: an `admin` may not change a support account, and only a superadmin may.\n\n### Rank: superadmin owns the admin group\n\n`adminAc` gives `admin` and `superadmin` the same `set-role`, so the `admin()` plugin alone would let an `admin` promote anyone to `superadmin`. `rankGuard()` (`packages\u002Fauth\u002Fsrc\u002Fplugins\u002Frank-guard.ts`) runs before every `\u002Fadmin\u002F*` endpoint on `adminAuth`, on an `adminAuth.api.*` call with the caller's headers as well as over HTTP, and asks `rankDenial()` in `authorize.ts`. Over HTTP the forward already answers 404 on those paths, so in practice the guard runs on the api's own calls. In order:\n\n- **Impersonation is refused for everyone**, `superadmin` included: `\u002Fadmin\u002Fimpersonate-user` gets 403 \"impersonation is not available between the client and admin sessions\". An impersonated session would be an admin-audience row for a client account, which the split forbids; without this refusal the admin sign-in hook would answer the call with a wrong-credentials message. Cross-audience impersonation is out of scope, and `auth` refuses every `\u002Fadmin\u002F*` path anyway.\n- **A caller who is not `superadmin` may read** (`list-users`, `get-user`, `list-user-sessions`, `has-permission`) and may change client accounts.\n- **Only `superadmin` may change an admin-group account or grant an admin-group role.** A write whose target holds an `ADMIN_APP_ROLES` role, or that would give one (`set-role`, `create-user`, `update-user` with `data.role`), gets 403 \"only a superadmin may change an admin-group account or role\". `revoke-user-session` checks the owner of the session token.\n- **The table fails closed.** `ADMIN_PATHS` in `authorize.ts` lists every `\u002Fadmin\u002F*` endpoint of better-auth 1.7.7's `admin()` plugin by kind. Any path not in it is superadmin-only (403 \"only a superadmin may call this admin endpoint\"), so an endpoint a Better Auth bump adds needs one line in the table before an `admin` may call it.\n- **Nobody may take the role from the last superadmin.** Removing, banning or demoting the only account that holds `superadmin` gets 403 \"the last superadmin cannot be removed, banned or demoted\", whoever calls.\n\nThe guard reads target roles through `@repo\u002Fdb\u002Frepositories\u002Fsite-roles`, not the adapter, because the scoped adapter cannot see a session of the other audience.\n\n### First user wins\n\nThe first account to sign up on an empty `users` table gets `role: \"superadmin\"`. A `databaseHooks.user.create.before` hook in `sharedOptions()` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` reads the table before the row is written, so it can only match on the very first sign-up; every account after that keeps the plugin's default `\"user\"`. This is the only automatic promotion in the system, and it is what makes `saasaloy add admin` usable without SQL. It writes `superadmin` rather than `admin` because the first account has to be able to grant every other one, and only `superadmin` may change an admin-group role.\n\nBoth instances carry the hook, and in practice it fires on `auth`: `adminAuth` has no sign-up. So the first account signs up as a client, through `POST \u002Fauth\u002Fsign-up\u002Femail` or a client app's sign-up screen, and then signs in on the admin app with the same email and password. Both instances read one `accounts` table, so no second account is needed.\n\n**Client sign-up is open, so that first slot is a race you can lose.** Any account that reaches `\u002Fauth\u002Fsign-up` before you do becomes the superadmin, and on a deployed API with a public origin the window is real. Sign up yourself the moment the API answers its first request, then confirm with `select email, role from users`. Two sign-ups that land at the same instant both read an empty table and both become superadmin; that is accepted rather than locked, because a unique index on `role = 'superadmin'` would also block a deliberate second one later.\n\nIf somebody else got there first, or you are promoting an account on a project that already has users, flip the row by hand. Run this from the project root; `--filter @repo\u002Fdb` puts the working directory in `packages\u002Fdb`, which is what the relative paths are written against. The statement is the same under both drivers:\n\n```sql\nupdate users set role = 'superadmin' where email = 'you@example.com';\n```\n\n**How you run it is the driver's business**, so read the skill for the driver this project\ninstalled — `saasaloy-database-d1` or `saasaloy-database-postgres` — for the console it hands you.\nSwap `update` for `select email, role from users` to check it landed. The plural table name\nneeds no quotes: Postgres reserves `user`, not `users`.\n\nThe change takes effect on the next `getSession` call, because sessions are DB-backed and the role is read off the user row, and `cookieCache` is off (see the last boundary below). An account that is already signed in on the admin session needs no re-login. An account promoted from `user` has no admin session yet: it signs in on the admin app, because `adminAuth` refused it before the promotion. Demoting an account works the other way: its admin session stays in the table, but every role gate and the admin app's guard refuse it from the next request, and the admin app shows the refusal page.\n\nOnce one superadmin exists, promote the rest through the API instead of SQL: an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.setRole({ body: { userId, role: \"admin\" }, headers: c.req.raw.headers })` inside `adminAuthWrite`, so the change leaves an audit row. `\u002Fadmin\u002Fauth\u002Fadmin\u002Fset-role` itself answers 404 over HTTP. The call authorizes against the caller's own role and the rank guard above, so only a superadmin may grant `admin` or `superadmin`. Grant `admin` for a backoffice user and keep `superadmin` for the accounts that own the admin group and may cross an organization boundary. The plugin also carries `listUsers`, `banUser` and friends on `adminAuth.api`. `impersonateUser` is there too, and the rank guard refuses it.\n\n**A project that installed auth before this shipped needs a migration.** The four new `users` fields and `sessions.impersonatedBy` are schema changes like any other: run `pnpm --filter @repo\u002Fdb db:generate`, read the emitted SQL, then apply it with the command from the installed driver's skill. Existing users come out of it with `role` null, which is neither site role, so the guard denies them until you promote one.\n\n**`accounts.issuer` is the one that needs a hand.** better-auth 1.7.2 made it required and put a unique index over (`issuer`, `accountId`); 1.7.3 took both back out, so the pinned snapshot no longer carries them and (`providerId`, `accountId`) is the row's identity again. A project that never applied the 1.7.2 migration needs nothing here. A project that already applied it gets the reverse from `db:generate`:\n\n```sql\nDROP INDEX `accounts_issuer_account_id_uidx`;--> statement-breakpoint\nALTER TABLE `accounts` DROP COLUMN `issuer`;\n```\n\nTake the index identifier from your own generated migration rather than from the snippet above. Drizzle derives it from the schema the 1.7.2 migration was generated against, so a project that kept better-auth's own naming sees `account_issuer_accountId_uidx` instead, and a `DROP INDEX` on a name that is not there fails and leaves `issuer` in place.\n\nRead it before you apply it, because a `DROP COLUMN` is not reversible and SQLite rewrites the table to do it. Take a copy of the database first. A Postgres project gets the same two statements with `DROP INDEX \"accounts_issuer_account_id_uidx\"` and `ALTER TABLE \"accounts\" DROP COLUMN \"issuer\"`. Nothing reads the column after the drop: better-auth 1.7.3's `getAuthTables()` never writes it and the adapter never selects it.\n\nLeaving the column in place is the option that breaks. The snapshot no longer declares it, so `db:generate` treats it as drift on every later run, and a fresh insert against a database that still has `issuer text NOT NULL` fails the constraint the moment 1.7.3 stops writing the value.\n\n## Seed users and the dev password\n\n`auth` ships seed slices for its four tables, so `pnpm db:seed` gives a development database four users, one for each way the admin app shows a user:\n\n| Email | Role | Notes |\n| --- | --- | --- |\n| `superadmin@example.test` | `superadmin` | sign in here to reach every admin page |\n| `admin@example.test` | `admin` | |\n| `member@example.test` | `user` | a client: signs in on `\u002Fauth`, refused on the admin app |\n| `banned@example.test` | `user` | banned, so sign-in is refused |\n\nEvery one has an email-and-password account with the password **`saasaloy-dev-password`**, and `db:seed` prints it after the counts. The hash in `packages\u002Fdb\u002Fsrc\u002Fseed\u002Fslices\u002Faccounts.ts` is precomputed in Better Auth's own format, so the seed never loads Better Auth. `sessions` and `verifications` ship empty slices: a seeded session would carry a token nobody holds.\n\nA seeded database already holds a superadmin, so the first-user promotion above does not fire there: the first person to sign up gets `user`. Sign in on the admin app as `superadmin@example.test` instead. Never seed a database other people can reach; the password is in this file.\n\n`auth` also ships the example route test, `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.test.ts`. It signs the seeded superadmin in through `POST \u002Fauth\u002Fsign-in\u002Femail` and checks the session row, then a second test proves that row is gone. The rest pins the split: both cookies in one browser, a token copied into the other cookie, the admin sign-in refusal, `\u002Fauth\u002Fadmin\u002F*` refused, the rank rules and the impersonation refusal. A Better Auth bump that changes how a session is found fails these tests. Copy its shape for a route of your own; the database driver's skill, \"Route tests\", explains `testDatabase()`.\n\n## Revocation: delete the session row\n\nSessions are DB-backed on purpose (build-spec §2.5) — revoking one is a delete, no token\ndenylist needed:\n\n```sql\ndelete from sessions where id = '...';\n-- or, to kill every session for a user:\ndelete from sessions where user_id = '...';\n```\n\nThe next authed request with that cookie gets `401` from `getSession`.\n\n**One user has one sessions table, so a revocation by user ends both audiences.** A password change with `revokeOtherSessions: true`, the admin plugin's `revoke-user-sessions`, or the `delete ... where user_id` above signs that user out of the client session and the admin session alike. To end only one, delete by id, or add `and audience = 'client'` (or `'admin'`) to the statement.\n\n## `@auth\u002Fclient`: two factories, framework-agnostic\n\n`packages\u002Fauth\u002Fsrc\u002Fclient.ts` wraps `createAuthClient` (ships inside `better-auth`, no new npm dep). There are no React bindings and none are planned. It exports one factory per instance, and a browser bundle picks the one for its user group:\n\n| Factory | Instance | `basePath` | Plugin array | Used by |\n|---|---|---|---|---|\n| `createClient(baseURL)` | `auth` | `\u002Fauth` | `authClientPlugins` (empty by default) | every client-facing app |\n| `createAdminClient(baseURL)` | `adminAuth` | `\u002Fadmin\u002Fauth` | `adminAuthClientPlugins` (holds `adminClient()`) | `apps\u002Fadmin` only |\n\n```ts\nimport { createClient } from \"@repo\u002Fauth\u002Fclient\";\n\nconst client = createClient(\"https:\u002F\u002Fapi.x.com\"); \u002F\u002F same origin as BETTER_AUTH_URL\nawait client.signUp.email({ email, password, name });\nawait client.signIn.email({ email, password });\n```\n\n`apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` builds its client with `createAdminClient(apiBaseUrl)` and exports it as `auth`, so a module screen that imports `auth` from `@admin\u002Flib\u002Fauth` reaches the admin session with no change. The admin client has no `signUp`: the server refuses it.\n\n`fetchOptions: { credentials: \"include\" }` is baked into both. The calling origin must be in `CORS_ORIGINS` (api's spine) for the cookie to be set and sent cross-origin.\n\n`adminClient()` rides on the admin client only, mirroring the server's `admin()`. That is what types `session.user.role`. It also puts `auth.admin.*` on the admin app's client, but the api's forward answers 404 to every `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` path, so no browser code calls those methods. A staff screen calls an api route under `\u002Fadmin\u002F` instead, which writes the audit row. A feature module that ships a client plugin patches both arrays. Keep each array literal and never delete one, even when it is empty.\n\n## Wire-up: the sign-in and sign-up blocks\n\n`auth` ships two blocks into `@repo\u002Fui`, with the frame they share. Each entry carries `when: { installed: [\"shell\"] }`, because the blocks render the `shell` primitives. A project with no signed-in app gets none of them. `saasaloy add admin` or `saasaloy add app` brings `shell`, and the same run writes the blocks (the backfill).\n\n| File | Exports |\n|---|---|\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fsign-in.tsx` | `SignInCard`, `SignInValues` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fsign-up.tsx` | `SignUpCard`, `SignUpValues` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fauth-card.tsx` | `AuthCard`, `AuthAlert`, `useAuthSubmit`, the frame both cards use |\n\nThe blocks do no IO, per the `@repo\u002Fui` rule. They import no auth client, no router, no store and no env. The app renders a block on its own route and owns the call:\n\n- **`onSubmit(values)` returns `Promise\u003Cstring | undefined>`.** Return a message and the card shows it in a `role=\"alert\"` line above the button. Return `undefined` (or nothing) on success, after you navigate. Do not write `string | void`: the project lint rejects `void` in a union, and the type does not match.\n- **Catch your own network failure.** A throw resets the button and reaches the console, but the card shows nothing. Turn it into a returned message, as the example below does.\n- **`SignInCard` takes `signUpHref?`, `title?` and `description?`.** With no `signUpHref`, the card has no footer. `admin` passes its own title and description and no `signUpHref`.\n- **`SignUpCard` takes `signInHref`, `title?` and `description?`.** Its password field asks for 12 characters, the server's `minPasswordLength` (see \"Password rules\"). Change both together.\n- **The block renders the card, not the page.** Centre it on your app's canvas: `app` uses `bg-sidebar`, `admin` uses `bg-background`.\n\nA sign-in route in a TanStack Router app. `@app\u002Flib\u002Fauth` stands for the app's own client file: `createClient(apiBaseUrl)` from `@repo\u002Fauth\u002Fclient`, with the url from the app's env gate, as `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` does with `createAdminClient`.\n\n```tsx\nimport { createFileRoute, useRouter } from \"@tanstack\u002Freact-router\";\nimport { SignInCard } from \"@repo\u002Fui\u002Fblocks\u002Fauth\u002Fsign-in\";\nimport type { SignInValues } from \"@repo\u002Fui\u002Fblocks\u002Fauth\u002Fsign-in\";\nimport { auth } from \"@app\u002Flib\u002Fauth\";\n\nexport const Route = createFileRoute(\"\u002Fsign-in\")({ component: SignInScreen });\n\nfunction SignInScreen() {\n  const router = useRouter();\n\n  async function handleSignIn(values: SignInValues): Promise\u003Cstring | undefined> {\n    try {\n      const { error } = await auth.signIn.email(values);\n      if (error) {\n        return error.message ?? \"Sign-in failed. Check the email and password.\";\n      }\n    } catch {\n      return \"Could not reach the api. Check that it is running.\";\n    }\n    await router.navigate({ to: \"\u002F\" });\n  }\n\n  return (\n    \u003Cmain className=\"bg-sidebar flex min-h-dvh items-center justify-center p-4\">\n      \u003CSignInCard onSubmit={handleSignIn} signUpHref=\"\u002Fsign-up\" \u002F>\n    \u003C\u002Fmain>\n  );\n}\n```\n\n`SignUpCard` follows the same shape, with `auth.signUp.email({ name, email, password })` and `signInHref=\"\u002Fsign-in\"`.\n\n**Styles.** The blocks are under `packages\u002Fui\u002Fsrc\u002Fblocks\u002F`, which `globals.css` scans. An app stylesheet that does not import `globals.css`, such as one built on `brand.css`, adds `@source \"..\u002Fblocks\u002Fauth\u002F**\u002F*.tsx\";`, or the card renders unstyled with no error.\n\n**Lint.** The base `oxlint.config.mjs` twin-primitive rule covers `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002F**`, so a base primitive in a block is a lint error. A project made before this rule copies the glob from the base template.\n\n**Removal.** `saasaloy remove shell` refuses while `admin` or `app` is installed. When it runs, it deletes the three block files with it, so delete each route that imports them first.\n\n## Signed-in state on the static site\n\nThe base `apps\u002Fweb` is a prerendered Astro site, and no module puts a header with a session on it. When a project adds one (a \"Log in\" link that turns into an avatar), two faults are waiting. The session lives in an httpOnly cookie on the api origin, so the page learns who is signed in only when a session check answers:\n\n- The header shows \"Log in\" first and swaps to the avatar after the check, a visible jump on every load (2.5 s in one project).\n- A sign-in form that signs in without a page load leaves a header that checked on mount still showing \"Log in\".\n\nUse two pieces, both in `apps\u002Fweb\u002Fsrc\u002Flib\u002F`:\n\n- **A `session:change` event.** One seam, `session.ts`, owns `getSession()` on the client factory. Export `announceSessionChange()`, which dispatches `new Event(\"session:change\")` on `window`, and `onSessionChange(listener)`, which returns the unsubscribe. Call `announceSessionChange()` after each sign-in and sign-out. Every island that shows the session (the header, an account panel) listens and checks again.\n- **A first-paint hint.** `session-hint.ts` stores one flag in `localStorage` each time a check answers: `\"1\"` while signed in, removed when not. An inline script in `\u003Chead>` of `Layout.astro` (`\u003Cscript is:inline set:html={SESSION_HINT_SCRIPT} \u002F>`, a string, because a module script runs after the paint) sets `data-session=\"in\"` on `\u003Chtml>` from that flag. The header renders both states, and CSS under `[data-session=\"in\"]` shows one, so server and client markup match and hydration does not warn.\n\nThe flag holds no name and no id, so a shared device shows nothing about the user. The cookie stays the truth: a stale flag costs one swap, and the next check clears it. Wrap every `localStorage` access in `try`, because storage can be off.\n\n## Password rules\n\nBoth instances set `minPasswordLength: 12` (`MIN_PASSWORD_LENGTH` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`). Better Auth applies it on sign-up, on a password reset and on a password change, and answers `400` with `code: \"PASSWORD_TOO_SHORT\"`. It never applies it on sign-in, so an account made before the rule, with a shorter password, still signs in. Keep the number and the sign-up form's hint in step. A project made before this rule gets it through `saasaloy update auth`.\n\n## Password reset mail\n\n`auth` does not depend on `email`. When `email` is in the project, `auth` ships the reset mail as well. Each of these entries carries `when: { installed: [\"email\"] }` (ADR 0054):\n\n| Entry | What it does |\n|---|---|\n| `packages\u002Fauth\u002Fsrc\u002Fplugins\u002Freset-password-mail.ts` | A Better Auth plugin whose `init()` sets `emailAndPassword.sendResetPassword`. It sends through `createEmail(env)`, with `env` from `cloudflare:workers`. |\n| `resetPasswordMail()` in `auth`'s `plugins` array | A `plugin-array` patch. Only the client instance sends the mail: `adminAuth` reads the same `accounts` table, so a new password counts there too. |\n| `@repo\u002Femail` in `packages\u002Fauth\u002Fpackage.json` | A `package-json-dependency` patch. |\n| `packages\u002Femail\u002Fsrc\u002Ftemplates\u002Freset-password.ts` | The template, in the `email` module's convention. Edit it like `welcome.ts`. |\n| `apps\u002Fapi\u002Fsrc\u002Froutes\u002Freset-password.test.ts` | The route test, only when testing is on too. It replaces `createEmail` with a sender that keeps each message. |\n\n`saasaloy add email` in a project that already has `auth` writes all of them in the same run (the backfill). `saasaloy add auth` in a project with `email` writes them at once.\n\n**Use it.** The client calls Better Auth's endpoint, and the mail goes to the address if it has an account:\n\n```ts\nawait authClient.requestPasswordReset({\n  email,\n  redirectTo: `${location.origin}\u002Freset-password`,\n});\n```\n\n`POST \u002Fauth\u002Frequest-password-reset` answers `200` with the same message for a known and an unknown address, so it does not tell a caller which addresses have accounts. The mail carries Better Auth's link, `\u003CBETTER_AUTH_URL>\u002Fauth\u002Freset-password\u002F\u003Ctoken>?callbackURL=\u003CredirectTo>`. That endpoint checks the token and redirects to `redirectTo` with `?token=`. The `redirectTo` origin has to be in `trustedOrigins` (`CORS_ORIGINS`, or the localhost dev list), or the request answers `403`. The token lives for 60 minutes. The page that reads the token and calls `authClient.resetPassword({ newPassword, token })` is the app's: no module ships it yet (#230 plans it).\n\n**Check it locally.** With `email-console` and `EMAIL_PROVIDER=console`, the mail prints to the api's stdout:\n\n```sh\ncurl -X POST http:\u002F\u002Flocalhost:4000\u002Fauth\u002Frequest-password-reset \\\n  -H 'content-type: application\u002Fjson' -H 'origin: http:\u002F\u002Flocalhost:3000' \\\n  -d '{\"email\":\"member@example.test\",\"redirectTo\":\"http:\u002F\u002Flocalhost:3000\u002Freset-password\"}'\n```\n\n**Failure modes.**\n\n- The request answers `400` with `code: \"RESET_PASSWORD_DISABLED\"`: `email` is not installed, or the `resetPasswordMail()` line is missing from `auth`'s `plugins`. Run `saasaloy add email`, or put the line back.\n- The request answers `200` but no mail arrives: the sender threw. Better Auth logs the error and answers as usual, on purpose. Read the api log. The usual causes are an unset `EMAIL_PROVIDER` or `EMAIL_FROM`, and a `BETTER_AUTH_URL` that is not `https` outside localhost, which `safeUrl` refuses.\n- After `saasaloy remove email`, `pnpm install` fails on `@repo\u002Femail`: `remove` deletes the reset files and reverts the `plugins` line, but it does not reverse a `package-json-dependency` patch. Delete `\"@repo\u002Femail\"` from `packages\u002Fauth\u002Fpackage.json` by hand.\n\n## Enabling social OAuth \u002F email verification (not wired)\n\n- **Social providers** (Google, GitHub, …): add a `socialProviders` block to\n  `packages\u002Fauth\u002Fsrc\u002Fauth.ts` yourself — not pre-wired, since it needs per-provider client\n  IDs\u002Fsecrets this module can't invent safely.\n- **Email verification**: `requireEmailVerification` stays off, with or without `email`. Turning it\n  on needs a `sendVerificationEmail` sender, written the same way as `reset-password-mail.ts`, and a\n  verification screen in each app. Turning it on with no provider configured makes sign-up appear\n  to hang or silently fail. The password reset mail is wired: see \"Password reset mail\".\n\n## Schema: hand-authored, never generated at `add` time\n\n`packages\u002Fdb\u002Fsrc\u002Fschema\u002Fauth.ts` (one of `auth.sqlite.ts` and `auth.pg.ts`, chosen by the\ninstalled driver) is a **checked-in Drizzle snapshot** of Better Auth's core tables (`users`, `sessions`, `accounts`, `verifications`) plus the\nfields the `admin` plugin adds (`users.role`, `banned`, `ban_reason`, `ban_expires`, and\n`sessions.impersonated_by`), plus `sessions.audience` from this module's own `audience()` plugin (text, not null, default `'client'`), pinned to the exact `better-auth` version in\n`packages\u002Fauth\u002Fpackage.json` — not run through a generator at add-time (no exec, deterministic, `--diff`-able). If you bump `better-auth`, **re-verify this file against the new version's schema** (`@better-auth\u002Fcore`'s `getAuthTables()`, and the admin plugin's own `schema` export) before shipping — fix the snapshot, not the adapter config, on a mismatch. The adapter matches on the Drizzle **property** name (`banReason`), not the SQL column name (`ban_reason`), and does no case conversion. It's picked up by database's existing barrel + migration scripts same as any other table:\n\n```sh\npnpm --filter @repo\u002Fdb db:generate       # emits SQL for the new tables\n```\n\nThe rule has a guard in this repo. The snapshot's header names the version it was verified against, and `modules\u002Fauth\u002Ffiles\u002Fsrc\u002Fschema-version.test.ts` fails `pnpm test` when that string and `better-auth` in `modules\u002Fauth\u002Ffiles\u002Fpackage.json` disagree. It cannot check a column; it makes a bump that skipped the re-verification loud instead of silent. Do the comparison, fix what moved, then edit the header. Editing the header alone to get green is the one way to defeat it.\n\nThe 1.7.2 → 1.7.3 pass is the worked example of what \"re-verify\" means here. It found one change, and it was a removal: `accounts.issuer` and its unique index are gone from `getAuthTables()`, so they came out of both snapshots and the headers say so. The admin plugin's own `schema` export did not move.\n\n`db:generate` belongs to the `database` core and is the same command under either driver. **The\napply step is the driver's**, and the command differs, so read the skill for the driver this\nproject installed: `saasaloy-database-d1` or `saasaloy-database-postgres`.\n\nBoth variants have to stay in step. Edit one table and edit its twin — `add auth` installs only the\none matching the project's driver, so a mismatch shows up on the other driver's first install, long\nafter the edit.\n\n## Upgrading from singular table names\n\nA project that installed auth before the tables became plural has `user`, `session`, `account` and `verification` in its database. Move them to the new names like this:\n\n1. Run `saasaloy update auth`. It takes the new schema file and the `auth.ts` that passes `usePlural: true`. The schema rename and `usePlural` must land together, because one without the other breaks sign-in. Update auth before `teams`, `api-keys` and `subscription`.\n2. Run `pnpm db:generate`.\n3. drizzle-kit asks, for each new table, whether it is created or renamed from an existing table. Pick the rename from the old name: `user` → `users`, `session` → `sessions`, `account` → `accounts`, `verification` → `verifications`.\n4. Read the generated SQL before you apply it. It must rename the tables and the indexes (`ALTER TABLE ... RENAME TO ...`, and `session_user_id_idx` → `sessions_user_id_idx`, `account_user_id_idx` → `accounts_user_id_idx`, `verification_identifier_idx` → `verifications_identifier_idx`). It must contain no `DROP TABLE` or `CREATE TABLE` for a table that holds data.\n5. If it drops a table, delete that migration file and run `pnpm db:generate` again.\n6. Apply the migration with the command from the installed driver's skill, then sign in once to confirm the adapter finds every table.\n\n## Upgrading a project made before the client\u002Fadmin split\n\nA project made before the split has one instance and one `better-auth.session_token` cookie. Move it to two instances in this order:\n\n1. Run `saasaloy update auth admin`.\n2. Resolve the merge plan for `packages\u002Fauth\u002Fsrc\u002Fauth.ts`, `packages\u002Fauth\u002Fsrc\u002Fclient.ts`, `packages\u002Fauth\u002Fsrc\u002Fserver.ts` and `@db\u002Fschema\u002Fauth.ts`. Take the new `adminAuth` export, `adminAuthClientPlugins`, `createAdminClient` and the `audience` column. Carry over any plugin or option you added by hand to both instances.\n3. Run `pnpm db:generate`. It writes one migration that adds `sessions.audience` with default `'client'`. Read it, then apply it with `pnpm db:migrate:local`, or the production migrate command from the installed driver's skill.\n4. Run `saasaloy update` for each installed module that patches auth: `teams`, `api-keys` and `subscription-stripe`. Each one now adds its plugin to `adminAuth` and to `adminAuthClientPlugins` as well.\n\nRun step 4 after step 2. Before the merge, `auth.ts` has no `adminAuth` export, and the patch prints a warning that names the missing export. That warning means \"merge `auth.ts` first\", and the module's lock entry stays where it was, so running `saasaloy update \u003Cmodule>` again after the merge applies the patch.\n\nEvery existing session ends, because the cookie names change from `better-auth.session_token` to `client.session_token` and `admin.session_token`. Old session rows read as client rows through the column default, but no browser holds a cookie that names them. Tell your users they must sign in again. A route of your own that calls `auth.api.*` reads only the client session after the update; switch it to `authFor(c).api.*` if the admin app calls it. A middleware of your own on `\u002Fadmin\u002F*` must now skip `\u002Fadmin\u002Fauth\u002F*`.\n\n## Boundaries to honor\n\n- **Only `packages\u002Fauth` imports `better-auth`.** Every other workspace goes through\n  `@repo\u002Fauth\u002Fserver` \u002F `@repo\u002Fauth\u002Fclient` (ADR 0020).\n- **`auth` and `adminAuth` stay module-scope singletons** in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`. Don't refactor them into a per-request factory; that would break the plugin-array patch points every future capability relies on. The database behind it stays request-scoped for the opposite reason (ADR 0029);\n  don't collapse the two by binding a client at module scope.\n- **Every `api.*` and `handler` call on either instance runs inside `withAuthScope`.** Don't add a fallback\n  that opens a client when the scope is empty: that path has no `executionCtx` to close the socket\n  on, which is the leak the wrapper exists to prevent.\n- **`plugins` stays a literal array** in each `betterAuth({ ... })` call. Never omit it, never hoist it to a named const, and never drop `audience(...)` or `siteRoles()` from it. A feature plugin goes into both arrays.\n- **Keep the audience scoping.** Don't unwrap `scopeSessionsTo` or drop the `audience` column: without them a client token copied into the admin cookie is an admin session.\n- **`\u002Fadmin\u002Fauth\u002F*` belongs to `adminAuth`.** Don't mount a route under it, and make any `\u002Fadmin\u002F*` middleware skip it.\n- **CORS is api's job.** Don't add CORS handling here; reuse `CORS_ORIGINS`.\n- **Sessions are DB-backed; `cookieCache` stays off** — revocability over the marginal latency of\n  one database read per request.\n- **The dialect lives in the two schema variants and in `db-provider.ts`, nowhere else.** A\n  `sqlite-core` or `pg-core` import outside `files\u002Fdb\u002Fschema\u002Fauth.*.ts`, or a `provider:` string\n  written inline in `auth.ts`, pins this module to one driver again.\n\n## Next\n\nRun `saasaloy-app` to give a signed-in user a home, with the sign-in and sign-up blocks on its routes.\n","# auth — Better Auth, httpOnly cookies + subdomains\n\n`packages\u002Fauth` (`@repo\u002Fauth`) owns [Better Auth](https:\u002F\u002Fbetter-auth.com) outright (ADR 0020), and no other workspace depends on `better-auth` directly. `apps\u002Fapi` gets a thin `routes\u002Fauth.ts` that forwards to the two instances' handlers; `packages\u002Fdb` gets a hand-authored schema snapshot. Sessions are **DB-backed httpOnly cookies**, not JWTs (build-spec §2.5 \u002F ADR 0004): one database read per request is negligible, and sessions are instantly revocable by deleting the row.\n\n## Two instances: the client session and the admin session\n\nA project has two user groups. The **client** group is the shopper, the customer, the app user, and its only site role is `user`. The **admin** group is every role in `ADMIN_APP_ROLES` (`superadmin` and `admin` ship). Each group signs in on its own Better Auth instance, both built in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` on the same four tables:\n\n| Export | Group | `basePath` | Cookie | Sign-up |\n|---|---|---|---|---|\n| `auth` | client | `\u002Fauth` | `client.session_token` | open |\n| `adminAuth` | admin | `\u002Fadmin\u002Fauth` | `admin.session_token` | none (`disableSignUp: true`) |\n\nIn production both cookies carry the `__Secure-` prefix. `advanced.cookiePrefix` sets the name, so a client and an admin stay signed in together in two tabs of one browser, and a sign-out in one tab leaves the other signed in. The decision record is [ADR 0050](..\u002F..\u002F..\u002F..\u002Fdocs\u002Fadr\u002F0050-adr-client-and-admin-sessions-are-two-auth-instances-2026-10-23.md).\n\nEverything the two share (the adapter, the secret, `trustedOrigins`, the first-user hook, `advanced`) lives in `sharedOptions(group)`. Each `betterAuth({...})` spreads it and keeps its own literal `plugins: [...]`.\n\n**The audience column keeps the two apart.** `sessions.audience` is `client` or `admin`, not null, default `'client'`, in both driver schemas. The `audience(name)` plugin in `packages\u002Fauth\u002Fsrc\u002Fplugins\u002Faudience.ts` declares the field with `input: false` (no endpoint can set it) and writes the instance's name into every new row. Each instance wraps its `drizzleAdapter` in `scopeSessionsTo(adapter, group)` from `packages\u002Fauth\u002Fsrc\u002Fscoped-adapter.ts`, so a session lookup by token finds only rows of its own audience. A token copied into the other cookie is no session at all: every endpoint, middleware and `api.*` call on that instance sees `null`. `decide()` in `authorize.ts` checks the audience a second time behind the adapter.\n\n**`adminAuth` refuses a user outside the admin group.** The admin instance registers `audience(\"admin\", { roles: ADMIN_APP_ROLES })`, whose `session.create.before` hook refuses to open a session for a user whose role is not in the list. The answer is Better Auth's own `INVALID_EMAIL_OR_PASSWORD` (\"Invalid email or password\"), so the admin login tells an attacker nothing about which addresses hold an account. The `accounts` table is shared, so an admin signs in on the admin app with the same email and password the account uses on the client side.\n\n**The client instance refuses every admin endpoint.** Both instances keep the `admin()` plugin, because it writes the default `\"user\"` role, types `user.role` and refuses a banned account at sign-in. On `auth`, `clientAdminGuard()` (`packages\u002Fauth\u002Fsrc\u002Fplugins\u002Fclient-admin-guard.ts`) answers 403 `ADMIN_SESSION_REQUIRED` on every `\u002Fauth\u002Fadmin\u002F*` path. It matches the path prefix, so an endpoint a Better Auth bump adds is refused too.\n\n**The admin forward closes the same endpoints over HTTP.** `adminAuthRoute` in `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` answers 404 on every `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` path, reads and impersonation included, before it forwards to `adminAuth.handler`. It decodes the path and folds case and repeated slashes, so an encoded path gets the same 404. No browser code calls these endpoints, and an open `set-role` or `ban-user` would be a staff write with no audit row, under `\u002Fadmin\u002Fauth\u002F*` where the `admin` module's audit coverage test cannot see it (issue #310). Server code still reaches them: an api route under `\u002Fadmin\u002F` calls `adminAuth.api.*` with the caller's headers inside `withAuthScope`, and `adminAuthWrite` from the `admin` module when it changes something. That call runs the admin session check and the rank guard below.\n\n**`\u002Fadmin\u002Fauth\u002F*` is reserved.** The `auth` module mounts `adminAuthRoute` at `\u002Fadmin\u002Fauth` with a second `chained-route` patch on `base`, beside `authRoute` at `\u002Fauth`. The path sits under `\u002Fadmin` so one edge rule (WAF, Access, a log filter) covers the whole admin group on the api. A middleware a project adds on `\u002Fadmin\u002F*` must skip `\u002Fadmin\u002Fauth\u002F*`, or the sign-in endpoint itself demands a session. A project without the `admin` module still has the `\u002Fadmin\u002Fauth` route; nothing calls it.\n\n## Either database driver\n\nThis module installs against `database-d1` or `database-postgres`, and picks the right files for\nwhichever one the project holds. It depends on `api` and `database`, and names no driver:\n`database`'s own `requiresOneOf` is what guarantees one is present.\n\nTwo files ship twice, and nothing else does:\n\n| Source in the module | Installs when | What differs |\n|---|---|---|\n| `files\u002Fdb\u002Fschema\u002Fauth.sqlite.ts` | `onlyWith: \"database-d1\"` | `sqliteTable`, `drizzle-orm\u002Fsqlite-core`, millisecond-integer dates |\n| `files\u002Fdb\u002Fschema\u002Fauth.pg.ts` | `onlyWith: \"database-postgres\"` | `pgTable`, `drizzle-orm\u002Fpg-core`, `timestamptz` dates, `boolean` flags |\n| `files\u002Fsrc\u002Fdb-provider.d1.ts` | `onlyWith: \"database-d1\"` | `provider: \"sqlite\"`, and `withAuthScope` runs the body |\n| `files\u002Fsrc\u002Fdb-provider.pg.ts` | `onlyWith: \"database-postgres\"` | `provider: \"pg\"`, and `withAuthScope` wraps `withDb` |\n\nEach pair names one `target` — `packages\u002Fdb\u002Fsrc\u002Fschema\u002Fauth.ts` and\n`packages\u002Fauth\u002Fsrc\u002Fdb-provider.ts` — so exactly one of the two lands and the other is filtered out\nbefore the plan is built. `saasaloy add auth --dry-run` prints which source it chose.\n\n`auth.ts`, `env.ts`, `server.ts`, `client.ts` and `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` are single files\nunder both drivers. The dialect reaches the table declarations and the four lines of\n`db-provider.ts`, and stops there.\n\nThe two schema variants are the same four tables, so keep them in step. They differ only where each\ndialect is idiomatic. A row comes back the same shape either way.\n\n**Switching driver is remove-then-add, and it takes this module with it.** The unchosen variant is\nfiltered before planning, so a project that swaps drivers keeps the schema it already installed.\nRemove `auth` and add it again after the driver switch to get the other variant. There is no data\nmigration; see ADR 0026.\n\n## The database client is request-scoped\n\n`auth` and `adminAuth` are module-scope singletons whose database client belongs to a single request. That split is the one thing to understand before writing a call against `auth.api.*` or `adminAuth.api.*`.\n\nWhy it exists: a Workers isolate outlives the request that created it, but an open socket does not.\nUnder `database-postgres`, a client bound once at module scope serves the first request and then\nthrows `Cannot perform I\u002FO on behalf of a different request` on the second. A single manual sign-in\ndoes not catch it; it takes two requests into one worker.\n\nHow it works: `drizzleAdapter` is handed `authDb`, a proxy holding no client of its own. It reads\nthe current request's client out of an `AsyncLocalStorage` in `packages\u002Fauth\u002Fsrc\u002Fdb-scope.ts`.\n`withAuthScope(c, fn)` in `packages\u002Fauth\u002Fsrc\u002Fdb-provider.ts` is what puts it there — under\nPostgres by wrapping the driver's `withDb`, which also closes the socket on\n`c.executionCtx.waitUntil`; under D1 by opening a binding stub and running the body.\n\n**The adapter runs with `usePlural: true`.** Better Auth asks for singular models (`user`, `session`), and the tables here are plural (`users`, `sessions`). The Drizzle adapter finds a table by its export key in the schema object, never by its SQL name, and `usePlural` appends an `s` to every model name, a custom `modelName` included. Keep the flag and the plural export keys together: remove one and every auth call throws `The model \"user\" was not found in the schema object`, which `pnpm typecheck` does not catch. A plugin with `modelName: \"X\"` needs the export key `Xs`. The naming rule is in the `saasaloy-database` skill under `## Table names`, and ADR 0038 records it.\n\n**Every `handler` and `api.*` call on either instance runs inside `withAuthScope`.** `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.ts` already wraps both handlers, and `getSession(c)` and the gates already wrap their own reads, so ordinary use needs nothing. Reach for the wrapper by hand only when calling an instance yourself:\n\n```ts\nimport { adminAuth, withAuthScope } from \"@repo\u002Fauth\u002Fserver\";\n\nconst users = await withAuthScope(c, () => adminAuth.api.listUsers({ query: {}, headers: c.req.raw.headers }));\n```\n\nForget it and the read throws with a message naming `withAuthScope` — **on both drivers**, D1\nincluded. That is deliberate. D1 is the default driver, so most development happens there, and a\npermissive D1 path would let the mistake pass every local test and surface only after a project\nswitched to Postgres. The cost on D1 is one property lookup per call. See ADR 0029.\n\n## The plugin-array patch points (read this before adding subscription\u002Fteams)\n\n`packages\u002Fauth\u002Fsrc\u002Fauth.ts` exports two **module-scope singletons**, each with its own literal plugin array:\n\n```ts\nexport const auth = betterAuth({\n  ...sharedOptions(CLIENT_AUDIENCE),\n  basePath: \"\u002Fauth\",\n  \u002F\u002F ...\n  plugins: [audience(CLIENT_AUDIENCE), siteRoles(), clientAdminGuard()],\n});\n\nexport const adminAuth = betterAuth({\n  ...sharedOptions(ADMIN_AUDIENCE),\n  basePath: \"\u002Fadmin\u002Fauth\",\n  \u002F\u002F ...\n  plugins: [audience(ADMIN_AUDIENCE, { roles: ADMIN_APP_ROLES }), siteRoles(), rankGuard()],\n});\n```\n\nThis is deliberately a top-level `export const`, not a per-request `c.env`-scoped factory (every other capability's convention): the plugin arrays must exist at module scope for the codemod to patch. Keep `audience(...)` first in each array, so the session row carries its audience before any other plugin reads it.\n\n**A feature module that adds a Better Auth plugin patches both instances.** The admin app hosts every self-service screen (teams, roles, keys, subscription), so the admin session needs the same feature plugins as the client session. `teams`, `api-keys` and `subscription-stripe` each declare one `plugin-array` patch with `\"exportName\": \"auth\"` and a second with `\"exportName\": \"adminAuth\"`:\n\n```json\n\"patches\": [\n  { \"file\": \"packages\u002Fauth\u002Fsrc\u002Fauth.ts\", \"kind\": \"plugin-array\", \"exportName\": \"auth\", \"arrayProp\": \"plugins\", \"call\": \"stripe\", \"import\": { \"name\": \"stripe\", \"from\": \"@better-auth\u002Fstripe\" } },\n  { \"file\": \"packages\u002Fauth\u002Fsrc\u002Fauth.ts\", \"kind\": \"plugin-array\", \"exportName\": \"adminAuth\", \"arrayProp\": \"plugins\", \"call\": \"stripe\", \"import\": { \"name\": \"stripe\", \"from\": \"@better-auth\u002Fstripe\" } }\n]\n```\n\nA module that ships a client plugin does the same in `packages\u002Fauth\u002Fsrc\u002Fclient.ts`, once for `authClientPlugins` and once for `adminAuthClientPlugins`.\n\nThe existing codemod (`packages\u002Fcli\u002Fsrc\u002Flib\u002Fpatch\u002Fts-module.ts`) inserts the call into each array and adds the import once. It is idempotent and formatting-preserving, and it finds `plugins` next to the `...sharedOptions(...)` spread. When the named export does not exist (a project whose `auth.ts` predates `adminAuth`), the patch is a refusal, not a silent no-op: `saasaloy add` and `saasaloy update` print a warning that names the missing export, and `update` keeps the module's lock entry so a later `update` retries it. See \"Upgrading a project made before the client\u002Fadmin split\" below.\n\nThe plugin's own vendor dep (`@better-auth\u002Fstripe`) merges into `packages\u002Fauth\u002Fpackage.json` (ADR 0020: vendor plugin deps land in the capability that owns the vendor package), never into the feature's own files.\n\n## Env checklist (`add auth` prints this)\n\n| Var | What | Prod | Local |\n|---|---|---|---|\n| `BETTER_AUTH_SECRET` | Signs sessions | **Required** — generate a real secret | Optional, but only when `BETTER_AUTH_URL` is a loopback origin |\n| `BETTER_AUTH_URL` | The API's own origin | `https:\u002F\u002Fapi.x.com` | `http:\u002F\u002Flocalhost:4000` (the api Worker's pinned dev port) — **set it**, it is what opens the keyless path |\n| `COOKIE_DOMAIN` | Explicit cookie domain | `.x.com` (cross-subdomain) | Leave unset (host-only) |\n\n### The secret fails closed\n\n`packages\u002Fauth\u002Fsrc\u002Fenv.ts` reads `BETTER_AUTH_SECRET` at module load and **throws** when it is\nunset. Better Auth's fallback key is published in its own source, so a Worker signing sessions with\nit accepts a cookie anyone can forge, and the only signal is one console warning printed on a cold\nstart. Throwing takes the Worker down on its first request instead.\n\nThe one way out is narrow and explicit: `BETTER_AUTH_URL` must name a loopback host (`localhost`,\n`127.0.0.1`, `[::1]`). The match is exact, so `localhost.attacker.example` and `127.0.0.1.nip.io`\ndo not open it. An **unset** `BETTER_AUTH_URL` does not open it either — a production Worker whose\nsecrets were never set looks exactly like that, which is the case this rule exists to catch.\n\nSo local dev is keyless but not configless: `BETTER_AUTH_URL=http:\u002F\u002Flocalhost:4000` is the\nlocal default in `packages\u002Fenv\u002F.env.example`, `pnpm env:setup` writes it into `apps\u002Fapi\u002F.env`,\nand `wrangler dev` then runs with no secret. Everywhere else,\nset the secret with `wrangler secret put BETTER_AUTH_SECRET`.\n\nMisconfigured prod fails **visibly** rather than silently: an origin missing from\n`CORS_ORIGINS` gets no `Access-Control-Allow-Origin` header, so the browser refuses to hand the\nresponse to the page, and Better Auth's `trustedOrigins` (fed from the same var) additionally\nanswers `403 INVALID_ORIGIN` on state-changing calls. Two independent layers — see below.\n\n### The cookie-domain rule\n\n1. `COOKIE_DOMAIN` set → used verbatim, `advanced.crossSubDomainCookies.enabled: true`.\n2. Unset, `BETTER_AUTH_URL` host is a loopback host (`localhost`\u002F`127.0.0.1`\u002F`[::1]`) → host-only\n   cookie (no `Domain` attr).\n3. Unset, host starts `api.` **and the remainder still contains a dot** → strips to the apex\n   (`api.x.com` → `.x.com`), cross-subdomain. A host like `api.dev`, whose apex would strip to a\n   bare TLD, falls through to rule 4 instead — browsers reject a TLD-only cookie domain outright.\n4. Unset, anything else → **host-only** (conservative — never guess a domain shape that isn't one\n   of the two recognized shapes; a wrong guess breaks login silently, host-only always works).\n\n## CORS lives in `api`, not here\n\n`auth`'s `trustedOrigins` reads the **same** `CORS_ORIGINS` env var as `modules\u002Fapi`'s `cors()`\nmiddleware — one origin list, two readers, no drift. If a credentialed cross-origin call is\nfailing, check `CORS_ORIGINS` on the api Worker first; auth carries zero CORS code of its own.\n\nThe two readers enforce different things, and it's worth not confusing them:\n\n| Layer | Who enforces | What an unlisted origin gets |\n|---|---|---|\n| `cors()` in api's spine | the **browser** | The Worker still runs the handler and returns a body; it just omits `Access-Control-Allow-Origin`, so the browser won't let the calling page read the response. A non-browser client (`curl`) sees the body regardless. |\n| `trustedOrigins` in Better Auth | the **server** | State-changing auth calls are rejected outright with `403 INVALID_ORIGIN` (and `403 MISSING_OR_NULL_ORIGIN` when the header is absent) — before any session work happens. |\n\nSo CORS is a read gate, not a request gate. When you need a request genuinely refused rather than\nmerely unreadable, that's `trustedOrigins` or an explicit origin check — don't rely on the CORS\nheaders to prove it.\n\n## Protect a route: the gates, never `better-auth` directly\n\n`@repo\u002Fauth\u002Fserver` exports two reads, one instance picker and five gates. The reads answer *who*; the gates answer *whether they may act*. Each one reads a fixed session or the session the request names:\n\n| Helper | Session it reads | Returns | Throws |\n|---|---|---|---|\n| `getSession(c)` | the one `x-auth-audience` names | the session, or `null` | 400 for an unknown header value |\n| `getAdminSession(c)` | always the admin session | the session, or `null` | never |\n| `authFor(c)` | the one `x-auth-audience` names | the instance, `auth` or `adminAuth` | 400 for an unknown header value |\n| `requireSession(c)` | the one `x-auth-audience` names | the session | `HTTPException(401, \"sign in first\")` |\n| `requireRole(c, role)` | always the admin session | the session | 401 as above, then `HTTPException(403, \"role required: \u003Crole>\")` |\n| `requireAdmin(c)` | always the admin session | the session | as `requireRole(c, ADMIN_ROLES)` |\n| `requireAdminApp(c)` | always the admin session | the session | as `requireRole(c, ADMIN_APP_ROLES)` |\n| `requireSuperadmin(c)` | always the admin session | the session | as `requireRole(c, \"superadmin\")` |\n\n**The `x-auth-audience` header picks the session for the generic helpers.** Its values are `client` and `admin`. No header means `client`. Any other value, the empty string included, gets 400 `x-auth-audience must be \"client\" or \"admin\"` rather than a quiet fallback to the client session. The admin app's `api` client sends `x-auth-audience: admin` on every request, so a teams or subscription screen there reads the admin who is signed in, not a client signed in on another tab. The header picks between the caller's own two cookies, so it grants nothing. Hono's `cors()` with no `allowHeaders` echoes the preflight's headers, so CORS needs no change for it.\n\n**The role gates ignore the header.** `requireRole`, `requireAdmin`, `requireAdminApp` and `requireSuperadmin` read `adminAuth` through `getAdminSession`, whatever the request says. Every site role lives in the admin group, so a client session never passes a role gate, even one that belongs to a `superadmin`. A request with only a client cookie gets 401 from them, not 403.\n\n**A route that calls Better Auth itself uses `authFor(c)`.** `authFor(c).api.getActiveMember({ headers })` reads the session the request names, so the same route serves the client app and the admin app. Calling `auth.api.*` directly reads only the client session, which is the bug `subscription`, `entitlements` and `multitenant` had before the split. Wrap the call in `withAuthScope` as above.\n\nAll of them take the whole Hono context, not `c.req.raw`. They need `c.env` to open this request's database client and `c.executionCtx` to close it, and they enter `withAuthScope` for you. See \"Either database driver\" below.\n\nReach for a gate first. A route that reads `getSession` and branches by hand is writing the same two error bodies again, and one typo in either is a hole.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fwidgets.ts\nimport { Hono } from \"hono\";\nimport { requireAdmin } from \"@repo\u002Fauth\u002Fserver\";\nimport type { AuthDbBindings } from \"@repo\u002Fauth\u002Fserver\";\n\nexport const widgets = new Hono\u003C{ Bindings: AuthDbBindings }>().get(\"\u002F\", async (c) => {\n  const session = await requireAdmin(c);\n  return c.json({ userId: session.user.id }, 200);\n});\n```\n\nThere is no `if` and no error body in that route, and that is the point. The gates throw a Hono `HTTPException`, `apps\u002Fapi`'s `onError` catches it, and `ERROR_CODES` renders it as the one envelope the api publishes: `{ \"error\": { \"code\": \"forbidden\", \"message\": \"role required: admin\" } }` on a 403, `\"unauthorized\"` on a 401. Write the check by hand and you own that shape yourself, in every route, forever.\n\nEach gate returns the session, so the caller reads `session.user.id` without a second round trip. `requireRole` takes any string, and it also takes an array to demand any one of several roles. `requireAdmin` uses that form against the exported `ADMIN_ROLES` and `requireAdminApp` against `ADMIN_APP_ROLES`, so `admin` and `superadmin` pass both today, and `requireSuperadmin` demands `superadmin` exactly. Every comparison is `===`, so `\"Admin\"` and `\"administrator\"` are not admins. Pick `requireAdmin` for admin-only work and `requireAdminApp` for a route every admin-app user may call; \"Two role lists\" below says why the two differ.\n\n`AuthDbBindings` is whichever binding shape the installed driver declares, so this route is one file under both drivers.\n\n**One role per user is the contract here, and it is narrower than better-auth's.** The plugin reads `user.role` as a comma-separated list (`has-permission.mjs` splits it on `,`), so a row holding `\"admin,support\"` is an admin to `adminAuth.api.listUsers` and gets a 403 from `requireAdmin`. `apps\u002Fadmin`'s browser guard compares with `===` too, so both halves of the gate agree with each other and both refuse the joined string. Nothing a scaffolded project writes produces one: the first-user hook writes `\"superadmin\"`, and `adminAuth.api.setRole({ body: { userId, role: \"admin\" }, headers })` writes one value. If you want stacked roles, change `hasRole` in `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` and `isAdmin` in `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` together, never one alone.\n\nKeep `getSession` for the case it was written for: a route whose answer *changes* for a signed-in caller but is still served to an anonymous one. A public page that shows a \"you already voted\" badge reads the session; it does not gate on it.\n\n```ts\nconst session = await getSession(c);\nreturn c.json({ voted: session ? await hasVoted(session.user.id) : false }, 200);\n```\n\nIf you do hand-write a deny, write the body out rather than importing a helper: `auth` depends on `api` and `database` only, so `@repo\u002Fvalidators` may not resolve. In a project that has it, `errorBody(\"unauthorized\", \"sign in first\")` from `@repo\u002Fvalidators\u002Fcommon` produces the identical shape.\n\nEvery helper wraps `getSession({ headers })` on the instance it reads, so both httpOnly cookies ride along on `c.req.raw` automatically and the instance reads only its own. No route imports `better-auth` (ADR 0020); everything goes through `@repo\u002Fauth\u002Fserver`.\n\nNote the route shape: one named `export const`, one chained expression, an explicit status on every `c.json`. That is what `hc\u003CAppType>` reads. Register it with a `chained-route` patch on the exported chain (`\"exportName\": \"default\"`), never by dropping the file and hoping (ADR 0028). `modules\u002Fadmin`'s `GET \u002Fadmin\u002Fusers` is the worked example of a gated route registered that way: it lists `adminGate` before its query validator, so a signed-out caller with a bad `?limit=` gets 401, not 400.\n\n**The gate is the api's, not the browser's.** `apps\u002Fadmin` also refuses an account outside `ADMIN_APP_ROLES`, in `beforeLoad`. That guard stops the SPA from asking; it cannot stop `curl`. A route that skips `requireAdmin` because the admin app already checks is open to anyone holding any session cookie.\n\n## Roles and the first user\n\nBetter Auth's `admin` plugin is on from the start, on both instances (`siteRoles()` in `auth.ts`). It gives `user` a `role` column, writes `\"user\"` into it for every new sign-up (except the first one, see below), refuses a banned account at sign-in, and treats the roles in `adminRoles` as privileged. Its `\u002Fadmin\u002F*` endpoints answer only on `adminAuth`.\n\n**The role strings live in `packages\u002Fconfig\u002Fsrc\u002Fsections\u002Fauth.ts`, which this module installs, and they have exactly one home.** `packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` reads `config.auth.adminRole`, `config.auth.superadminRole` and `config.auth.adminAppExtraRoles`, and `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` reads the same three — a browser bundle cannot import `@repo\u002Fauth\u002Fserver`, but `@repo\u002Fconfig` has no dependencies at all, so both sides read one copy. `siteRoleMap` in `authorize.ts` keys the `admin()` plugin's statements by the same strings, so a renamed role keeps its `\u002Fadmin\u002F*` permissions. Rename either role in `packages\u002Fconfig\u002Fsrc\u002Fproject.ts`; rows already written keep the old string, so an existing project needs the `update users set role = ...` to match.\n\nThere are two site roles, and they are not interchangeable. `admin` runs `apps\u002Fadmin` for the client accounts. `superadmin` does everything `admin` does, owns the admin group (see \"Rank\" below), and is the only role that may act inside an organization it does not belong to, through the `x-organization-id` header the `multitenant` module reads. That bypass needs the superadmin signed in on the admin session; a superadmin's client session gets the ordinary 403. Inside an organization an `admin` is an ordinary member: the site role grants nothing on a tenant route, which asks `requireTenant` and reads the caller's membership instead.\n\n`adminRoles` names both, so the plugin's own endpoints admit a `superadmin` as well as an `admin`. Leaving it at the default `[\"admin\"]` would let `requireAdmin` pass a caller the plugin then refused.\n\n### Two role lists\n\n`packages\u002Fauth\u002Fsrc\u002Fauthorize.ts` exports two lists, and they answer different questions:\n\n| List | Question | Gate | Ships with |\n|---|---|---|---|\n| `ADMIN_APP_ROLES` | Who is in the admin group: who may sign in on the admin session and open `apps\u002Fadmin`? | `requireAdminApp` | `admin`, `superadmin` |\n| `ADMIN_ROLES` | Who may do admin-only work? | `requireAdmin` | `admin`, `superadmin` |\n\nThey hold the same roles today and stay separate on purpose. `adminAuth`'s sign-in hook and the rank guard read `ADMIN_APP_ROLES`; the `admin()` plugin's `adminRoles` reads `ADMIN_ROLES`. `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` builds its own `ADMIN_APP_ROLES` from the same `config.auth` section, because a bundle cannot import from `@repo\u002Fauth\u002Fserver`, and its guard reads that list:\n\n```ts\nconst { data } = await auth.getSession();\nif (!ADMIN_APP_ROLES.some((role) => data?.user.role === role)) { \u002F* denied *\u002F }\n```\n\n`role` is typed on the admin client because `adminAuthClientPlugins` in `packages\u002Fauth\u002Fsrc\u002Fclient.ts` holds `adminClient()`, the client half of the server plugin. Keep the pair: drop the client half and `session.user.role` goes back to being an unchecked cast.\n\n### Adding a `support` role to the admin group\n\nA support agent who may sign in on the admin app but may not run admin-only routes is one role added to the group list only:\n\n1. In `packages\u002Fconfig\u002Fsrc\u002Fproject.ts`, set `auth: { adminAppExtraRoles: [\"support\"] }`. `ADMIN_APP_ROLES` on the api and in `apps\u002Fadmin` both pick it up. Leave `ADMIN_ROLES` alone.\n2. If support should reach an `admin()` plugin endpoint (for example `list-users`), give it a statement set in `siteRoles()` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`. Without one, the plugin refuses every `\u002Fadmin\u002F*` call from support. Do not add `support` to `adminRoles`, which would give it every plugin permission. A read-only set looks like this; check the statement names against the pinned better-auth's `better-auth\u002Fplugins\u002Fadmin\u002Faccess`:\n\n```ts\nimport { createAccessControl } from \"better-auth\u002Fplugins\u002Faccess\";\nimport { adminAc, defaultRoles, defaultStatements } from \"better-auth\u002Fplugins\u002Fadmin\u002Faccess\";\n\nconst ac = createAccessControl(defaultStatements);\nconst support = ac.newRole({ user: [\"list\", \"get\"], session: [\"list\"] });\n\nfunction siteRoles() {\n  return admin({\n    ac,\n    adminRoles: [...ADMIN_ROLES],\n    roles: { ...siteRoleMap({ admin: adminAc, user: defaultRoles.user }), support },\n  });\n}\n```\n\n3. Open each api route support may call with `requireAdminApp(c)`. Every `requireAdmin` route keeps refusing support with 403.\n4. Grant the role as a superadmin, through an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.setRole({ body: { userId, role: \"support\" }, headers: c.req.raw.headers })` inside `adminAuthWrite`. Only a superadmin may grant a role in `ADMIN_APP_ROLES`. The browser cannot call `\u002Fadmin\u002Fauth\u002Fadmin\u002Fset-role`: the forward answers 404.\n\nSupport is then in the admin group for the rank guard too: an `admin` may not change a support account, and only a superadmin may.\n\n### Rank: superadmin owns the admin group\n\n`adminAc` gives `admin` and `superadmin` the same `set-role`, so the `admin()` plugin alone would let an `admin` promote anyone to `superadmin`. `rankGuard()` (`packages\u002Fauth\u002Fsrc\u002Fplugins\u002Frank-guard.ts`) runs before every `\u002Fadmin\u002F*` endpoint on `adminAuth`, on an `adminAuth.api.*` call with the caller's headers as well as over HTTP, and asks `rankDenial()` in `authorize.ts`. Over HTTP the forward already answers 404 on those paths, so in practice the guard runs on the api's own calls. In order:\n\n- **Impersonation is refused for everyone**, `superadmin` included: `\u002Fadmin\u002Fimpersonate-user` gets 403 \"impersonation is not available between the client and admin sessions\". An impersonated session would be an admin-audience row for a client account, which the split forbids; without this refusal the admin sign-in hook would answer the call with a wrong-credentials message. Cross-audience impersonation is out of scope, and `auth` refuses every `\u002Fadmin\u002F*` path anyway.\n- **A caller who is not `superadmin` may read** (`list-users`, `get-user`, `list-user-sessions`, `has-permission`) and may change client accounts.\n- **Only `superadmin` may change an admin-group account or grant an admin-group role.** A write whose target holds an `ADMIN_APP_ROLES` role, or that would give one (`set-role`, `create-user`, `update-user` with `data.role`), gets 403 \"only a superadmin may change an admin-group account or role\". `revoke-user-session` checks the owner of the session token.\n- **The table fails closed.** `ADMIN_PATHS` in `authorize.ts` lists every `\u002Fadmin\u002F*` endpoint of better-auth 1.7.7's `admin()` plugin by kind. Any path not in it is superadmin-only (403 \"only a superadmin may call this admin endpoint\"), so an endpoint a Better Auth bump adds needs one line in the table before an `admin` may call it.\n- **Nobody may take the role from the last superadmin.** Removing, banning or demoting the only account that holds `superadmin` gets 403 \"the last superadmin cannot be removed, banned or demoted\", whoever calls.\n\nThe guard reads target roles through `@repo\u002Fdb\u002Frepositories\u002Fsite-roles`, not the adapter, because the scoped adapter cannot see a session of the other audience.\n\n### First user wins\n\nThe first account to sign up on an empty `users` table gets `role: \"superadmin\"`. A `databaseHooks.user.create.before` hook in `sharedOptions()` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts` reads the table before the row is written, so it can only match on the very first sign-up; every account after that keeps the plugin's default `\"user\"`. This is the only automatic promotion in the system, and it is what makes `saasaloy add admin` usable without SQL. It writes `superadmin` rather than `admin` because the first account has to be able to grant every other one, and only `superadmin` may change an admin-group role.\n\nBoth instances carry the hook, and in practice it fires on `auth`: `adminAuth` has no sign-up. So the first account signs up as a client, through `POST \u002Fauth\u002Fsign-up\u002Femail` or a client app's sign-up screen, and then signs in on the admin app with the same email and password. Both instances read one `accounts` table, so no second account is needed.\n\n**Client sign-up is open, so that first slot is a race you can lose.** Any account that reaches `\u002Fauth\u002Fsign-up` before you do becomes the superadmin, and on a deployed API with a public origin the window is real. Sign up yourself the moment the API answers its first request, then confirm with `select email, role from users`. Two sign-ups that land at the same instant both read an empty table and both become superadmin; that is accepted rather than locked, because a unique index on `role = 'superadmin'` would also block a deliberate second one later.\n\nIf somebody else got there first, or you are promoting an account on a project that already has users, flip the row by hand. Run this from the project root; `--filter @repo\u002Fdb` puts the working directory in `packages\u002Fdb`, which is what the relative paths are written against. The statement is the same under both drivers:\n\n```sql\nupdate users set role = 'superadmin' where email = 'you@example.com';\n```\n\n**How you run it is the driver's business**, so read the skill for the driver this project\ninstalled — `saasaloy-database-d1` or `saasaloy-database-postgres` — for the console it hands you.\nSwap `update` for `select email, role from users` to check it landed. The plural table name\nneeds no quotes: Postgres reserves `user`, not `users`.\n\nThe change takes effect on the next `getSession` call, because sessions are DB-backed and the role is read off the user row, and `cookieCache` is off (see the last boundary below). An account that is already signed in on the admin session needs no re-login. An account promoted from `user` has no admin session yet: it signs in on the admin app, because `adminAuth` refused it before the promotion. Demoting an account works the other way: its admin session stays in the table, but every role gate and the admin app's guard refuse it from the next request, and the admin app shows the refusal page.\n\nOnce one superadmin exists, promote the rest through the API instead of SQL: an api route under `\u002Fadmin\u002F` that calls `adminAuth.api.setRole({ body: { userId, role: \"admin\" }, headers: c.req.raw.headers })` inside `adminAuthWrite`, so the change leaves an audit row. `\u002Fadmin\u002Fauth\u002Fadmin\u002Fset-role` itself answers 404 over HTTP. The call authorizes against the caller's own role and the rank guard above, so only a superadmin may grant `admin` or `superadmin`. Grant `admin` for a backoffice user and keep `superadmin` for the accounts that own the admin group and may cross an organization boundary. The plugin also carries `listUsers`, `banUser` and friends on `adminAuth.api`. `impersonateUser` is there too, and the rank guard refuses it.\n\n**A project that installed auth before this shipped needs a migration.** The four new `users` fields and `sessions.impersonatedBy` are schema changes like any other: run `pnpm --filter @repo\u002Fdb db:generate`, read the emitted SQL, then apply it with the command from the installed driver's skill. Existing users come out of it with `role` null, which is neither site role, so the guard denies them until you promote one.\n\n**`accounts.issuer` is the one that needs a hand.** better-auth 1.7.2 made it required and put a unique index over (`issuer`, `accountId`); 1.7.3 took both back out, so the pinned snapshot no longer carries them and (`providerId`, `accountId`) is the row's identity again. A project that never applied the 1.7.2 migration needs nothing here. A project that already applied it gets the reverse from `db:generate`:\n\n```sql\nDROP INDEX `accounts_issuer_account_id_uidx`;--> statement-breakpoint\nALTER TABLE `accounts` DROP COLUMN `issuer`;\n```\n\nTake the index identifier from your own generated migration rather than from the snippet above. Drizzle derives it from the schema the 1.7.2 migration was generated against, so a project that kept better-auth's own naming sees `account_issuer_accountId_uidx` instead, and a `DROP INDEX` on a name that is not there fails and leaves `issuer` in place.\n\nRead it before you apply it, because a `DROP COLUMN` is not reversible and SQLite rewrites the table to do it. Take a copy of the database first. A Postgres project gets the same two statements with `DROP INDEX \"accounts_issuer_account_id_uidx\"` and `ALTER TABLE \"accounts\" DROP COLUMN \"issuer\"`. Nothing reads the column after the drop: better-auth 1.7.3's `getAuthTables()` never writes it and the adapter never selects it.\n\nLeaving the column in place is the option that breaks. The snapshot no longer declares it, so `db:generate` treats it as drift on every later run, and a fresh insert against a database that still has `issuer text NOT NULL` fails the constraint the moment 1.7.3 stops writing the value.\n\n## Seed users and the dev password\n\n`auth` ships seed slices for its four tables, so `pnpm db:seed` gives a development database four users, one for each way the admin app shows a user:\n\n| Email | Role | Notes |\n| --- | --- | --- |\n| `superadmin@example.test` | `superadmin` | sign in here to reach every admin page |\n| `admin@example.test` | `admin` | |\n| `member@example.test` | `user` | a client: signs in on `\u002Fauth`, refused on the admin app |\n| `banned@example.test` | `user` | banned, so sign-in is refused |\n\nEvery one has an email-and-password account with the password **`saasaloy-dev-password`**, and `db:seed` prints it after the counts. The hash in `packages\u002Fdb\u002Fsrc\u002Fseed\u002Fslices\u002Faccounts.ts` is precomputed in Better Auth's own format, so the seed never loads Better Auth. `sessions` and `verifications` ship empty slices: a seeded session would carry a token nobody holds.\n\nA seeded database already holds a superadmin, so the first-user promotion above does not fire there: the first person to sign up gets `user`. Sign in on the admin app as `superadmin@example.test` instead. Never seed a database other people can reach; the password is in this file.\n\n`auth` also ships the example route test, `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fauth.test.ts`. It signs the seeded superadmin in through `POST \u002Fauth\u002Fsign-in\u002Femail` and checks the session row, then a second test proves that row is gone. The rest pins the split: both cookies in one browser, a token copied into the other cookie, the admin sign-in refusal, `\u002Fauth\u002Fadmin\u002F*` refused, the rank rules and the impersonation refusal. A Better Auth bump that changes how a session is found fails these tests. Copy its shape for a route of your own; the database driver's skill, \"Route tests\", explains `testDatabase()`.\n\n## Revocation: delete the session row\n\nSessions are DB-backed on purpose (build-spec §2.5) — revoking one is a delete, no token\ndenylist needed:\n\n```sql\ndelete from sessions where id = '...';\n-- or, to kill every session for a user:\ndelete from sessions where user_id = '...';\n```\n\nThe next authed request with that cookie gets `401` from `getSession`.\n\n**One user has one sessions table, so a revocation by user ends both audiences.** A password change with `revokeOtherSessions: true`, the admin plugin's `revoke-user-sessions`, or the `delete ... where user_id` above signs that user out of the client session and the admin session alike. To end only one, delete by id, or add `and audience = 'client'` (or `'admin'`) to the statement.\n\n## `@auth\u002Fclient`: two factories, framework-agnostic\n\n`packages\u002Fauth\u002Fsrc\u002Fclient.ts` wraps `createAuthClient` (ships inside `better-auth`, no new npm dep). There are no React bindings and none are planned. It exports one factory per instance, and a browser bundle picks the one for its user group:\n\n| Factory | Instance | `basePath` | Plugin array | Used by |\n|---|---|---|---|---|\n| `createClient(baseURL)` | `auth` | `\u002Fauth` | `authClientPlugins` (empty by default) | every client-facing app |\n| `createAdminClient(baseURL)` | `adminAuth` | `\u002Fadmin\u002Fauth` | `adminAuthClientPlugins` (holds `adminClient()`) | `apps\u002Fadmin` only |\n\n```ts\nimport { createClient } from \"@repo\u002Fauth\u002Fclient\";\n\nconst client = createClient(\"https:\u002F\u002Fapi.x.com\"); \u002F\u002F same origin as BETTER_AUTH_URL\nawait client.signUp.email({ email, password, name });\nawait client.signIn.email({ email, password });\n```\n\n`apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` builds its client with `createAdminClient(apiBaseUrl)` and exports it as `auth`, so a module screen that imports `auth` from `@admin\u002Flib\u002Fauth` reaches the admin session with no change. The admin client has no `signUp`: the server refuses it.\n\n`fetchOptions: { credentials: \"include\" }` is baked into both. The calling origin must be in `CORS_ORIGINS` (api's spine) for the cookie to be set and sent cross-origin.\n\n`adminClient()` rides on the admin client only, mirroring the server's `admin()`. That is what types `session.user.role`. It also puts `auth.admin.*` on the admin app's client, but the api's forward answers 404 to every `\u002Fadmin\u002Fauth\u002Fadmin\u002F*` path, so no browser code calls those methods. A staff screen calls an api route under `\u002Fadmin\u002F` instead, which writes the audit row. A feature module that ships a client plugin patches both arrays. Keep each array literal and never delete one, even when it is empty.\n\n## Wire-up: the sign-in and sign-up blocks\n\n`auth` ships two blocks into `@repo\u002Fui`, with the frame they share. Each entry carries `when: { installed: [\"shell\"] }`, because the blocks render the `shell` primitives. A project with no signed-in app gets none of them. `saasaloy add admin` or `saasaloy add app` brings `shell`, and the same run writes the blocks (the backfill).\n\n| File | Exports |\n|---|---|\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fsign-in.tsx` | `SignInCard`, `SignInValues` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fsign-up.tsx` | `SignUpCard`, `SignUpValues` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002Fauth-card.tsx` | `AuthCard`, `AuthAlert`, `useAuthSubmit`, the frame both cards use |\n\nThe blocks do no IO, per the `@repo\u002Fui` rule. They import no auth client, no router, no store and no env. The app renders a block on its own route and owns the call:\n\n- **`onSubmit(values)` returns `Promise\u003Cstring | undefined>`.** Return a message and the card shows it in a `role=\"alert\"` line above the button. Return `undefined` (or nothing) on success, after you navigate. Do not write `string | void`: the project lint rejects `void` in a union, and the type does not match.\n- **Catch your own network failure.** A throw resets the button and reaches the console, but the card shows nothing. Turn it into a returned message, as the example below does.\n- **`SignInCard` takes `signUpHref?`, `title?` and `description?`.** With no `signUpHref`, the card has no footer. `admin` passes its own title and description and no `signUpHref`.\n- **`SignUpCard` takes `signInHref`, `title?` and `description?`.** Its password field asks for 12 characters, the server's `minPasswordLength` (see \"Password rules\"). Change both together.\n- **The block renders the card, not the page.** Centre it on your app's canvas: `app` uses `bg-sidebar`, `admin` uses `bg-background`.\n\nA sign-in route in a TanStack Router app. `@app\u002Flib\u002Fauth` stands for the app's own client file: `createClient(apiBaseUrl)` from `@repo\u002Fauth\u002Fclient`, with the url from the app's env gate, as `apps\u002Fadmin\u002Fsrc\u002Flib\u002Fauth.ts` does with `createAdminClient`.\n\n```tsx\nimport { createFileRoute, useRouter } from \"@tanstack\u002Freact-router\";\nimport { SignInCard } from \"@repo\u002Fui\u002Fblocks\u002Fauth\u002Fsign-in\";\nimport type { SignInValues } from \"@repo\u002Fui\u002Fblocks\u002Fauth\u002Fsign-in\";\nimport { auth } from \"@app\u002Flib\u002Fauth\";\n\nexport const Route = createFileRoute(\"\u002Fsign-in\")({ component: SignInScreen });\n\nfunction SignInScreen() {\n  const router = useRouter();\n\n  async function handleSignIn(values: SignInValues): Promise\u003Cstring | undefined> {\n    try {\n      const { error } = await auth.signIn.email(values);\n      if (error) {\n        return error.message ?? \"Sign-in failed. Check the email and password.\";\n      }\n    } catch {\n      return \"Could not reach the api. Check that it is running.\";\n    }\n    await router.navigate({ to: \"\u002F\" });\n  }\n\n  return (\n    \u003Cmain className=\"bg-sidebar flex min-h-dvh items-center justify-center p-4\">\n      \u003CSignInCard onSubmit={handleSignIn} signUpHref=\"\u002Fsign-up\" \u002F>\n    \u003C\u002Fmain>\n  );\n}\n```\n\n`SignUpCard` follows the same shape, with `auth.signUp.email({ name, email, password })` and `signInHref=\"\u002Fsign-in\"`.\n\n**Styles.** The blocks are under `packages\u002Fui\u002Fsrc\u002Fblocks\u002F`, which `globals.css` scans. An app stylesheet that does not import `globals.css`, such as one built on `brand.css`, adds `@source \"..\u002Fblocks\u002Fauth\u002F**\u002F*.tsx\";`, or the card renders unstyled with no error.\n\n**Lint.** The base `oxlint.config.mjs` twin-primitive rule covers `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fauth\u002F**`, so a base primitive in a block is a lint error. A project made before this rule copies the glob from the base template.\n\n**Removal.** `saasaloy remove shell` refuses while `admin` or `app` is installed. When it runs, it deletes the three block files with it, so delete each route that imports them first.\n\n## Signed-in state on the static site\n\nThe base `apps\u002Fweb` is a prerendered Astro site, and no module puts a header with a session on it. When a project adds one (a \"Log in\" link that turns into an avatar), two faults are waiting. The session lives in an httpOnly cookie on the api origin, so the page learns who is signed in only when a session check answers:\n\n- The header shows \"Log in\" first and swaps to the avatar after the check, a visible jump on every load (2.5 s in one project).\n- A sign-in form that signs in without a page load leaves a header that checked on mount still showing \"Log in\".\n\nUse two pieces, both in `apps\u002Fweb\u002Fsrc\u002Flib\u002F`:\n\n- **A `session:change` event.** One seam, `session.ts`, owns `getSession()` on the client factory. Export `announceSessionChange()`, which dispatches `new Event(\"session:change\")` on `window`, and `onSessionChange(listener)`, which returns the unsubscribe. Call `announceSessionChange()` after each sign-in and sign-out. Every island that shows the session (the header, an account panel) listens and checks again.\n- **A first-paint hint.** `session-hint.ts` stores one flag in `localStorage` each time a check answers: `\"1\"` while signed in, removed when not. An inline script in `\u003Chead>` of `Layout.astro` (`\u003Cscript is:inline set:html={SESSION_HINT_SCRIPT} \u002F>`, a string, because a module script runs after the paint) sets `data-session=\"in\"` on `\u003Chtml>` from that flag. The header renders both states, and CSS under `[data-session=\"in\"]` shows one, so server and client markup match and hydration does not warn.\n\nThe flag holds no name and no id, so a shared device shows nothing about the user. The cookie stays the truth: a stale flag costs one swap, and the next check clears it. Wrap every `localStorage` access in `try`, because storage can be off.\n\n## Password rules\n\nBoth instances set `minPasswordLength: 12` (`MIN_PASSWORD_LENGTH` in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`). Better Auth applies it on sign-up, on a password reset and on a password change, and answers `400` with `code: \"PASSWORD_TOO_SHORT\"`. It never applies it on sign-in, so an account made before the rule, with a shorter password, still signs in. Keep the number and the sign-up form's hint in step. A project made before this rule gets it through `saasaloy update auth`.\n\n## Password reset mail\n\n`auth` does not depend on `email`. When `email` is in the project, `auth` ships the reset mail as well. Each of these entries carries `when: { installed: [\"email\"] }` (ADR 0054):\n\n| Entry | What it does |\n|---|---|\n| `packages\u002Fauth\u002Fsrc\u002Fplugins\u002Freset-password-mail.ts` | A Better Auth plugin whose `init()` sets `emailAndPassword.sendResetPassword`. It sends through `createEmail(env)`, with `env` from `cloudflare:workers`. |\n| `resetPasswordMail()` in `auth`'s `plugins` array | A `plugin-array` patch. Only the client instance sends the mail: `adminAuth` reads the same `accounts` table, so a new password counts there too. |\n| `@repo\u002Femail` in `packages\u002Fauth\u002Fpackage.json` | A `package-json-dependency` patch. |\n| `packages\u002Femail\u002Fsrc\u002Ftemplates\u002Freset-password.ts` | The template, in the `email` module's convention. Edit it like `welcome.ts`. |\n| `apps\u002Fapi\u002Fsrc\u002Froutes\u002Freset-password.test.ts` | The route test, only when testing is on too. It replaces `createEmail` with a sender that keeps each message. |\n\n`saasaloy add email` in a project that already has `auth` writes all of them in the same run (the backfill). `saasaloy add auth` in a project with `email` writes them at once.\n\n**Use it.** The client calls Better Auth's endpoint, and the mail goes to the address if it has an account:\n\n```ts\nawait authClient.requestPasswordReset({\n  email,\n  redirectTo: `${location.origin}\u002Freset-password`,\n});\n```\n\n`POST \u002Fauth\u002Frequest-password-reset` answers `200` with the same message for a known and an unknown address, so it does not tell a caller which addresses have accounts. The mail carries Better Auth's link, `\u003CBETTER_AUTH_URL>\u002Fauth\u002Freset-password\u002F\u003Ctoken>?callbackURL=\u003CredirectTo>`. That endpoint checks the token and redirects to `redirectTo` with `?token=`. The `redirectTo` origin has to be in `trustedOrigins` (`CORS_ORIGINS`, or the localhost dev list), or the request answers `403`. The token lives for 60 minutes. The page that reads the token and calls `authClient.resetPassword({ newPassword, token })` is the app's: no module ships it yet (#230 plans it).\n\n**Check it locally.** With `email-console` and `EMAIL_PROVIDER=console`, the mail prints to the api's stdout:\n\n```sh\ncurl -X POST http:\u002F\u002Flocalhost:4000\u002Fauth\u002Frequest-password-reset \\\n  -H 'content-type: application\u002Fjson' -H 'origin: http:\u002F\u002Flocalhost:3000' \\\n  -d '{\"email\":\"member@example.test\",\"redirectTo\":\"http:\u002F\u002Flocalhost:3000\u002Freset-password\"}'\n```\n\n**Failure modes.**\n\n- The request answers `400` with `code: \"RESET_PASSWORD_DISABLED\"`: `email` is not installed, or the `resetPasswordMail()` line is missing from `auth`'s `plugins`. Run `saasaloy add email`, or put the line back.\n- The request answers `200` but no mail arrives: the sender threw. Better Auth logs the error and answers as usual, on purpose. Read the api log. The usual causes are an unset `EMAIL_PROVIDER` or `EMAIL_FROM`, and a `BETTER_AUTH_URL` that is not `https` outside localhost, which `safeUrl` refuses.\n- After `saasaloy remove email`, `pnpm install` fails on `@repo\u002Femail`: `remove` deletes the reset files and reverts the `plugins` line, but it does not reverse a `package-json-dependency` patch. Delete `\"@repo\u002Femail\"` from `packages\u002Fauth\u002Fpackage.json` by hand.\n\n## Enabling social OAuth \u002F email verification (not wired)\n\n- **Social providers** (Google, GitHub, …): add a `socialProviders` block to\n  `packages\u002Fauth\u002Fsrc\u002Fauth.ts` yourself — not pre-wired, since it needs per-provider client\n  IDs\u002Fsecrets this module can't invent safely.\n- **Email verification**: `requireEmailVerification` stays off, with or without `email`. Turning it\n  on needs a `sendVerificationEmail` sender, written the same way as `reset-password-mail.ts`, and a\n  verification screen in each app. Turning it on with no provider configured makes sign-up appear\n  to hang or silently fail. The password reset mail is wired: see \"Password reset mail\".\n\n## Schema: hand-authored, never generated at `add` time\n\n`packages\u002Fdb\u002Fsrc\u002Fschema\u002Fauth.ts` (one of `auth.sqlite.ts` and `auth.pg.ts`, chosen by the\ninstalled driver) is a **checked-in Drizzle snapshot** of Better Auth's core tables (`users`, `sessions`, `accounts`, `verifications`) plus the\nfields the `admin` plugin adds (`users.role`, `banned`, `ban_reason`, `ban_expires`, and\n`sessions.impersonated_by`), plus `sessions.audience` from this module's own `audience()` plugin (text, not null, default `'client'`), pinned to the exact `better-auth` version in\n`packages\u002Fauth\u002Fpackage.json` — not run through a generator at add-time (no exec, deterministic, `--diff`-able). If you bump `better-auth`, **re-verify this file against the new version's schema** (`@better-auth\u002Fcore`'s `getAuthTables()`, and the admin plugin's own `schema` export) before shipping — fix the snapshot, not the adapter config, on a mismatch. The adapter matches on the Drizzle **property** name (`banReason`), not the SQL column name (`ban_reason`), and does no case conversion. It's picked up by database's existing barrel + migration scripts same as any other table:\n\n```sh\npnpm --filter @repo\u002Fdb db:generate       # emits SQL for the new tables\n```\n\nThe rule has a guard in this repo. The snapshot's header names the version it was verified against, and `modules\u002Fauth\u002Ffiles\u002Fsrc\u002Fschema-version.test.ts` fails `pnpm test` when that string and `better-auth` in `modules\u002Fauth\u002Ffiles\u002Fpackage.json` disagree. It cannot check a column; it makes a bump that skipped the re-verification loud instead of silent. Do the comparison, fix what moved, then edit the header. Editing the header alone to get green is the one way to defeat it.\n\nThe 1.7.2 → 1.7.3 pass is the worked example of what \"re-verify\" means here. It found one change, and it was a removal: `accounts.issuer` and its unique index are gone from `getAuthTables()`, so they came out of both snapshots and the headers say so. The admin plugin's own `schema` export did not move.\n\n`db:generate` belongs to the `database` core and is the same command under either driver. **The\napply step is the driver's**, and the command differs, so read the skill for the driver this\nproject installed: `saasaloy-database-d1` or `saasaloy-database-postgres`.\n\nBoth variants have to stay in step. Edit one table and edit its twin — `add auth` installs only the\none matching the project's driver, so a mismatch shows up on the other driver's first install, long\nafter the edit.\n\n## Upgrading from singular table names\n\nA project that installed auth before the tables became plural has `user`, `session`, `account` and `verification` in its database. Move them to the new names like this:\n\n1. Run `saasaloy update auth`. It takes the new schema file and the `auth.ts` that passes `usePlural: true`. The schema rename and `usePlural` must land together, because one without the other breaks sign-in. Update auth before `teams`, `api-keys` and `subscription`.\n2. Run `pnpm db:generate`.\n3. drizzle-kit asks, for each new table, whether it is created or renamed from an existing table. Pick the rename from the old name: `user` → `users`, `session` → `sessions`, `account` → `accounts`, `verification` → `verifications`.\n4. Read the generated SQL before you apply it. It must rename the tables and the indexes (`ALTER TABLE ... RENAME TO ...`, and `session_user_id_idx` → `sessions_user_id_idx`, `account_user_id_idx` → `accounts_user_id_idx`, `verification_identifier_idx` → `verifications_identifier_idx`). It must contain no `DROP TABLE` or `CREATE TABLE` for a table that holds data.\n5. If it drops a table, delete that migration file and run `pnpm db:generate` again.\n6. Apply the migration with the command from the installed driver's skill, then sign in once to confirm the adapter finds every table.\n\n## Upgrading a project made before the client\u002Fadmin split\n\nA project made before the split has one instance and one `better-auth.session_token` cookie. Move it to two instances in this order:\n\n1. Run `saasaloy update auth admin`.\n2. Resolve the merge plan for `packages\u002Fauth\u002Fsrc\u002Fauth.ts`, `packages\u002Fauth\u002Fsrc\u002Fclient.ts`, `packages\u002Fauth\u002Fsrc\u002Fserver.ts` and `@db\u002Fschema\u002Fauth.ts`. Take the new `adminAuth` export, `adminAuthClientPlugins`, `createAdminClient` and the `audience` column. Carry over any plugin or option you added by hand to both instances.\n3. Run `pnpm db:generate`. It writes one migration that adds `sessions.audience` with default `'client'`. Read it, then apply it with `pnpm db:migrate:local`, or the production migrate command from the installed driver's skill.\n4. Run `saasaloy update` for each installed module that patches auth: `teams`, `api-keys` and `subscription-stripe`. Each one now adds its plugin to `adminAuth` and to `adminAuthClientPlugins` as well.\n\nRun step 4 after step 2. Before the merge, `auth.ts` has no `adminAuth` export, and the patch prints a warning that names the missing export. That warning means \"merge `auth.ts` first\", and the module's lock entry stays where it was, so running `saasaloy update \u003Cmodule>` again after the merge applies the patch.\n\nEvery existing session ends, because the cookie names change from `better-auth.session_token` to `client.session_token` and `admin.session_token`. Old session rows read as client rows through the column default, but no browser holds a cookie that names them. Tell your users they must sign in again. A route of your own that calls `auth.api.*` reads only the client session after the update; switch it to `authFor(c).api.*` if the admin app calls it. A middleware of your own on `\u002Fadmin\u002F*` must now skip `\u002Fadmin\u002Fauth\u002F*`.\n\n## Boundaries to honor\n\n- **Only `packages\u002Fauth` imports `better-auth`.** Every other workspace goes through\n  `@repo\u002Fauth\u002Fserver` \u002F `@repo\u002Fauth\u002Fclient` (ADR 0020).\n- **`auth` and `adminAuth` stay module-scope singletons** in `packages\u002Fauth\u002Fsrc\u002Fauth.ts`. Don't refactor them into a per-request factory; that would break the plugin-array patch points every future capability relies on. The database behind it stays request-scoped for the opposite reason (ADR 0029);\n  don't collapse the two by binding a client at module scope.\n- **Every `api.*` and `handler` call on either instance runs inside `withAuthScope`.** Don't add a fallback\n  that opens a client when the scope is empty: that path has no `executionCtx` to close the socket\n  on, which is the leak the wrapper exists to prevent.\n- **`plugins` stays a literal array** in each `betterAuth({ ... })` call. Never omit it, never hoist it to a named const, and never drop `audience(...)` or `siteRoles()` from it. A feature plugin goes into both arrays.\n- **Keep the audience scoping.** Don't unwrap `scopeSessionsTo` or drop the `audience` column: without them a client token copied into the admin cookie is an admin session.\n- **`\u002Fadmin\u002Fauth\u002F*` belongs to `adminAuth`.** Don't mount a route under it, and make any `\u002Fadmin\u002F*` middleware skip it.\n- **CORS is api's job.** Don't add CORS handling here; reuse `CORS_ORIGINS`.\n- **Sessions are DB-backed; `cookieCache` stays off** — revocability over the marginal latency of\n  one database read per request.\n- **The dialect lives in the two schema variants and in `db-provider.ts`, nowhere else.** A\n  `sqlite-core` or `pg-core` import outside `files\u002Fdb\u002Fschema\u002Fauth.*.ts`, or a `provider:` string\n  written inline in `auth.ts`, pins this module to one driver again.\n\n## Next\n\nRun `saasaloy-app` to give a signed-in user a home, with the sign-in and sign-up blocks on its routes.\n",{"name":5,"description":7},"main","5ecf3d110b216ef678e06a1630f6b63a8e730bb5","modules\u002Fauth\u002Fskills\u002Fsaasaloy-auth",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-auth",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-auth",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-auth","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fauth\u002Fskills\u002Fsaasaloy-auth\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",[],[]]