Documentation menuMenu da documentação

$ cat docs/middleware/tenant.md

TenantTenant (workspace)

Know which workspace a request belongs to, without ever trusting the raw x-workspace-id header.Saiba a qual workspace a requisição pertence, sem nunca confiar no header x-workspace-id cru.

What it doesO que faz

tenant<TTenant>(options: TenantOptions<TTenant>): TenantMiddleware<TTenant>. It reads the id from x-workspace-id (from: 'header'), from the label before baseDomain (from: 'subdomain') or from your function, checks the format and calls verify(ctx, tenantId). Whatever verify returns is the tenant: tenants.get(ctx) gives it back typed, and getTenantId(ctx) gives the id (used by audit).

tenant<TTenant>(options: TenantOptions<TTenant>): TenantMiddleware<TTenant>. Ele lê o id de x-workspace-id (from: 'header'), do rótulo antes de baseDomain (from: 'subdomain') ou da sua função, confere o formato e chama verify(ctx, tenantId). O que o verify devolve é o tenant: tenants.get(ctx) devolve tipado, e getTenantId(ctx) devolve o id (usado pelo audit).

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it after the middleware that prepares authentication (session, jwt or apiKey). verify runs before access, so it reads the caller with await ctx.getPrincipal(): that runs the app's authenticate once per request, and access reuses the result.

Registre depois do middleware que prepara a autenticação (session, jwt ou apiKey). O verify roda antes do access, então lê quem chama com await ctx.getPrincipal(): isso roda o authenticate do app uma vez por requisição, e o access reaproveita o resultado.

ExampleExemplo

tenant.ts
import { createModule } from '@tupik/core';
import { tenant } from '@tupik/middleware';

const workspaces = tenant({
  from: 'header', // x-workspace-id
  verify: async (ctx, workspaceId) => {
    const user = await ctx.getPrincipal(); // authenticate, once per request
    // undefined → 403 TENANT_FORBIDDEN
    return user === null ? undefined : findMembership(user.id, workspaceId);
  },
});

const api = createModule('/api')
  .use(workspaces)
  .get('/projects', { access: 'authenticated', handler: (ctx) => listProjects(workspaces.get(ctx)) });
import { createModule } from '@tupik/core';
import { tenant } from '@tupik/middleware';

const workspaces = tenant({
  from: 'header', // x-workspace-id
  verify: async (ctx, workspaceId) => {
    const user = await ctx.getPrincipal(); // authenticate, uma vez por requisição
    // undefined → 403 TENANT_FORBIDDEN
    return user === null ? undefined : findMembership(user.id, workspaceId);
  },
});

const api = createModule('/api')
  .use(workspaces)
  .get('/projects', { access: 'authenticated', handler: (ctx) => listProjects(workspaces.get(ctx)) });

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
from 'header' | 'subdomain' | (ctx) => string | undefined Required. Where the id comes from.Obrigatório. De onde vem o id.
verify (ctx, tenantId) => Awaitable<TTenant | false | null | undefined> Required: without it the factory throws. A falsy result answers 403. May be async and read ctx.getPrincipal().Obrigatório: sem ele a factory lança. Resultado falso responde 403. Pode ser async e ler ctx.getPrincipal().
header string x-workspace-id (with from: 'header').x-workspace-id (com from: 'header').
baseDomain string Required with from: 'subdomain'. acme.app.example.com → acme; deeper labels are rejected.Obrigatório com from: 'subdomain'. acme.app.example.com → acme; rótulos mais fundos são recusados.
required boolean true. false lets requests without an id through (get returns undefined).true. false deixa passar requisições sem id (get devolve undefined).
pattern RegExp /^[A-Za-z0-9_-]{1,128}$/./^[A-Za-z0-9_-]{1,128}$/.

type TenantOptions<TTenant> = { verify; required?; pattern? } & ({ from: "header"; header? } | { from: "subdomain"; baseDomain } | { from: fn })

type TenantOptions<TTenant> = { verify; required?; pattern? } & ({ from: "header"; header? } | { from: "subdomain"; baseDomain } | { from: fn })

Errors and limitsErros e limites

  • No id: 400 TENANT_REQUIRED. Bad format: 400 TENANT_INVALID. verify refused: 403 TENANT_FORBIDDEN. All RFC 9457.
  • Missing verify, or subdomain without baseDomain, throws at creation.
  • An error thrown by verify reaches the engine (500); it is never treated as allowed.
  • Sem id: 400 TENANT_REQUIRED. Formato ruim: 400 TENANT_INVALID. verify recusou: 403 TENANT_FORBIDDEN. Todos RFC 9457.
  • verify ausente, ou subdomain sem baseDomain, lança na criação.
  • Um erro lançado pelo verify chega ao engine (500); nunca é tratado como permitido.

When not to use itQuando não usar

It checks that the caller may enter the workspace, not that each record belongs to it: keep filtering queries by tenant id (row-level ownership is the route access policy in the core).

Ele confere se quem chama pode entrar no workspace, não se cada registro pertence a ele: continue filtrando as consultas pelo id do tenant (a posse por registro é a política de acesso da rota no core).