[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GKQAF1B0NCAZ8VSFMBTRE":3,"skill-same:01M79GKQAF1B0NCAZ8VSFMBTRE":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},"01M79GKQAF1B0NCAZ8VSFMBTRE","saasaloy-multitenant",null,"Runbook for the multitenant feature, which resolves which organization a request acts for, guards every scoped query, and gates a route with requirePermission. Use when writing or reviewing a route that reads organization-owned data, adding a permission-checked route, adding a table that belongs to an organization, registering a new credential type, working on the \u002Froles screen, or working on the superadmin x-organization-id bypass, the 401\u002F403 rules, or removal behavior.","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\u002Fmultitenant\u002Fskills\u002Fsaasaloy-multitenant\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-multitenant\ndescription: Runbook for the multitenant feature, which resolves which organization a request acts for, guards every scoped query, and gates a route with requirePermission. Use when writing or reviewing a route that reads organization-owned data, adding a permission-checked route, adding a table that belongs to an organization, registering a new credential type, working on the \u002Froles screen, or working on the superadmin x-organization-id bypass, the 401\u002F403 rules, or removal behavior.\n---\n\n# multitenant\n\nThe `multitenant` feature answers one question on every request: **which organization is this for, and who is asking?** `teams` shipped the organizations. This ships the boundary around them.\n\nIt adds `requireTenant(c)` to `packages\u002Fauth`, the branded `TenantId` and the `forTenant` wrapper to `packages\u002Fdb`, `GET \u002Ftenant` to the api, the throwing permission gate `requirePermission(c, permissions)`, the `\u002Froles` screen in `apps\u002Fadmin`, and a worked `projects` example you delete once your own tables exist.\n\n`teams` ships the vocabulary and the pure `can()` rule this module throws on. Read `saasaloy-teams` for `access.ts`, custom roles and the base-role lock.\n\n## The route recipe\n\nTwo lines, and neither is optional.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts\nconst tenant = await requireTenant(c);\nconst rows = await withDb(c, (db) => listProjects(db, tenant.organizationId));\n```\n\n```ts\n\u002F\u002F packages\u002Fdb\u002Fsrc\u002Frepositories\u002Fprojects.ts\nexport function listProjects(db: Db, tenantId: TenantId) {\n  return forTenant(db, tenantId).select(projects);\n}\n```\n\nOn the cookie path, `requireTenant` reads the session the request's `x-auth-audience` header names, through `requireSession` and `authFor(c).api.getActiveMember`: the client session by default, the admin session when the admin app calls. A scoped screen in `apps\u002Fadmin` therefore acts as the admin signed in there, with that admin's active organization, and the same route serves a client app unchanged.\n\n`requireTenant` is the only thing in the project that mints a `TenantId`, and `forTenant` accepts nothing else. A handler that skips the first line cannot call the second, and that is a compile error rather than a review note.\n\nThe queries live in a repository, not in the route. `drizzle-orm` belongs to `@repo\u002Fdb` and no other workspace imports it (ADR 0020), so a route cannot write `eq(...)` even when it wants to.\n\n**The one gap:** a handler that ignores `forTenant` and writes `db.select().from(projects)` still compiles. Convention and review cover that in v1; a lint rule that refuses raw `db` on a tenant table is a filed follow-up. Read a scoped route for the `forTenant(` call the same way you read it for the `requireTenant(` call.\n\n## The permission gate\n\nOn a write, the first line changes. `requirePermission` replaces `requireTenant` rather than joining it.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts\nexport const projects = new Hono\u003C{ Bindings: AuthDbBindings }>()\n  .get(\"\u002F\", async (c) => {\n    const tenant = await requireTenant(c); \u002F\u002F membership is the gate on a read\n    \u002F\u002F ...\n  })\n  .delete(\"\u002F:id\", async (c) => {\n    const tenant = await requirePermission(c, { project: [\"delete\"] });\n    await withDb(c, (db) => deleteProject(db, tenant.organizationId, c.req.param(\"id\")));\n    return c.json({ id }, 200);\n  });\n```\n\n`requirePermission` **is** `requireTenant` plus `can`, and it returns the same `Tenant`. Never call both in one handler: the second call re-resolves the session and re-runs the `organization_roles` query for an answer it already has.\n\nReads usually stay on `requireTenant`. `member` holds `project: [\"read\"]` in `access.ts`, so gating a read is the same check written twice. Gate a read when some members must not see the rows at all, not by reflex.\n\n`permissions` is typed by `Permissions` from `access.ts`. An undeclared resource or a misspelled action is a compile error, not a check that silently passes.\n\n## The `\u002Froles` screen\n\n`apps\u002Fadmin` imports `allows` from `@repo\u002Fauth\u002Fpermission-rules`, fetches `GET \u002Ftenant` once per page through `tenantQuery`, and hides a control the caller may not use. Better Auth's `checkRolePermission` is deliberately not used: it knows the static roles only, so it answers wrongly for every custom role.\n\n**The hide is cosmetic. The 403 is the gate.** A screen that hides a button and skips `requirePermission` has no authorization at all. Write the route check first, then hide the control.\n\nThe screen ships here rather than in `teams` because it calls `GET \u002Ftenant`, and this module mounts that route. A `teams`-only project would render the screen onto a 404.\n\nA `nav-entry` patch adds the screen to the admin sidebar: `{ to: \"\u002Froles\", label: \"Roles\" }` with `ShieldCheckIcon`, in the `Manage` group of `NAV_AREAS` in `apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav.ts`. `remove multitenant` reverses it.\n\n## Three different questions\n\nDo not reach for the wrong one.\n\n| Helper | Question |\n| --- | --- |\n| `requireAdmin(c)` | Does the admin session hold an admin role? (`requireAdminApp(c)` asks who may open `apps\u002Fadmin`) |\n| `requireSuperadmin(c)` | Is this the one site role that crosses organizations? |\n| `requireTenant(c)` | Which organization is this request for, and as whom? |\n| `requirePermission(c, p)` | That, and may they do this here? |\n\nA site `admin` is an ordinary member on every tenant route. The site role grants nothing here, so an `admin` who belongs to no organization gets the same 403 as anyone else.\n\n## The tenant column convention\n\nEvery table a request may read on behalf of one organization declares the same column and the same index:\n\n```ts\nexport const projects = sqliteTable(\n  \"projects\",\n  { id: text(\"id\").primaryKey(), organizationId: tenantColumn(), \u002F* ... *\u002F },\n  (table) => [tenantIndex(table, \"projects\")]\n);\n```\n\n`tenantColumn()` and `tenantIndex()` come from `@repo\u002Fdb\u002Ftenant-column`, which ships in two dialects. They expand to `text(\"organization_id\").notNull().references(() => organization.id)` plus one index named `\u003Ctable>_organization_id_idx`.\n\nThree parts matter, each for its own reason:\n\n- **The property name is `organizationId`.** `forTenant` reads `table.organizationId`, so a table naming it `orgId` does not fit `TenantTable` even when the column underneath is right.\n- **`notNull` is not negotiable.** A nullable tenant column makes a row belonging to no organization, which every scoped query silently omits and no guard ever refuses.\n- **The index carries every scoped read.** Without it each one is a full scan.\n\nThe `teams` and `api-keys-organization` tables already meet the convention. `members`, `invitations` and `organization_roles` were hand-written that way; `api_keys` gets there through the API-key plugin's `referenceId` field rename. `organizations` itself is the parent and carries no tenant column.\n\n## What `TenantId` refuses\n\n`TenantId` is `string` at runtime and a distinct type at compile time. `packages\u002Fdb\u002Fsrc\u002Ftenant.typecheck.ts` is the proof, and `pnpm typecheck` in `packages\u002Fdb` runs it. Every `@ts-expect-error` in that file is an assertion, so `tsc` fails if one stops being an error. Do not silence one; change it in the same commit as the guard, and say why.\n\nIt refuses, in order of how likely each is to be the bug:\n\n- a raw string, so a route that reads an organization id out of a request body or a header cannot scope a query with it,\n- a table with no `organizationId` column,\n- an insert that names `organizationId` itself, so a request body spread into `values` cannot write into another organization,\n- an update that sets `organizationId`, which is how a row would be moved between organizations.\n\n## The header contract\n\n`x-organization-id` names an organization to act inside. It is honoured **only** on the cookie path and **only** for a `superadmin` on the admin session. `mayCrossOrganizations` in `tenant-rules.ts` checks both the role and `session.audience === \"admin\"`. The admin app's `api` client sends `x-auth-audience: admin`, which is what makes `requireTenant` read the admin session. A superadmin's client session, the one they use the product with, gets the 403 like any other caller.\n\n- A `superadmin` on the admin session sending it gets that organization, with `principal: { kind: \"superadmin\", userId }`. The id is looked up first, so a typo is 404 `unknown organization` rather than a tenant that does not exist.\n- Any other signed-in caller sending it gets 403 `forbidden`, a `superadmin` on the client session included. Refused, not ignored: a silently ignored header reads as \"it worked\" to whoever sent it.\n- Beside a bearer credential it is 403 whatever it says. A key is bound to one organization.\n\nThere is no organization picker in `apps\u002Fadmin` yet. Reach for the header with `curl` until the follow-up issue lands. Sign in on `\u002Fadmin\u002Fauth\u002Fsign-in\u002Femail` and send `x-auth-audience: admin` beside `x-organization-id`, or the request reads the client session and gets 403.\n\n## Failure codes\n\nEvery one of these renders through api's `ERROR_CODES` envelope, so a caller parses one body.\n\n| Condition | Status | Message |\n| --- | --- | --- |\n| Signed out | 401 | `sign in first` |\n| No active organization, or membership revoked | 403 | `no active organization` |\n| `x-organization-id` from a caller who may not send it | 403 | `forbidden` |\n| `x-organization-id` from a `superadmin` on the admin session naming no organization | 404 | `unknown organization` |\n| A claimed bearer credential that fails (`api-keys-organization`) | 401 | `invalid api key` |\n| A `can()` refusal | 403 | `permission required: \u003Cresource>:\u003Caction>` |\n| A write naming a base role (`teams`) | 403 | `base role is locked: \u003Cname>` |\n\nThe permission message names the first missing pair, never the whole demand: a refusal listing every permission a route wants would describe the route to an attacker.\n\n`NO_ACTIVE_ORGANIZATION` is exported and `apps\u002Fadmin` matches on the exact string, to tell \"you have no organization yet\" apart from \"you may not do this\". Change it in `tenant-rules.ts` and change the SPA in the same commit.\n\n## The credential resolver table\n\n`packages\u002Fauth\u002Fsrc\u002Ftenant.ts` exports an empty table:\n\n```ts\nexport const tenantResolvers = defineTenantResolvers({ resolvers: [] });\n```\n\nA credential module registers into it with one `plugin-array` patch, the same shape `authClientPlugins` uses. Keep the array literal at module scope, and never remove it even while it is empty.\n\nA resolver has a `name`, a synchronous `claims(headers)` and an async `resolve(c)`. `claims` answers \"is this my credential\", not \"is it valid\". Returning `true` takes the request off the session path for good: `resolve` then returns a `Tenant` or throws. That is what stops a rejected API key from quietly falling back to whatever session cookie rode along with it. Array order is precedence; the first claimer wins.\n\n## Roles are loaded once\n\nOn the member path, `requireTenant` reads that organization's `organization_roles` rows in one query and resolves the caller's statements onto the principal. `can()` then reads the answer instead of asking again, so a route with three permission checks still pays for one round trip.\n\nThe merge has four cases, all in `resolveStatements` in `tenant-rules.ts` and all covered by `tenant-rules.test.ts`: a base role with a stored row of the same name resolves to the static role widened by the row; a base role alone resolves to itself; a custom role resolves to its stored row; a name matching neither resolves to nothing. The last one is the decision that matters — a deleted role fails closed for its holders rather than falling back to `member`.\n\n## Boundaries to honor\n\n- **Do not add a second permission path.** `can()` reads `principal.statements` and nothing else. A route that calls `auth.api.hasPermission` itself pays a query per check and answers from a different engine.\n- **Do not mint a `TenantId` outside `requireTenant`.** `asTenantId` exists for that one caller. Calling it on a request-supplied value hands out another organization's rows.\n- **Do not widen `Tenant.organizationId` to `string`.** Every guarantee above turns into a naming convention the moment you do.\n- **Do not resolve the tenant in middleware.** The `chained-route` patch kind registers routes, not `.use()` links (ADR 0028), so a middleware convention would have no way to install itself.\n- **The `projects` table and its routes are an example.** Delete them once your own scoped tables exist. `remove multitenant` names `projects` in its warning, and every route written against `requireTenant`, `forTenant` or `requirePermission` stops compiling when this module goes. A third warning covers custom roles: `teams` keeps them live after this removal, and the `\u002Froles` screen that edits them goes with this module.\n\n## Upgrading from singular table names\n\nA project that installed `multitenant` before the tables became plural has a `project` table in its database. `projects` is this module's example table, not a Better Auth table, so the adapter never looks it up. A project that already deleted the example has nothing to do here. Otherwise, move it to the new name like this:\n\n1. Update `auth` first, because its schema rename and `usePlural: true` land together. Then run `saasaloy update multitenant` to take the new schema file.\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: `project` → `projects`.\n4. Read the generated SQL before you apply it. It must rename the table and its index (`ALTER TABLE ... RENAME TO ...`), and 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, then sign in once to confirm the adapter finds every table.\n\n## Upgrading from rbac\n\nUntil 2026-09-20 a separate `rbac` module shipped the rule, the lock, the gate, the `\u002Froles` screen and the gated `projects.ts`. That module is gone, and `teams` and `multitenant` own its files now. `saasaloy add multitenant` does not bring them back in a project that already has `multitenant`, because `add` skips an installed module. Run `update` per module instead:\n\n1. Commit or stash first, so `git diff` shows what each step did.\n2. Run `saasaloy remove rbac`. It deletes `rbac.ts`, `rbac-rules.ts`, `plugins\u002Frole-lock.ts`, `\u002Froles`, its two components, `admin\u002Flib\u002Ftenant.ts` and `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts`. If `api-keys` is installed, its lock entry still names `rbac` in `dependsOn`, so add `--force`.\n3. Run `saasaloy update teams`. It writes `permission-rules.ts` and `plugins\u002Frole-lock.ts`, and patches `roleLockGuard()` into both `auth` and `adminAuth`. Until this step runs, no base-role lock is active.\n4. Run `saasaloy update multitenant`. It writes `permissions.ts`, the `\u002Froles` screen and its components, `admin\u002Flib\u002Ftenant.ts` and the gated `projects.ts`, and adds the Roles sidebar entry.\n5. If `api-keys` is installed, run `saasaloy update api-keys`. Its files import `@repo\u002Fauth\u002Fpermission-rules` now.\n6. In your own code, change `@repo\u002Fauth\u002Frbac` to `@repo\u002Fauth\u002Fpermissions`, `@repo\u002Fauth\u002Frbac-rules` to `@repo\u002Fauth\u002Fpermission-rules`, and `requireCan` to `requirePermission`. Then run `pnpm typecheck`.\n\nNo table changes. Stored custom roles in `organization_roles` keep working.\n\n## Next\n\nRun `saasaloy-feature` to build a product entity that is scoped to the active organization.\n","# multitenant\n\nThe `multitenant` feature answers one question on every request: **which organization is this for, and who is asking?** `teams` shipped the organizations. This ships the boundary around them.\n\nIt adds `requireTenant(c)` to `packages\u002Fauth`, the branded `TenantId` and the `forTenant` wrapper to `packages\u002Fdb`, `GET \u002Ftenant` to the api, the throwing permission gate `requirePermission(c, permissions)`, the `\u002Froles` screen in `apps\u002Fadmin`, and a worked `projects` example you delete once your own tables exist.\n\n`teams` ships the vocabulary and the pure `can()` rule this module throws on. Read `saasaloy-teams` for `access.ts`, custom roles and the base-role lock.\n\n## The route recipe\n\nTwo lines, and neither is optional.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts\nconst tenant = await requireTenant(c);\nconst rows = await withDb(c, (db) => listProjects(db, tenant.organizationId));\n```\n\n```ts\n\u002F\u002F packages\u002Fdb\u002Fsrc\u002Frepositories\u002Fprojects.ts\nexport function listProjects(db: Db, tenantId: TenantId) {\n  return forTenant(db, tenantId).select(projects);\n}\n```\n\nOn the cookie path, `requireTenant` reads the session the request's `x-auth-audience` header names, through `requireSession` and `authFor(c).api.getActiveMember`: the client session by default, the admin session when the admin app calls. A scoped screen in `apps\u002Fadmin` therefore acts as the admin signed in there, with that admin's active organization, and the same route serves a client app unchanged.\n\n`requireTenant` is the only thing in the project that mints a `TenantId`, and `forTenant` accepts nothing else. A handler that skips the first line cannot call the second, and that is a compile error rather than a review note.\n\nThe queries live in a repository, not in the route. `drizzle-orm` belongs to `@repo\u002Fdb` and no other workspace imports it (ADR 0020), so a route cannot write `eq(...)` even when it wants to.\n\n**The one gap:** a handler that ignores `forTenant` and writes `db.select().from(projects)` still compiles. Convention and review cover that in v1; a lint rule that refuses raw `db` on a tenant table is a filed follow-up. Read a scoped route for the `forTenant(` call the same way you read it for the `requireTenant(` call.\n\n## The permission gate\n\nOn a write, the first line changes. `requirePermission` replaces `requireTenant` rather than joining it.\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts\nexport const projects = new Hono\u003C{ Bindings: AuthDbBindings }>()\n  .get(\"\u002F\", async (c) => {\n    const tenant = await requireTenant(c); \u002F\u002F membership is the gate on a read\n    \u002F\u002F ...\n  })\n  .delete(\"\u002F:id\", async (c) => {\n    const tenant = await requirePermission(c, { project: [\"delete\"] });\n    await withDb(c, (db) => deleteProject(db, tenant.organizationId, c.req.param(\"id\")));\n    return c.json({ id }, 200);\n  });\n```\n\n`requirePermission` **is** `requireTenant` plus `can`, and it returns the same `Tenant`. Never call both in one handler: the second call re-resolves the session and re-runs the `organization_roles` query for an answer it already has.\n\nReads usually stay on `requireTenant`. `member` holds `project: [\"read\"]` in `access.ts`, so gating a read is the same check written twice. Gate a read when some members must not see the rows at all, not by reflex.\n\n`permissions` is typed by `Permissions` from `access.ts`. An undeclared resource or a misspelled action is a compile error, not a check that silently passes.\n\n## The `\u002Froles` screen\n\n`apps\u002Fadmin` imports `allows` from `@repo\u002Fauth\u002Fpermission-rules`, fetches `GET \u002Ftenant` once per page through `tenantQuery`, and hides a control the caller may not use. Better Auth's `checkRolePermission` is deliberately not used: it knows the static roles only, so it answers wrongly for every custom role.\n\n**The hide is cosmetic. The 403 is the gate.** A screen that hides a button and skips `requirePermission` has no authorization at all. Write the route check first, then hide the control.\n\nThe screen ships here rather than in `teams` because it calls `GET \u002Ftenant`, and this module mounts that route. A `teams`-only project would render the screen onto a 404.\n\nA `nav-entry` patch adds the screen to the admin sidebar: `{ to: \"\u002Froles\", label: \"Roles\" }` with `ShieldCheckIcon`, in the `Manage` group of `NAV_AREAS` in `apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav.ts`. `remove multitenant` reverses it.\n\n## Three different questions\n\nDo not reach for the wrong one.\n\n| Helper | Question |\n| --- | --- |\n| `requireAdmin(c)` | Does the admin session hold an admin role? (`requireAdminApp(c)` asks who may open `apps\u002Fadmin`) |\n| `requireSuperadmin(c)` | Is this the one site role that crosses organizations? |\n| `requireTenant(c)` | Which organization is this request for, and as whom? |\n| `requirePermission(c, p)` | That, and may they do this here? |\n\nA site `admin` is an ordinary member on every tenant route. The site role grants nothing here, so an `admin` who belongs to no organization gets the same 403 as anyone else.\n\n## The tenant column convention\n\nEvery table a request may read on behalf of one organization declares the same column and the same index:\n\n```ts\nexport const projects = sqliteTable(\n  \"projects\",\n  { id: text(\"id\").primaryKey(), organizationId: tenantColumn(), \u002F* ... *\u002F },\n  (table) => [tenantIndex(table, \"projects\")]\n);\n```\n\n`tenantColumn()` and `tenantIndex()` come from `@repo\u002Fdb\u002Ftenant-column`, which ships in two dialects. They expand to `text(\"organization_id\").notNull().references(() => organization.id)` plus one index named `\u003Ctable>_organization_id_idx`.\n\nThree parts matter, each for its own reason:\n\n- **The property name is `organizationId`.** `forTenant` reads `table.organizationId`, so a table naming it `orgId` does not fit `TenantTable` even when the column underneath is right.\n- **`notNull` is not negotiable.** A nullable tenant column makes a row belonging to no organization, which every scoped query silently omits and no guard ever refuses.\n- **The index carries every scoped read.** Without it each one is a full scan.\n\nThe `teams` and `api-keys-organization` tables already meet the convention. `members`, `invitations` and `organization_roles` were hand-written that way; `api_keys` gets there through the API-key plugin's `referenceId` field rename. `organizations` itself is the parent and carries no tenant column.\n\n## What `TenantId` refuses\n\n`TenantId` is `string` at runtime and a distinct type at compile time. `packages\u002Fdb\u002Fsrc\u002Ftenant.typecheck.ts` is the proof, and `pnpm typecheck` in `packages\u002Fdb` runs it. Every `@ts-expect-error` in that file is an assertion, so `tsc` fails if one stops being an error. Do not silence one; change it in the same commit as the guard, and say why.\n\nIt refuses, in order of how likely each is to be the bug:\n\n- a raw string, so a route that reads an organization id out of a request body or a header cannot scope a query with it,\n- a table with no `organizationId` column,\n- an insert that names `organizationId` itself, so a request body spread into `values` cannot write into another organization,\n- an update that sets `organizationId`, which is how a row would be moved between organizations.\n\n## The header contract\n\n`x-organization-id` names an organization to act inside. It is honoured **only** on the cookie path and **only** for a `superadmin` on the admin session. `mayCrossOrganizations` in `tenant-rules.ts` checks both the role and `session.audience === \"admin\"`. The admin app's `api` client sends `x-auth-audience: admin`, which is what makes `requireTenant` read the admin session. A superadmin's client session, the one they use the product with, gets the 403 like any other caller.\n\n- A `superadmin` on the admin session sending it gets that organization, with `principal: { kind: \"superadmin\", userId }`. The id is looked up first, so a typo is 404 `unknown organization` rather than a tenant that does not exist.\n- Any other signed-in caller sending it gets 403 `forbidden`, a `superadmin` on the client session included. Refused, not ignored: a silently ignored header reads as \"it worked\" to whoever sent it.\n- Beside a bearer credential it is 403 whatever it says. A key is bound to one organization.\n\nThere is no organization picker in `apps\u002Fadmin` yet. Reach for the header with `curl` until the follow-up issue lands. Sign in on `\u002Fadmin\u002Fauth\u002Fsign-in\u002Femail` and send `x-auth-audience: admin` beside `x-organization-id`, or the request reads the client session and gets 403.\n\n## Failure codes\n\nEvery one of these renders through api's `ERROR_CODES` envelope, so a caller parses one body.\n\n| Condition | Status | Message |\n| --- | --- | --- |\n| Signed out | 401 | `sign in first` |\n| No active organization, or membership revoked | 403 | `no active organization` |\n| `x-organization-id` from a caller who may not send it | 403 | `forbidden` |\n| `x-organization-id` from a `superadmin` on the admin session naming no organization | 404 | `unknown organization` |\n| A claimed bearer credential that fails (`api-keys-organization`) | 401 | `invalid api key` |\n| A `can()` refusal | 403 | `permission required: \u003Cresource>:\u003Caction>` |\n| A write naming a base role (`teams`) | 403 | `base role is locked: \u003Cname>` |\n\nThe permission message names the first missing pair, never the whole demand: a refusal listing every permission a route wants would describe the route to an attacker.\n\n`NO_ACTIVE_ORGANIZATION` is exported and `apps\u002Fadmin` matches on the exact string, to tell \"you have no organization yet\" apart from \"you may not do this\". Change it in `tenant-rules.ts` and change the SPA in the same commit.\n\n## The credential resolver table\n\n`packages\u002Fauth\u002Fsrc\u002Ftenant.ts` exports an empty table:\n\n```ts\nexport const tenantResolvers = defineTenantResolvers({ resolvers: [] });\n```\n\nA credential module registers into it with one `plugin-array` patch, the same shape `authClientPlugins` uses. Keep the array literal at module scope, and never remove it even while it is empty.\n\nA resolver has a `name`, a synchronous `claims(headers)` and an async `resolve(c)`. `claims` answers \"is this my credential\", not \"is it valid\". Returning `true` takes the request off the session path for good: `resolve` then returns a `Tenant` or throws. That is what stops a rejected API key from quietly falling back to whatever session cookie rode along with it. Array order is precedence; the first claimer wins.\n\n## Roles are loaded once\n\nOn the member path, `requireTenant` reads that organization's `organization_roles` rows in one query and resolves the caller's statements onto the principal. `can()` then reads the answer instead of asking again, so a route with three permission checks still pays for one round trip.\n\nThe merge has four cases, all in `resolveStatements` in `tenant-rules.ts` and all covered by `tenant-rules.test.ts`: a base role with a stored row of the same name resolves to the static role widened by the row; a base role alone resolves to itself; a custom role resolves to its stored row; a name matching neither resolves to nothing. The last one is the decision that matters — a deleted role fails closed for its holders rather than falling back to `member`.\n\n## Boundaries to honor\n\n- **Do not add a second permission path.** `can()` reads `principal.statements` and nothing else. A route that calls `auth.api.hasPermission` itself pays a query per check and answers from a different engine.\n- **Do not mint a `TenantId` outside `requireTenant`.** `asTenantId` exists for that one caller. Calling it on a request-supplied value hands out another organization's rows.\n- **Do not widen `Tenant.organizationId` to `string`.** Every guarantee above turns into a naming convention the moment you do.\n- **Do not resolve the tenant in middleware.** The `chained-route` patch kind registers routes, not `.use()` links (ADR 0028), so a middleware convention would have no way to install itself.\n- **The `projects` table and its routes are an example.** Delete them once your own scoped tables exist. `remove multitenant` names `projects` in its warning, and every route written against `requireTenant`, `forTenant` or `requirePermission` stops compiling when this module goes. A third warning covers custom roles: `teams` keeps them live after this removal, and the `\u002Froles` screen that edits them goes with this module.\n\n## Upgrading from singular table names\n\nA project that installed `multitenant` before the tables became plural has a `project` table in its database. `projects` is this module's example table, not a Better Auth table, so the adapter never looks it up. A project that already deleted the example has nothing to do here. Otherwise, move it to the new name like this:\n\n1. Update `auth` first, because its schema rename and `usePlural: true` land together. Then run `saasaloy update multitenant` to take the new schema file.\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: `project` → `projects`.\n4. Read the generated SQL before you apply it. It must rename the table and its index (`ALTER TABLE ... RENAME TO ...`), and 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, then sign in once to confirm the adapter finds every table.\n\n## Upgrading from rbac\n\nUntil 2026-09-20 a separate `rbac` module shipped the rule, the lock, the gate, the `\u002Froles` screen and the gated `projects.ts`. That module is gone, and `teams` and `multitenant` own its files now. `saasaloy add multitenant` does not bring them back in a project that already has `multitenant`, because `add` skips an installed module. Run `update` per module instead:\n\n1. Commit or stash first, so `git diff` shows what each step did.\n2. Run `saasaloy remove rbac`. It deletes `rbac.ts`, `rbac-rules.ts`, `plugins\u002Frole-lock.ts`, `\u002Froles`, its two components, `admin\u002Flib\u002Ftenant.ts` and `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fprojects.ts`. If `api-keys` is installed, its lock entry still names `rbac` in `dependsOn`, so add `--force`.\n3. Run `saasaloy update teams`. It writes `permission-rules.ts` and `plugins\u002Frole-lock.ts`, and patches `roleLockGuard()` into both `auth` and `adminAuth`. Until this step runs, no base-role lock is active.\n4. Run `saasaloy update multitenant`. It writes `permissions.ts`, the `\u002Froles` screen and its components, `admin\u002Flib\u002Ftenant.ts` and the gated `projects.ts`, and adds the Roles sidebar entry.\n5. If `api-keys` is installed, run `saasaloy update api-keys`. Its files import `@repo\u002Fauth\u002Fpermission-rules` now.\n6. In your own code, change `@repo\u002Fauth\u002Frbac` to `@repo\u002Fauth\u002Fpermissions`, `@repo\u002Fauth\u002Frbac-rules` to `@repo\u002Fauth\u002Fpermission-rules`, and `requireCan` to `requirePermission`. Then run `pnpm typecheck`.\n\nNo table changes. Stored custom roles in `organization_roles` keep working.\n\n## Next\n\nRun `saasaloy-feature` to build a product entity that is scoped to the active organization.\n",{"name":5,"description":7},"main","a46a4dd388795519840da0ed1f695634b6dcd99b","modules\u002Fmultitenant\u002Fskills\u002Fsaasaloy-multitenant",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-multitenant",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-multitenant",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-multitenant","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fmultitenant\u002Fskills\u002Fsaasaloy-multitenant\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",[],[]]