[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationTenancy

Tenancy

Schema constants, tenancy tables, request tenant resolution, access gates, membership writes, and the tenant lifecycle contract.

Overview

The DMS serves several tenants from one backend. Tenant-owned tables live in a per-tenant schema, and a model handle is bound to one tenant when you obtain it. GetModel(TenantMemberModel, tenantId) reads and writes the rows of that tenant only. No query filters rows by tenant, and no table carries a tenantId column. The handle carries the isolation.

For a first implementation, follow Multi-tenant data. It registers the table in the tenant schema, protects the route, and injects a tenant-bound model. This page lists the schema constants and the lifecycle contracts. Resolving a tenant id is not an authorization check, so getRequestTenantId must run behind authentication.

The tenancy exports span several subpaths:

SubpathContains
@antelopejs/interface-dms/constantsSchema names and the default tenant
@antelopejs/interface-dms/dbThe Tenant, TenantMember and Role tables and their models
@antelopejs/interface-dms/request-tenantResolving the request's tenant
@antelopejs/interface-dms/tenant-scoped-modelInjecting a tenant-bound model
@antelopejs/interface-dms/tenant-accessTenant access gates
@antelopejs/interface-dms/tenant-ownershipMembership and ownership writes
@antelopejs/interface-dms/tenant-memberschangeTenantMembers, the one write path for memberships and invitations
@antelopejs/interface-dms/tenant-lifecycleProducer admission and permanent closure before deletion
@antelopejs/interface-dms/utils/saas-modeDeclaring SaaS mode
@antelopejs/interface-dms/data-controllersThe built-in members and roles data controllers

Constants

typescript
import {
  CORE_SCHEMA_NAME,
  DEFAULT_TENANT_ID,
  DEFAULT_TENANT_NAME,
  TENANT_SCHEMA_NAME,
} from "@antelopejs/interface-dms/constants";
ConstantValueMeaning
CORE_SCHEMA_NAME"dms-core"Schema for tables with a single instance across the whole backend.
TENANT_SCHEMA_NAME"dms-tenant"Schema instantiated once per tenant.
DEFAULT_TENANT_ID"default"The tenant an unauthenticated request resolves to, and the only tenant a single-tenant project uses.
DEFAULT_TENANT_NAME"Default"Display name of that tenant.

Register your own table in TENANT_SCHEMA_NAME to make it per-tenant, or in CORE_SCHEMA_NAME to keep one instance of it:

typescript
import {
  Field,
  Index,
  RegisterTable,
  Table,
} from "@antelopejs/interface-database-decorators";
import { TENANT_SCHEMA_NAME } from "@antelopejs/interface-dms/constants";

@RegisterTable("invoices", TENANT_SCHEMA_NAME)
export class Invoice extends Table {
  @Field("string")
  declare _id: string;

  @Index()
  @Field("string")
  declare reference: string;
}

The tenancy tables

@antelopejs/interface-dms/db exports the three tables, their models, and the table-name constants tenantsTableName, tenantMembersTableName and ROLES_TABLE_NAME.

Tenant

Table tenants in dms-core. It holds one row per tenant, shared across the backend.

FieldTypeNotes
_idstringTenant id. Every per-tenant model handle takes it as the instance id.
namestringDisplay name.
createdAtDateCreation time, indexed.
updatedAtDateUpdate time, indexed.

TenantModel extends BasicDataModel(Tenant, tenantsTableName) and adds getMany(ids: string[]): Promise<Tenant[]>, which returns [] for an empty id list. tenants is a core-schema table, so you obtain the model without an instance id: GetModel(TenantModel).

TenantMember

Table tenant_members in dms-tenant. It holds one row per member of the tenant the handle is bound to.

FieldTypeNotes
_idstringMembership id.
userIdstringRelated to the User table of the Auth domain. Indexed across tenant instances.
roleIdsstring[]Related to Role, many. The roles whose grants make up the member's base permission set.
isTenantOwnerbooleanWhether the member owns the tenant.
inviteDeliveryIdstring, optionalTies this membership to the durable invite acceptance that created it.
joinedAtDateCreation time. Indexed across tenant instances.
invitedBystring | nullIndexed, related to User.

TenantMemberModel extends BasicDataModel(TenantMember, tenantMembersTableName):

MethodReturns
getByUser(userId)Promise<TenantMember | undefined>
existsByUser(userId)Promise<boolean>
listOwners()Promise<TenantMember[]>, the members with isTenantOwner set
listByUserWithTenantIds(userId)Promise<Array<{ tenantId: string; member: TenantMember }>>
getOldestByUser(userId)Promise<{ tenantId: string; member: TenantMember } | undefined>, the row with the earliest joinedAt
countOwnersExcluding(excludedUserIds)Promise<number>

listByUserWithTenantIds and getOldestByUser return the tenant each row came from. A lookup that spans tenant instances needs that id.

Role

Table roles in dms-tenant. It holds the roles of the tenant.

FieldTypeNotes
_idstringRole id, as referenced by TenantMember.roleIds.
createdAtDateCreation time, indexed.
updatedAtDateUpdate time, indexed.
namestringIndexed.
descriptionstring | null, optionalWhat the role is for, shown in the roles editor. Absent on older rows.
permissionsstring[]Granted permission ids (Permissions).

RoleModel extends BasicDataModel(Role, ROLES_TABLE_NAME) and adds getByName(name): Promise<Role | undefined>.

Resolve the request's tenant

getRequestTenantId(ctx) returns the tenant of the request's verified credential. The DMS binds that credential in the auth decorators (AuthUser, AuthRawUser, IfAuthUser with a valid token, AuthOwnerOnly, AuthUserWithPermission, and the auth a PageController installs), in the tenant guards (AuthTenantMember, AuthTenantOwner and authenticateTenantRequest), and in authenticateRequestUser. A guard that verifies a credential without a user binds it with bindVerifiedRequestIdentity. Without a verified credential, such as an anonymous request or an invalid or forged token, it returns DEFAULT_TENANT_ID. The DMS never reads a token's tenant before it checks the token's signature, user and session. When the request's authentication failed, or its Authorization header changed after authentication, getRequestTenantId throws HTTPResult(401).

typescript
import {
  Context,
  Controller,
  Get,
  type RequestContext,
} from "@antelopejs/interface-api";
import { AuthUser } from "@antelopejs/interface-dms/auth";
import { getRequestTenantId } from "@antelopejs/interface-dms/request-tenant";
import type { User } from "@antelopejs/interface-dms/auth/db";

export class WorkspaceController extends Controller("/api/workspace") {
  @Get("/current")
  async current(@AuthUser() _user: User, @Context() ctx: RequestContext) {
    return { tenantId: getRequestTenantId(ctx) };
  }
}

Call it in the handler, after the route's auth decorator ran. A parameter or property provider resolved alongside the auth decorator uses resolveRequestTenantId(ctx) instead. That async function waits for the tenant guards and credential checks the route's other providers start, and answers the tenant they verified. Without one, it verifies a bearer token itself and binds its tenant. A request without a verified credential reads as anonymous, and a credential verified on it later answers 401. TenantScopedModel uses it. A resolved tenant still authorizes nothing, so check membership and permissions for the operation.

Scope a model to the request's tenant

TenantScopedModel(ModelClass) is a parameter and property decorator. It injects GetModel(ModelClass, await resolveRequestTenantId(ctx)), which is the tenant of the verified credential, or DEFAULT_TENANT_ID without one.

typescript
import { Controller, Get } from "@antelopejs/interface-api";
import { AuthTenantMember } from "@antelopejs/interface-dms/guards";
import { RoleModel } from "@antelopejs/interface-dms/db";
import { TenantScopedModel } from "@antelopejs/interface-dms/tenant-scoped-model";
import type { User } from "@antelopejs/interface-dms/auth/db";

export class RoleController extends Controller("/api/roles") {
  @Get("/list")
  async list(
    @AuthTenantMember() _user: User,
    @TenantScopedModel(RoleModel) roles: RoleModel,
  ) {
    return roles.getAll();
  }
}

As a property decorator, it fills the @ModelReference() field of a data controller:

typescript
import { ModelReference } from "@antelopejs/interface-data-api/metadata";
import { RoleModel } from "@antelopejs/interface-dms/db";
import { TenantScopedModel } from "@antelopejs/interface-dms/tenant-scoped-model";

// inside a DataController subclass
@ModelReference()
@TenantScopedModel(RoleModel)
declare model: RoleModel;

Use it only for a model whose table lives in TENANT_SCHEMA_NAME or another schema with one instance per tenant. For a core-schema table, take the model without an instance id.

Tenant access gates

A gate is a binary check at tenant level. It decides whether the tenant may use the product at all, independently of any permission set. The DMS evaluates the gates at every tenant authorization point: permission guards, the tenant member and owner guards, table view data routes, page and menu visibility, and realtime page access.

typescript
import { RegisterTenantAccessGate } from "@antelopejs/interface-dms/tenant-access";

export async function construct(): Promise<void> {
  RegisterTenantAccessGate({
    id: "my_app.subscription-status",
    order: 100,
    gate: async (userId, tenantId) => {
      if (await tenantIsSuspended(tenantId)) {
        return { allowed: false, code: "my_app.errors.tenant_suspended" };
      }
      return { allowed: true };
    },
  });
}
typescript
type TenantAccessResult = { allowed: true } | { allowed: false; code: string };

type TenantAccessGateFn = (
  userId: string | undefined,
  tenantId: string,
) => Promise<TenantAccessResult> | TenantAccessResult;

TenantAccessGateInfo carries id, gate and order. The interface guarantees these semantics:

  • Gates run in ascending order, and ties run in registration order. The first denial wins, and its code reaches the client.
  • Registering an id a second time replaces the earlier gate. It does not add a second gate.
  • A gate that throws fails the request.
  • The registration is removed when the registering module unloads.
  • Register in construct(), so the gate is active before the API serves requests.
  • userId is undefined for an unauthenticated request.

Three functions evaluate the gates:

FunctionBehavior
CheckTenantAccess(userId, tenantId)Resolves to the first denial, or { allowed: true }.
AssertTenantAccess(userId, tenantId)Calls CheckTenantAccess and throws a 403 whose body is the code of the denying gate.
EvaluateTenantAccess(userId, tenantId)Server-side only. Resolves to every denial as TenantAccessDenial[] ({ gateId, code }), in gate order, and to [] when no gate denies. A gate that throws rejects the whole evaluation.
typescript
import {
  AssertTenantAccess,
  CheckTenantAccess,
} from "@antelopejs/interface-dms/tenant-access";

const access = await CheckTenantAccess(user._id, tenantId);
if (!access.allowed) {
  // access.code is a machine-readable key
}

await AssertTenantAccess(user._id, tenantId); // or let it throw

AuthTenantOwner and AuthTenantMember call AssertTenantAccess unless the route opts out with bypassTenantAccessGate (Permissions). A table view opts out with the option of the same name in TableViewOptions. Routes that must stay reachable for a denied tenant, such as billing or recovery, use these options.

EvaluateTenantAccess is for a module that must know whether another denial is in place, for example before it lifts its own hold. Identify gates by gateId, never by code, because two gates may share a code. The result is an observation. It is not an authorization receipt or an atomic snapshot of external state, so revalidate before you act on it.

A gate denies a tenant outright. To shape what the users of a tenant may do, use a permissions resolver.

Memberships and ownership

applyTenantOwnership(userModel, userId, tenantId, patch) adds the user to the tenant, or sets the roles and ownership of an existing member.

typescript
import { GetModel } from "@antelopejs/interface-database-decorators";
import { applyTenantOwnership } from "@antelopejs/interface-dms/tenant-ownership";
import { UserModel } from "@antelopejs/interface-dms/auth/db";

await applyTenantOwnership(GetModel(UserModel), userId, tenantId, {
  roleIds: ["role-editor"],
  isTenantOwner: false,
});

TenantMembershipPatch is the fourth argument:

FieldTypeDescription
roleIdsstring[]Roles the member holds after the write. Replaces the previous list.
isTenantOwnerbooleanOwnership flag after the write.
invitedBystring | null, optionalRecorded on insert. Ignored when the membership row already exists.
deliveryIdstring, optionalDurable invite delivery. It grants membership without replacing later edits.

applyTenantOwnership goes through changeTenantMembers, which fires Hook.MEMBER_BEING_CHANGED before any write, so a module can veto it. When the user is not a member yet, it also fires Hook.MEMBER_BEING_ADDED before the write and Hook.MEMBER_ADDED after it. For an existing member, it updates roleIds and isTenantOwner and fires neither of those two hooks (Hooks).

Two helpers keep the platform-owner flag on the user row aligned with tenant ownership:

FunctionSignature
syncPlatformOwnerOnTenantOwnerChange(userModel, userId, tenantId, nextIsTenantOwner: boolean) => Promise<void>
clearPlatformOwnerOnMemberRemoval(userModel, userId, tenantId, removedMemberWasTenantOwner: boolean) => Promise<void>

Both mirror the value onto User.owner. Both do nothing outside the default tenant, and nothing when the backend runs in SaaS mode, where User.owner means platform ownership. clearPlatformOwnerOnMemberRemoval also does nothing when the removed member was not a tenant owner. Call them after a write that changes ownership without applyTenantOwnership, which mirrors the flag itself.

RegisterSaasMode

By default, the owners of the default tenant are the platform owners. In SaaS mode the two are independent. Tenant owners are customers, and platform ownership is managed separately. The SaaS module declares the mode itself with RegisterSaasMode. The DMS never infers it from the modules it finds loaded.

typescript
import { RegisterSaasMode } from "@antelopejs/interface-dms/utils/saas-mode";

export async function construct(): Promise<void> {
  RegisterSaasMode();
}

While SaaS mode is on:

  • applyTenantOwnership and the two helpers above no longer mirror the default tenant's owner flag onto User.owner.
  • Removing members from the default tenant no longer refuses to remove the last platform owner.

The registration is removed when the registering module unloads. The mode stays on while at least one registration is active. isSaasMode() resolves to the current state, and to false until a module registers. Both behaviors read the mode on every request, so the SaaS module may register before or after the DMS starts.

Tenant lifecycle admission

Membership and invite producers coordinate with tenant deletion through @antelopejs/interface-dms/tenant-lifecycle. This contract orders writes against deletion. It is not an authorization check or a transaction, so authorize the caller separately.

changeTenantMembers

Every insert, update or delete of a TenantMemberModel or UserInviteModel row goes through one entry point, changeTenantMembers from @antelopejs/interface-dms/tenant-members. The DMS uses it for every membership and invitation write it makes:

  • adding a member;
  • changing a member's roles or ownership, from the members table or the owner route;
  • removing a member, and moving the holders of a deleted role;
  • leaving each tenant when an account is deleted;
  • creating, editing, resending, cancelling, expiring and accepting invitations.

A module that writes these rows itself must use it too. There is no other supported write path. A raw GetModel(...).insert, update or delete on these rows skips both the barrier and the policy hook.

typescript
changeTenantMembers<T>(
  tenantId: string,
  plan: () => Promise<TenantMembersWrite<T>>,
): Promise<T>

interface TenantMembersWrite<T> {
  changes: MemberChange[];
  write: () => Promise<T>;
}

It runs these steps in order:

  1. runTenantLifecycleOperation(tenantId, ...). While a barrier is held, or once admission is closed, the call is refused at once, before anything is read.
  2. plan(), inside the admission. It reads the current rows and describes the change.
  3. Hook.MEMBER_BEING_CHANGED, once per MemberChange, with { tenantId, ...change }. A throwing handler refuses the write, and that includes replays of an invitation acceptance.
  4. write(). The admission is then released as runTenantLifecycleOperation describes.

A MemberChange has a kind:

kindFieldsWhen
addeduserId, isTenantOwner, roleIds, deliveryId?A user joins by direct add, or by an accepted invitation (deliveryId set).
removeduserId, isTenantOwnerA member is removed, or leaves by deleting their account.
rolesuserId, roleIds, previousRoleIdsA member's roles change, including when a deleted role is reassigned.
ownershipuserId, isTenantOwner, previousIsTenantOwnerA member is given or loses the owner role.

One edit that sets both roles and ownership announces two changes. A write that changes no membership, such as an invitation created, edited or retired, passes changes: []. The write is still admitted, and invitation creation keeps its own Hook.INVITE_BEING_CREATED. Do not call changeTenantMembers from inside another changeTenantMembers or runTenantLifecycleOperation callback, because each call takes its own admission.

Deleting an account makes one call per tenant the user belongs to, one after the other. A tenant that holds a barrier refuses its call, and the deletion stops there. The account and its remaining memberships stay, and the user can retry once the barrier is released.

runTenantLifecycleOperation

runTenantLifecycleOperation<T>(tenantId: string, work: () => Promise<T>): Promise<T> admits one invocation, calls work, then releases that admission and returns the result. Closed admission rejects without running work. Membership and invitation writes use it through changeTenantMembers. Call it directly only for other work that must coordinate with tenant deletion. That work must await every effect and start no detached writer.

A successful callback releases its admission. A deliberate refusal, an HTTPResult with a 4xx status, also releases its admission and rethrows the original refusal. The release is tried three times, 200 ms and then 400 ms apart, so a short database outage does not block the tenant. If every try fails, the admission stays, the module logs an error that names the tenant and the attempt, and the call rejects. After a refusal it rejects with an AggregateError of the refusal and a TenantLifecycleReleaseError. After a success it rejects with the TenantLifecycleReleaseError. Any other failure retains the admission, because its effects may be indeterminate. A retry is a new invocation and never retires the identity of the failed one. There is no automatic expiry. An operator retires an admission with releaseTenantLifecycleAttempt.

TenantLifecycleReleaseError fieldValue
tenantIdThe tenant whose deletion stays blocked.
attemptIdThe admission that stays, as observeTenantLifecycle lists it in activeAttemptIds.
causeThe failure of the last release try.

Pausing admission

A module that must validate a tenant's inventory with no membership writer in flight, such as a plan downgrade, pauses admission instead of closing it:

FunctionBehavior
observeTenantLifecycle(tenantId)Resolves to a TenantLifecycleObservation: { revision, barrierId, activeAttemptIds, closed }. Never retires an attempt.
pauseTenantLifecycleAdmission(tenantId, barrierId, expectedRevision)Publishes the barrier with one compare-and-set on expectedRevision. Resolves false when the revision moved, a barrier is held, or admission is closed.
resumeTenantLifecycleAdmission(tenantId, barrierId)Releases this barrier. With no barrier held, it invalidates the revision so that a delayed pause fails. Resolves false for the barrier of another owner or for closed admission.

While a barrier is held, runTenantLifecycleOperation rejects new work without running it, with an HTTPResult 409 ($dms.refusals.tenant.admission_paused). The refusal writes nothing and retains no admission, and the caller may retry once the barrier is released. Admitted work keeps running.

Follow this order:

  1. Observe the revision before you check your own business intent.
  2. Pause with that revision.
  3. Check the intent again. If you abandon it, resume.
  4. Wait for an observation with no active attempt, then validate.

A false from pause needs a new observation, not a blind retry. Use a unique barrierId for each phase. Do not observe or pause from inside a runTenantLifecycleOperation callback, because the caller would wait for itself.

closeTenantLifecycleAdmission

closeTenantLifecycleAdmission(tenantId: string): Promise<void> closes admission permanently, then checks that no admitted operation remains. It rejects if work is active or indeterminate, or if the database cannot confirm the transition. A rejection can leave admission closed. It never authorizes deletion or reopening.

Call it before any destructive tenant phase, including deletion hooks. Do not delete business data when closure rejects. Preserve the tenant_lifecycle and invite_resolutions safety rows after deletion, because dropping the tenant schema or recreating those rows can reopen admission. Writers on mixed versions, and raw model writes that bypass admission, prevent a safe rollout. These table names describe what to preserve. They are not supported raw-model APIs.

The backend services guide shows where closure fits in a module's deletion flow.

Unblocking a deletion

releaseTenantLifecycleAttempt(tenantId: string, attemptId: string): Promise<boolean> retires one admission by hand. It is the operator path for a tenant whose closeTenantLifecycleAdmission keeps rejecting. It resolves true when it retired the admission. It resolves false, and writes nothing, when the tenant holds no such admission: the attempt was already retired, or the tenant or attempt id is wrong. Calling it again is safe.

Retire only an attempt whose effects you know are over:

  • An attempt that a TenantLifecycleReleaseError names finished or refused, so none of its effects is in flight. Retire it once the database answers again. The error and the log line give both ids.
  • Any other attempt that observeTenantLifecycle lists failed with effects that may be indeterminate. Retire it only after you have confirmed that its work left no write in flight, because the deletion can then overtake that write.

Call it from an operator script or a one-off task, never from a runTenantLifecycleOperation callback or on a timer. Then call closeTenantLifecycleAdmission again.

typescript
import {
  TenantLifecycleReleaseError,
  closeTenantLifecycleAdmission,
  releaseTenantLifecycleAttempt,
} from "@antelopejs/interface-dms/tenant-lifecycle";

export async function unblockDeletion(
  releaseFailure: TenantLifecycleReleaseError,
): Promise<void> {
  const retired = await releaseTenantLifecycleAttempt(
    releaseFailure.tenantId,
    releaseFailure.attemptId,
  );
  if (!retired) {
    throw new Error(`No admission ${releaseFailure.attemptId} to retire`);
  }
  await closeTenantLifecycleAdmission(releaseFailure.tenantId);
}

Built-in data controllers

The interface ships the two data controllers behind the built-in settings screens. The DMS module registers both itself, so their routes exist as soon as it is loaded. Reference them, and do not register them again.

ExportImport fromTableBase path
memberSettingDataAPI@antelopejs/interface-dms/data-controllersTenantMember/api/tables/members
roleSettingDataAPI@antelopejs/interface-dms/data-controllers/rolesRole/api/tables/roles

The /data-controllers barrel re-exports the members controller only. Import the roles controller from its own path.

typescript
import { roleSettingDataAPI } from "@antelopejs/interface-dms/data-controllers/roles";
import { DefaultDataTypes } from "@antelopejs/interface-dms/base/data-types/default-types";

// a role picker on one of your own form fields
const reviewerRolesField = {
  id: "reviewerRoleIds",
  label: "Reviewer roles",
  type: new DefaultDataTypes.RelationType({
    multiple: true,
    dataApiController: roleSettingDataAPI,
    keyMapping: { label: "name", value: "_id" },
  }),
};

Both bind their model with TenantScopedModel, so they read and write the request's tenant.

  • memberSettingDataAPI exposes _id, userId, the member's name, email, avatar, isValidated, lastActiveAt and twoFactorMethods joined from the User table, the member's roleIds as a plain relation onto roleSettingDataAPI, isTenantOwner, and joinedAt. The DMS members page draws the roles with its own role picker, through the component slot of the edit form. The controller mounts every default table route except new, archive and restore.
  • roleSettingDataAPI exposes _id, name, permissions, createdAt and updatedAt, with every default table route.

Reference either controller as the relation target of your own columns when you need a member or role picker, or pass one to a TableView to render it.

Next steps

Invites covers bringing a user into a tenant that has no membership row for them yet.