Aviary

Tenancy

Make the request's organization the tenant that every Aviary lib scopes its data by. Off until you turn it on.

The tenant is the customer the data belongs to: an organization, a user's personal workspace, a clinic. Once tenancy is on and your app sets the tenant of each request, tenant-aware Aviary libs show a request only its own tenant's data, with no tenancy code in your services.

Tenancy is off by default. Nothing changes for an app that does not turn it on.


Turn it on

ContextModule.forRoot({
  tenancy: {
    enabled: true,
    kinds: ['organization'], // optional: the tenant kinds libs honour
  },
});
OptionDefaultWhat it does
enabledfalseThe single switch. Every lib whose own tenancy option is 'inherit' (their default) starts scoping data by the tenant.
kindsall kindsAllow-list of tenant kinds. With nested tenants, libs scope by the most specific level whose kind is listed. A tenant with no listed level counts as no tenant.
requiredfalseA tenant-scoped read or write with no tenant throws TenantRequiredError (403) instead of using the rows that have no tenant. See Require a tenant.
personalfalseA signed-in user with no tenant counts as their own { kind: 'user' } tenant. See Personal tenants.
labelnone(tenant) => string | undefined | Promise<…>: the display name consoles show in their "Organization" picker. See Labels.

When enabled is true:

  • tenant and tenantId always ride the default cross-process carrier, even if your carrier list leaves them out. A custom serialize/deserialize decides for itself (see Across process boundaries).
  • Context.toBaggage() also sends the tenant's kind as tenantKind.
  • One info line at boot says tenancy is on.

forRootAsync accepts the same tenancy option.


Set the tenant

The app decides who the tenant is. Resolve it on the server, then make one call, typically from your auth guard or an interceptor:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Context } from '@dudousxd/nestjs-context';

@Injectable()
export class OrgGuard implements CanActivate {
  async canActivate(ctx: ExecutionContext): Promise<boolean> {
    const req = ctx.switchToHttp().getRequest();
    const claims = req.user; // already verified by your auth layer

    if (claims.org_id) {
      Context.setTenant({
        id: claims.org_id,
        kind: 'organization',
        slug: claims.org_slug, // optional, display only
        role: claims.org_role, // optional, the caller's role in this org
      });
    }
    return true;
  }
}

Context.setTenant writes both tenant and tenantId. Context.setTenant(null) clears both. A request with no tenant (a user with no organization) is a normal state, not an error.

Take the tenant from something the server verified: a signed token claim, a session, a membership lookup. Never take it straight from a client header or query parameter.

Nested tenants

When tenants nest (a clinic with units), set the most specific one and pass the levels above it as chain, root first:

Context.setTenant({
  id: unit.id,
  kind: 'unit',
  chain: [{ id: clinic.id, kind: 'clinic', slug: clinic.slug }],
});

Context.tenant();      // { id: 'u1', kind: 'unit', source: 'app', chain: [clinic, unit] }
Context.tenantChain(); // [{ id: 'c1', kind: 'clinic', slug: 'sunny' }, { id: 'u1', kind: 'unit' }]
Context.tenantId();    // 'u1'

Each lib scopes by the level its kinds name: a lib with kinds: ['clinic'] stamps and filters rows by the clinic, another with kinds: ['unit'] by the unit. Without kinds, libs use the most specific level.

Several tenant families

A request can also belong to tenants that are not part of the same hierarchy, for example a patient's own account next to the clinic. Set those with a family:

Context.setTenant({ id: clinic.id, kind: 'clinic' });
Context.setTenant({ id: account.id, kind: 'account' }, { family: 'account' });

Context.tenant();             // the clinic: the primary tenant, the one tenantId mirrors
Context.tenants();            // [clinic, { ...account, family: 'account' }]
Context.tenantChain('account');
Context.setTenant(null, { family: 'account' }); // clears only that family

A lib uses another family only when its kinds name that family's kind (kinds: ['account']) or its family option names it. Otherwise libs see only the primary tenant.

Personal tenants

With personal: true, a signed-in user (userRef) who has no tenant is treated as a tenant of their own, { id: userRef.id, kind: 'user', source: 'personal' }. The libs then keep each user's data apart, the same way they do for organizations. You can also switch to it explicitly, for example when the user picks "Personal" in an organization switcher:

Context.setTenant({ kind: 'user' }); // the id comes from the context's userRef

Without personal: true, setTenant({ kind: 'user' }) without an id throws. A user tenant with an explicit id is always accepted.

Apps that already put a tenantId in the store through initialize, an enricher or Context.set('tenantId', …) keep working. A plain tenantId reads as { id, kind: 'unknown', source: 'legacy' }. Set a kind with setTenant (or return a tenant from initialize) when you use kinds, because a tenant of kind 'unknown' never matches a kinds list.


Read the tenant

Context.tenant();   // { id: 'org_1', kind: 'organization', source: 'app', slug: 'acme' } | undefined
Context.tenantId(); // 'org_1' | undefined, always equal to tenant()?.id
Context.tenancy();  // { enabled: true, kinds: ['organization'], required: false, personal: false }
Context.tenants();  // the primary tenant first, then the other families
Context.tenantChain(); // the primary tenant's levels, root first
Context.requireTenant(); // the tenant, or throws TenantRequiredError

A TenantRef has these fields:

FieldMeaning
idStable key. Libs stamp and compare rows by it.
kind'organization', 'user', or any string of your own ('clinic'). 'unknown' for a plain tenantId.
source'app' (set in this process), 'carrier' (restored from a carrier or baggage), 'personal' (the signed-in user, see personal), 'legacy' (only a plain tenantId).
slugDisplay only, never a key.
roleThe caller's role inside this tenant. Display and authorization input only.
chainThe levels when tenants nest, root first and this tenant last. Absent for a flat tenant.
familyThe family name, on tenants set with { family }.

Require a tenant

Turn on required when every tenant-scoped piece of data must belong to a tenant:

ContextModule.forRoot({ tenancy: { enabled: true, required: true } });

A lib that reads or writes tenant data in a request with no tenant then throws TenantRequiredError, a 403 Forbidden with code: 'E_TENANT_REQUIRED', instead of using the rows that have no tenant. Work with no context at all (boot, internal workers) and Context.allTenants() still run. A lib can keep a path open without a tenant with its own tenancy: { required: false }.

For a route that needs a tenant regardless of the config, call Context.requireTenant() (or requireTenant({ kinds: ['clinic'] })) at the top of the handler.


Labels

Consoles show an "Organization" picker. By default it shows each tenant's slug, else its id. Give it real names with label:

ContextModule.forRootAsync({
  imports: [OrgsModule],
  inject: [OrgsService],
  useFactory: (orgs: OrgsService) => ({
    tenancy: {
      enabled: true,
      label: async (tenant) =>
        tenant.kind === 'organization' ? (await orgs.find(tenant.id))?.name : undefined,
    },
  }),
});

await Context.tenantLabel({ id: 'org_1', kind: 'organization' }); // 'Acme Inc.'
await Context.tenantLabels(tenants); // { org_1: 'Acme Inc.', org_2: 'globex' }

Return undefined to fall back to the slug or id. A resolver that throws falls back the same way. A lib that knows the tenants (an auth integration) can register a resolver with Context.setTenantLabeler(fn). The label option always wins over it.


Run code as a tenant, or as all tenants

Code outside a request (scripts, seeders, webhook handlers, tests) has no tenant. Give it one:

await Context.withTenant({ id: 'org_1', kind: 'organization' }, () => importInvoices());

withTenant runs the function in a copy of the current store with that tenant, or in a new store when there is none. withTenant(null, fn) runs with no tenant.

Admin and maintenance code that must see every tenant says so explicitly:

const all = await Context.allTenants(() => invoices.findAll());

allTenants is the only way to see other tenants' data. It is never carried across a boundary: a job enqueued inside it runs with the tenant it was enqueued with.


How libs scope data

Every tenant-aware lib asks the context for a filter, and applies the same rule to rows that carry a nullable tenant id:

Filter modeWhenRow of this tenantRow of another tenantRow with no tenant
tenanta request with a tenantvisibleinvisibleinvisible (visible with nullRows: 'shared')
tenantlessa request with no tenant, or none of a kind in kinds (with required, an error instead)—invisiblevisible
allinside Context.allTenants()visiblevisiblevisible
systemno context at all (boot, internal workers)visiblevisiblevisible

New rows are stamped with the tenant's id in tenant mode and with no tenant otherwise. A row the request cannot see is reported as not found (404), never as forbidden (403), so ids of other tenants do not leak.

Tenancy only narrows what a request sees. Each lib's own access rules still run.

Per-lib option

Each tenant-aware lib takes the same option:

tenancy?: 'inherit' | false | {
  enabled?: 'inherit' | boolean; // 'inherit' follows ContextModule's tenancy.enabled
  kinds?: string[];              // the level(s) this lib scopes by, instead of the context's kinds
  family?: string;               // scope by the tenant of this family
  required?: boolean;            // overrides ContextModule's tenancy.required for this lib
  nullRows?: 'tenantless' | 'shared'; // default 'tenantless'
};

The default 'inherit' follows the context switch. false keeps one lib out of tenancy. An explicit argument you pass to a lib call, or an explicit tenant hook in the lib's config, always wins over the context tenant.


Across process boundaries

The tenant travels with the rest of the context, so a queued job runs in the tenant that dispatched it:

await queue.add('send-invoice', { ...payload, __ctx: Context.serialize() });

// worker
Context.deserialize(job.data.__ctx, () => handler(job)); // Context.tenant() is restored, source 'carrier'

The default carrier includes tenant when one is set. With tenancy on, it is added even when your carrier list leaves it out. A custom serialize/deserialize is your own decision: the tenant crosses the boundary only if your serialize writes it and is restored only if your deserialize returns it. Use that to keep the tenant off carriers you don't trust. See Cross-Process.

A library that keeps work running after the request (a durable run resumed by a timer, a scheduled job) must store the tenant with that work and restore it itself; a context carrier alone only covers the hop it was attached to.

Over W3C baggage, toBaggage() sends tenantId and, with tenancy on, tenantKind. fromBaggage() restores the tenant only from a header that carries both. Only call fromBaggage on traffic from services you trust.


Testing

import { Context } from '@dudousxd/nestjs-context';

it('shows only the tenant rows', async () => {
  Context.configure({ tenancy: { enabled: true } });
  const rows = await Context.withTenant({ id: 'org_1', kind: 'organization' }, () => service.list());
  expect(rows.every((r) => r.tenantId === 'org_1')).toBe(true);
  Context.resetConfig();
});

For lib authors: the local reader

Libs never import @dudousxd/nestjs-context. They read the accessor structurally, either the CONTEXT_ACCESSOR they injected with @Optional(), or the global slot globalThis[Symbol.for('@dudousxd/nestjs-diagnostics:accessor')].current, which ContextModule publishes at init even when @dudousxd/nestjs-diagnostics is not installed.

Copy this file into your lib (for example src/tenancy.ts) as is. With the context missing, or an older context without tenancy, readTenancy answers { enabled: false }, so your lib behaves exactly as it does today. Call it per operation, not once at boot. With an older context, the family and required options are ignored and tenantLabels falls back to slug or id.

// Local reader for the @dudousxd/nestjs-context tenancy contract. Copied into each lib;
// it imports nothing, so the lib works with any context version or none at all.
export interface TenantLevel {
  id: string;
  kind: string;
  slug?: string;
  role?: string;
}
export interface TenantRef extends TenantLevel {
  source: string;
  chain?: TenantLevel[]; // root first, this tenant last; absent for a flat tenant
  family?: string;
}
export type TenantFilter =
  | { mode: 'system' }
  | { mode: 'all' }
  | { mode: 'tenantless' }
  | { mode: 'tenant'; tenant: TenantRef; chain?: TenantLevel[] }; // `chain`: context >= 2.1
export type TenancyOption =
  | 'inherit'
  | false
  | {
      enabled?: 'inherit' | boolean;
      kinds?: string[];
      family?: string;
      required?: boolean;
      nullRows?: 'tenantless' | 'shared';
    };
export type Tenancy =
  | { enabled: false }
  | { enabled: true; nullRows: 'tenantless' | 'shared'; filter(): TenantFilter };

interface FilterOptions {
  kinds?: string[];
  family?: string;
  required?: boolean;
}
interface Accessor {
  tenancy?(): { enabled: boolean; kinds?: string[]; required?: boolean };
  tenantFilter?(options?: FilterOptions): TenantFilter;
  tenantLabels?(tenants: TenantLevel[]): Promise<Record<string, string>>;
}
const SLOT = Symbol.for('@dudousxd/nestjs-diagnostics:accessor');

function accessorOf(accessor: unknown): Accessor | undefined {
  const slot = (globalThis as unknown as Record<symbol, { current?: unknown } | undefined>)[SLOT];
  return (accessor ?? slot?.current ?? undefined) as Accessor | undefined;
}

/** `accessor`: the `CONTEXT_ACCESSOR` injected with `@Optional()`, if any. Call per operation. */
export function readTenancy(option: TenancyOption = 'inherit', accessor?: unknown): Tenancy {
  const a = accessorOf(accessor);
  if (option === false || typeof a?.tenancy !== 'function' || !a.tenantFilter) {
    return { enabled: false };
  }
  const own = typeof option === 'object' ? option : {};
  const inherit = own.enabled === undefined || own.enabled === 'inherit';
  if (!(inherit ? a.tenancy().enabled : own.enabled)) return { enabled: false };
  const options: FilterOptions = {};
  if (own.kinds) options.kinds = own.kinds;
  if (own.family !== undefined) options.family = own.family;
  if (own.required !== undefined) options.required = own.required;
  const tenantFilter = a.tenantFilter.bind(a);
  return {
    enabled: true,
    nullRows: own.nullRows ?? 'tenantless',
    // Throws the context's TenantRequiredError (403) when a tenant is required and missing.
    filter: () => tenantFilter(Object.keys(options).length > 0 ? options : undefined),
  };
}

/** The matching rule: may this request see a row whose tenant column holds `rowTenantId`? */
export function canSeeRow(t: Tenancy, rowTenantId: string | null | undefined): boolean {
  if (!t.enabled) return true;
  const f = t.filter();
  if (f.mode === 'system' || f.mode === 'all') return true;
  if (rowTenantId === null || rowTenantId === undefined) {
    return f.mode === 'tenantless' || t.nullRows === 'shared';
  }
  return f.mode === 'tenant' && f.tenant.id === rowTenantId;
}

/** The tenant id to stamp on a new row: the active tenant's id, else `null`. */
export function rowTenantId(t: Tenancy): string | null {
  if (!t.enabled) return null;
  const f = t.filter();
  return f.mode === 'tenant' ? f.tenant.id : null;
}

/** Console labels keyed by tenant id: the app's `tenancy.label`, else the slug, else the id. */
export async function tenantLabels(
  tenants: TenantLevel[],
  accessor?: unknown,
): Promise<Record<string, string>> {
  const a = accessorOf(accessor);
  if (typeof a?.tenantLabels === 'function') {
    try {
      return await a.tenantLabels(tenants);
    } catch {
      // Fall back to slug/id below.
    }
  }
  const out: Record<string, string> = {};
  for (const t of tenants) out[t.id] = t.slug || t.id;
  return out;
}

Use it like this:

@Injectable()
export class InvoiceStore {
  constructor(
    @Optional() @Inject(Symbol.for('@dudousxd/nestjs-context:accessor')) private readonly ctx?: unknown,
    @Inject(INVOICE_OPTIONS) private readonly options: { tenancy?: TenancyOption } = {},
  ) {}

  async find(id: string) {
    const row = await this.repo.findOne(id);
    if (!row || !canSeeRow(readTenancy(this.options.tenancy, this.ctx), row.tenantId)) {
      throw new NotFoundException(); // 404, never 403
    }
    return row;
  }

  async create(input: NewInvoice) {
    const tenantId = rowTenantId(readTenancy(this.options.tenancy, this.ctx));
    return this.repo.insert({ ...input, tenantId });
  }
}

For queries, turn the filter into a WHERE clause instead of filtering in memory: tenant → tenant_id = :id (or tenant_id = :id OR tenant_id IS NULL with nullRows: 'shared'), tenantless → tenant_id IS NULL, all and system → no condition.

filter() throws TenantRequiredError when the app requires a tenant and the request has none. Let it propagate from request paths, so the caller gets a 403. On a path that must keep working without a tenant (recording telemetry, a health check), catch it or pass required: false.

What the accessor exposes

Every member beyond traceId, tenantId, userRef and get is optional, so feature-detect each one:

MemberReturns
tenancy(){ enabled, kinds?, required, personal }
tenantFilter({ kinds?, family?, required? }){ mode: 'system' }, { mode: 'all' }, { mode: 'tenantless' } or { mode: 'tenant', tenant, chain }. tenant is the level that matched kinds.
tenant()The primary tenant: { id, kind, source, slug?, role?, chain?, family? }
tenants()The primary tenant, then the other families
tenantChain(family?)The levels, root first
requireTenant({ kinds?, family? })The matching tenant, or throws TenantRequiredError
tenantLabel(level) / tenantLabels(levels)Display labels (Promise)

Restoring a tenant around later work

A lib that resumes work after the request (a durable run, a scheduled job) stamps the tenant on the work and restores it with withTenant. Read it from the tenancy slot, which ContextModule publishes at init:

interface TenancySlot {
  version: 1;
  withTenant<T>(tenant: { id: string; kind: string; chain?: unknown[]; family?: string } | null, fn: () => T): T;
  // also: tenancy, tenant, tenants, tenantChain, tenantFilter, requireTenant,
  // setTenant, allTenants, tenantLabel, tenantLabels, setTenantLabeler
}
const slot = (globalThis as Record<symbol, TenancySlot | undefined>)[
  Symbol.for('@dudousxd/nestjs-context:tenancy')
];
if (slot?.version === 1) {
  await slot.withTenant({ id: row.tenantId, kind: row.tenantKind }, () => resume(row));
}

Treat a missing slot, or a version other than 1, as tenancy off.

On this page