AGENT SKILL

saasaloy-multitenant

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 /roles screen, or working on the superadmin x-organization-id bypass, the 401/403 rules, or removal behavior.

License 许可
MIT
所属仓库
mimukit/saasaloy
最近更新
2026-11-13
Stars
★ 4
Forks
0

01 前言 Front Matter

name
saasaloy-multitenant
description
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 /roles screen, or working on the superadmin x-organization-id bypass, the 401/403 rules, or removal behavior.

03 SKILL.md 正文

multitenant

The 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.

It adds requireTenant(c) to packages/auth, the branded TenantId and the forTenant wrapper to packages/db, GET /tenant to the api, the throwing permission gate requirePermission(c, permissions), the /roles screen in apps/admin, and a worked projects example you delete once your own tables exist.

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.

The route recipe

Two lines, and neither is optional.

// apps/api/src/routes/projects.ts
const tenant = await requireTenant(c);
const rows = await withDb(c, (db) => listProjects(db, tenant.organizationId));
// packages/db/src/repositories/projects.ts
export function listProjects(db: Db, tenantId: TenantId) {
  return forTenant(db, tenantId).select(projects);
}

On 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/admin therefore acts as the admin signed in there, with that admin's active organization, and the same route serves a client app unchanged.

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.

The queries live in a repository, not in the route. drizzle-orm belongs to @repo/db and no other workspace imports it (ADR 0020), so a route cannot write eq(...) even when it wants to.

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.

The permission gate

On a write, the first line changes. requirePermission replaces requireTenant rather than joining it.

// apps/api/src/routes/projects.ts
export const projects = new Hono<{ Bindings: AuthDbBindings }>()
  .get("/", async (c) => {
    const tenant = await requireTenant(c); // membership is the gate on a read
    // ...
  })
  .delete("/:id", async (c) => {
    const tenant = await requirePermission(c, { project: ["delete"] });
    await withDb(c, (db) => deleteProject(db, tenant.organizationId, c.req.param("id")));
    return c.json({ id }, 200);
  });

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.

Reads 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.

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.

The /roles screen

apps/admin imports allows from @repo/auth/permission-rules, fetches GET /tenant 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.

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.

The screen ships here rather than in teams because it calls GET /tenant, and this module mounts that route. A teams-only project would render the screen onto a 404.

A nav-entry patch adds the screen to the admin sidebar: { to: "/roles", label: "Roles" } with ShieldCheckIcon, in the Manage group of NAV_AREAS in apps/admin/src/components/nav.ts. remove multitenant reverses it.

Three different questions

Do not reach for the wrong one.

Helper Question
requireAdmin(c) Does the admin session hold an admin role? (requireAdminApp(c) asks who may open apps/admin)
requireSuperadmin(c) Is this the one site role that crosses organizations?
requireTenant(c) Which organization is this request for, and as whom?
requirePermission(c, p) That, and may they do this here?

A 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.

The tenant column convention

Every table a request may read on behalf of one organization declares the same column and the same index:

export const projects = sqliteTable(
  "projects",
  { id: text("id").primaryKey(), organizationId: tenantColumn(), /* ... */ },
  (table) => [tenantIndex(table, "projects")]
);

tenantColumn() and tenantIndex() come from @repo/db/tenant-column, which ships in two dialects. They expand to text("organization_id").notNull().references(() => organization.id) plus one index named <table>_organization_id_idx.

Three parts matter, each for its own reason:

  • 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.
  • 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.
  • The index carries every scoped read. Without it each one is a full scan.

The 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.

What TenantId refuses

TenantId is string at runtime and a distinct type at compile time. packages/db/src/tenant.typecheck.ts is the proof, and pnpm typecheck in packages/db 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.

It refuses, in order of how likely each is to be the bug:

  • 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,
  • a table with no organizationId column,
  • an insert that names organizationId itself, so a request body spread into values cannot write into another organization,
  • an update that sets organizationId, which is how a row would be moved between organizations.

The header contract

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.

  • 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.
  • 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.
  • Beside a bearer credential it is 403 whatever it says. A key is bound to one organization.

There is no organization picker in apps/admin yet. Reach for the header with curl until the follow-up issue lands. Sign in on /admin/auth/sign-in/email and send x-auth-audience: admin beside x-organization-id, or the request reads the client session and gets 403.

Failure codes

Every one of these renders through api's ERROR_CODES envelope, so a caller parses one body.

Condition Status Message
Signed out 401 sign in first
No active organization, or membership revoked 403 no active organization
x-organization-id from a caller who may not send it 403 forbidden
x-organization-id from a superadmin on the admin session naming no organization 404 unknown organization
A claimed bearer credential that fails (api-keys-organization) 401 invalid api key
A can() refusal 403 permission required: <resource>:<action>
A write naming a base role (teams) 403 base role is locked: <name>

The 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.

NO_ACTIVE_ORGANIZATION is exported and apps/admin 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.

The credential resolver table

packages/auth/src/tenant.ts exports an empty table:

export const tenantResolvers = defineTenantResolvers({ resolvers: [] });

A 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.

A 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.

Roles are loaded once

On 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.

The 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.

Boundaries to honor

  • 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.
  • 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.
  • Do not widen Tenant.organizationId to string. Every guarantee above turns into a naming convention the moment you do.
  • 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.
  • 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 /roles screen that edits them goes with this module.

Upgrading from singular table names

A 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:

  1. Update auth first, because its schema rename and usePlural: true land together. Then run saasaloy update multitenant to take the new schema file.
  2. Run pnpm db:generate.
  3. 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.
  4. 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.
  5. If it drops a table, delete that migration file and run pnpm db:generate again.
  6. Apply the migration, then sign in once to confirm the adapter finds every table.

Upgrading from rbac

Until 2026-09-20 a separate rbac module shipped the rule, the lock, the gate, the /roles 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:

  1. Commit or stash first, so git diff shows what each step did.
  2. Run saasaloy remove rbac. It deletes rbac.ts, rbac-rules.ts, plugins/role-lock.ts, /roles, its two components, admin/lib/tenant.ts and apps/api/src/routes/projects.ts. If api-keys is installed, its lock entry still names rbac in dependsOn, so add --force.
  3. Run saasaloy update teams. It writes permission-rules.ts and plugins/role-lock.ts, and patches roleLockGuard() into both auth and adminAuth. Until this step runs, no base-role lock is active.
  4. Run saasaloy update multitenant. It writes permissions.ts, the /roles screen and its components, admin/lib/tenant.ts and the gated projects.ts, and adds the Roles sidebar entry.
  5. If api-keys is installed, run saasaloy update api-keys. Its files import @repo/auth/permission-rules now.
  6. In your own code, change @repo/auth/rbac to @repo/auth/permissions, @repo/auth/rbac-rules to @repo/auth/permission-rules, and requireCan to requirePermission. Then run pnpm typecheck.

No table changes. Stored custom roles in organization_roles keep working.

Next

Run saasaloy-feature to build a product entity that is scoped to the active organization.

04 同仓库更多 Skills

mimukit
mimukit/saasaloy

saasaloy-subscription

Runbook for the subscription capability — provider-agnostic subscriptions in packages/subscription, 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.

★ 4
mimukit
mimukit/saasaloy

saasaloy-notification

Runbook for the notification module, in-app notifications for apps/app. It owns the notifications and notification_opt_outs tables, notify() in apps/api/src/lib/notify.ts, the /notifications api routes, the bell in the app header, the sidebar badge, the /notifications 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.

★ 4
mimukit
mimukit/saasaloy

saasaloy-cms

Runbook for the cms module, the in-house CMS behind apps/admin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps/web 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.

★ 4
mimukit
mimukit/saasaloy

saasaloy-beta

The beta module's own procedure.

★ 4
mimukit
mimukit/saasaloy

helper

暂无简介

★ 4
mimukit
mimukit/saasaloy

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/merge-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.

★ 4