Documentation menuMenu da documentação

$ cat docs/recipes/multi-tenant.md

Recipe: multi-tenantReceita: multi-tenant

Each request belongs to one workspace. The id comes from the request, but only a verified membership lets it through.Cada requisição pertence a um workspace. O id vem da requisição, mas só um vínculo conferido o deixa passar.

Resolve and verify the tenantResolver e conferir o tenant

tenant reads the id from x-workspace-id (from: 'header'), from a subdomain (from: 'subdomain' with baseDomain) or from your function. verify(ctx, id) is mandatory: the factory throws without it. Whatever it returns is the tenant; false, null or undefined answer 403 TENANT_FORBIDDEN.

tenant lê o id de x-workspace-id (from: 'header'), de um subdomínio (from: 'subdomain' com baseDomain) ou da sua função. O verify(ctx, id) é obrigatório: a factory lança erro sem ele. O que ele devolve é o tenant; false, null ou undefined respondem 403 TENANT_FORBIDDEN.

Without an id the middleware answers 400 TENANT_REQUIRED (unless required: false), and an id outside /^[A-Za-z0-9_-]{1,128}$/ answers 400 TENANT_INVALID.

Sem id o middleware responde 400 TENANT_REQUIRED (salvo required: false), e um id fora de /^[A-Za-z0-9_-]{1,128}$/ responde 400 TENANT_INVALID.

Scope every queryPrender toda consulta

Pass getTenantId(ctx) to every query, so a record of another workspace is simply not found. Use workspaces.get(ctx) for the typed tenant in an access policy, such as "only owners delete".

Passe getTenantId(ctx) para toda consulta, então o registro de outro workspace simplesmente não aparece. Use workspaces.get(ctx) para ler o tenant tipado numa política de access, como "só o dono apaga".

projects.ts
import { createApp, createModule } from '@tupik/core';
import { getTenantId, tenant } from '@tupik/middleware';
import { z } from 'zod';
import { auth, db } from './services';

type User = { id: string };
type Workspace = { id: string; role: 'owner' | 'member' };
declare module '@tupik/core' {
  interface TupikRegister {
    principal: User;
  }
}

const workspaces = tenant<Workspace>({
  from: 'header', // x-workspace-id by default
  verify: async (ctx, workspaceId) => {
    // authenticate, run once and reused by access
    const user = await ctx.getPrincipal();
    // no membership: 403 TENANT_FORBIDDEN
    return user === null ? null : db.membership(user.id, workspaceId);
  },
});

type Ctx = Parameters<typeof workspaces.get>[0];
// the verified id; required: true (default) guarantees it
const tenantId = (ctx: Ctx): string => {
  const id = getTenantId(ctx);
  if (id === undefined) throw new Error('tenant() did not run');
  return id;
};
const isOwner = (ctx: Ctx) => workspaces.get(ctx)?.role === 'owner';

const projects = createModule('/projects')
  .use(workspaces)
  .access('authenticated')
  .get('/', {
    // every query takes the verified tenant id
    handler: (ctx) => db.projects(tenantId(ctx)),
  })
  .get('/:id', {
    schema: { params: z.object({ id: z.string() }) },
    handler: async (ctx) => (await db.project(tenantId(ctx), ctx.params.id)) ?? ctx.status(404).json({ code: 'NOT_FOUND' }),
  })
  .delete('/:id', {
    schema: { params: z.object({ id: z.string() }) },
    access: isOwner,
    handler: async (ctx) => {
      await db.deleteProject(tenantId(ctx), ctx.params.id);
      return ctx.status(204).text('');
    },
  });

export default createApp({ authenticate: (ctx) => auth.userFromRequest(ctx.req) }).register(projects);
import { createApp, createModule } from '@tupik/core';
import { getTenantId, tenant } from '@tupik/middleware';
import { z } from 'zod';
import { auth, db } from './services';

type User = { id: string };
type Workspace = { id: string; role: 'owner' | 'member' };
declare module '@tupik/core' {
  interface TupikRegister {
    principal: User;
  }
}

const workspaces = tenant<Workspace>({
  from: 'header', // x-workspace-id por padrão
  verify: async (ctx, workspaceId) => {
    // authenticate, rodado uma vez e reaproveitado pelo access
    const user = await ctx.getPrincipal();
    // sem vínculo: 403 TENANT_FORBIDDEN
    return user === null ? null : db.membership(user.id, workspaceId);
  },
});

type Ctx = Parameters<typeof workspaces.get>[0];
// o id verificado; required: true (padrão) garante que existe
const tenantId = (ctx: Ctx): string => {
  const id = getTenantId(ctx);
  if (id === undefined) throw new Error('tenant() did not run');
  return id;
};
const isOwner = (ctx: Ctx) => workspaces.get(ctx)?.role === 'owner';

const projects = createModule('/projects')
  .use(workspaces)
  .access('authenticated')
  .get('/', {
    // toda consulta recebe o id verificado do tenant
    handler: (ctx) => db.projects(tenantId(ctx)),
  })
  .get('/:id', {
    schema: { params: z.object({ id: z.string() }) },
    handler: async (ctx) => (await db.project(tenantId(ctx), ctx.params.id)) ?? ctx.status(404).json({ code: 'NOT_FOUND' }),
  })
  .delete('/:id', {
    schema: { params: z.object({ id: z.string() }) },
    access: isOwner,
    handler: async (ctx) => {
      await db.deleteProject(tenantId(ctx), ctx.params.id);
      return ctx.status(204).text('');
    },
  });

export default createApp({ authenticate: (ctx) => auth.userFromRequest(ctx.req) }).register(projects);

What can go wrongO que pode dar errado

  • verify runs as middleware, before access. Read the user with await ctx.getPrincipal(): it runs authenticate once per request and access reuses the result. Register the session middleware that authenticate reads before tenant.
  • A query without the tenant id in the filter leaks across workspaces. tupik-lint flags lookups by ctx.params without a tenant or owner in the same filter.
  • Caching verify results makes a removed member keep access until the cache expires. Keep the TTL short.
  • O verify roda como middleware, antes do access. Leia o usuário com await ctx.getPrincipal(): ele roda o authenticate uma vez por requisição e o access reaproveita o resultado. Registre antes do tenant o middleware de sessão que o authenticate lê.
  • Consulta sem o id do tenant no filtro vaza entre workspaces. O tupik-lint aponta consultas por ctx.params sem tenant ou dono no mesmo filtro.
  • Guardar em cache o resultado do verify faz um membro removido manter acesso até o cache vencer. Use TTL curto.