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

Permissions

Permission ids are dot-separated strings built from the page tree. The registry, the permission computation, the resolvers that reshape a set, and the route guards that check it.

A permission id is a dot-separated string built from the page tree: a page's fullId, then every component id in the position's path, then the action id when there is one. A role holds a flat list of granted ids, and a platform owner, a user flagged owner, holds the wildcard *. GetUserPermissions returns the base set a user's roles grant, without *: a role that lists it grants nothing through it. GetEffectiveUserPermissions runs that set through the registered resolvers, and every authorization surface uses the effective set.

The API spans three subpaths:

SubpathContains
@antelopejs/interface-dms/permissionsThe registry, the module-scope marks, and the permission computation
@antelopejs/interface-dms/permissions-resolverRegistering and running resolvers
@antelopejs/interface-dms/guardsRoute guards

Register a permission

Pages, components and actions register their own permissions when the page registers (Pages and modules). Register a standalone permission for a capability that has no component behind it:

typescript
import { RegisterPermission } from "@antelopejs/interface-dms/permissions";

RegisterPermission("reports.export", {
  id: "reports.export",
  title: "$my_app.perm.reports_export",
  icon: "i-ph-download",
  description: "$my_app.perm.reports_export_description",
  dependencies: ["reports.view"],
  defaultGranted: false,
});

RegisterPermission(id, permission) takes the id twice, once as the registry key and once inside the record. Keep the two equal.

Permission

FieldTypeDescription
idstringThe permission id. Required.
titlestringLabel shown in the roles editor. Required.
iconstringIcon name.
descriptionstringLonger description.
dependenciesstring[]Permission ids this one needs to be of any use. The roles editor grants them with it and removes it with them, and a role is saved with them and the ids they sit under. HasPermission requires each registered dependency, so a missing one makes the permission count for nothing. An unregistered dependency counts as held.
defaultGrantedbooleanTreats the permission as held by every caller, without a role grant.

A table view's actions declare their own dependencies. edit and export need view. Every action reached only from the rows needs list: delete, archive, viewArchived, export, and add, edit and view when their form opens over the table. restore needs viewArchived. A form that opens as its own page, and select, need no list.

UnregisterPermission(id) drops a permission from the grantable tree. It serves registrations undone while the process keeps running, such as a page extension whose module stopped. A permission left behind after its surface is gone stays offered in the roles editor and stays grantable, so code that registers a permission under a condition unregisters it under the same condition.

Read the registry

typescript
import {
  GetPermission,
  GetPermissions,
} from "@antelopejs/interface-dms/permissions";

const permission = await GetPermission("reports.export");
const tree = await GetPermissions();

GetPermission(id) resolves to the Permission or undefined. GetPermissions() resolves to a Record<string, PermissionTree> keyed by the first id segment:

typescript
type PermissionTree = {
  data?: Permission;
  children: Record<string, PermissionTree>;
};

Each level keys its children by the next dot-separated segment. data is absent on a level that exists only to hold children.

Both are interface functions, so they return promises even though the registry is in the same process.

Compute a user's permissions

typescript
import {
  GetEffectiveUserPermissions,
  GetUserPermissions,
  GrantsEveryPermission,
  HasAnyPermission,
  HasPermission,
} from "@antelopejs/interface-dms/permissions";
FunctionSignature
GetUserPermissions(user: { owner?: boolean }, roleIds: string[], roleModel: RoleModel) => Promise<Set<string>>
GetEffectiveUserPermissions(user: { _id: string; owner?: boolean }, tenantId: string, roleIds: string[], roleModel: RoleModel, context?: PermissionsResolverContext) => Promise<Set<string>>
HasPermission(permissions: Set<string>, permissionId: string) => Promise<boolean>
HasAnyPermission(permissions: Set<string>, permissionIds: string[]) => Promise<boolean>
GrantsEveryPermission(permissions: ReadonlySet<string>) => boolean

GetUserPermissions returns Set(["*"]) for a user with owner: true, an empty set when roleIds is empty, and otherwise the union of the permissions arrays of the roles it loads through roleModel. That is the base set. It ignores resolvers, so never authorize against it.

GetEffectiveUserPermissions passes the base set through ApplyPermissionsResolvers, with context (default {}) handed to each resolver. Every authorization surface uses this set: route guards, page and menu visibility, table view action checks and search.

HasPermission checks in this order:

  1. true when the set holds the wildcard *.
  2. false when the id is module-scoped.
  3. true when the registered permission carries defaultGranted.
  4. false when the set does not hold the id.
  5. false when the set lacks an id the permission sits under (pages.sales and pages for pages.sales.orders). An id above it that is not a registered permission, or that carries defaultGranted, counts as held.
  6. false when a registered dependency fails the same check. Otherwise true.

The wildcard comes first, so a platform owner passes even for a module-scoped id. Step 5 makes a grant worthless without its parents: a role that holds neither a table nor its page is refused the table's delete action. The roles editor and the role routes store each grant with every id above it, so only an older saved role, or a set a resolver reshaped, can miss one.

HasAnyPermission returns true when HasPermission passes for at least one of the ids.

GrantsEveryPermission returns true when the set holds the wildcard *, the test of step 1. Call it where no single id is at stake, such as an action that declares no permission or a resolver that leaves the platform owner's set alone. Read the wildcard through it rather than with permissions.has("*").

typescript
import { GetModel } from "@antelopejs/interface-database-decorators";
import {
  RoleModel,
  TenantMemberModel,
} from "@antelopejs/interface-dms/db";
import {
  GetEffectiveUserPermissions,
  HasPermission,
} from "@antelopejs/interface-dms/permissions";
import type { User } from "@antelopejs/interface-dms/auth/db";

async function canExport(user: User, tenantId: string): Promise<boolean> {
  const member = await GetModel(TenantMemberModel, tenantId).getByUser(user._id);
  const permissions = await GetEffectiveUserPermissions(
    user,
    tenantId,
    member?.roleIds ?? [],
    GetModel(RoleModel, tenantId),
  );
  return HasPermission(permissions, "reports.export");
}

RoleModel and TenantMemberModel are described in Tenancy.

Module-scoped permissions

The permissions of a module page or category never enter the grantable permission tree, and a role grant on such an id grants nothing. The ids are marked instead:

typescript
import {
  IsModuleScopedPermission,
  MarkModuleScopedPermission,
  UnmarkModuleScopedPermission,
} from "@antelopejs/interface-dms/permissions";

MarkModuleScopedPermission("modules.automation.builder");
const scoped = IsModuleScopedPermission("modules.automation.builder.canvas.add");
UnmarkModuleScopedPermission("modules.automation.builder");

IsModuleScopedPermission(id) checks the id and each id above it, one dot-separated segment at a time, so marking a page id also covers every component and action id derived from it. In the example, scoped is true. UnmarkModuleScopedPermission(id) removes the mark for that exact id only.

Page and category registration calls MarkModuleScopedPermission whenever isOwnerOnly holds: the entry is inside a module or declares ownerOnly (Modules and dynamic menus). Call it directly only for ids you build outside that path.

Reshape the effective set

A permissions resolver receives a caller's current permission set for a tenant and returns the set to use instead.

typescript
import { RegisterPermissionsResolver } from "@antelopejs/interface-dms/permissions-resolver";

export async function construct(): Promise<void> {
  RegisterPermissionsResolver({
    id: "my_app.plan-limits",
    order: 100,
    resolver: async (userId, tenantId, currentPermissions) => {
      const allowed = await loadPlanPermissions(tenantId);
      return new Set([...currentPermissions].filter((p) => allowed.has(p)));
    },
  });
}
typescript
type PermissionsResolverFn = (
  userId: string,
  tenantId: string,
  currentPermissions: Set<string>,
  context: PermissionsResolverContext,
) => Promise<Set<string>> | Set<string>;

interface PermissionsResolverContext {
  preview?: PermissionsResolverPreview;
}

interface PermissionsResolverPreview {
  rolePermissions: ReadonlySet<string>;
}

PermissionsResolverInfo carries id, resolver and order. context.preview is set when the call previews a role instead of computing a member's set, and rolePermissions holds the previewed role's permissions before any resolver reshaped them.

The interface guarantees these semantics:

  • Resolvers run in ascending order, each one receiving the previous one's result. Equal order runs in registration order, which is module load order.
  • Registering an id twice replaces the earlier resolver in its slot instead of adding a second one.
  • A resolver that throws aborts the computation and fails the request. It is never skipped.
  • The registration is removed when the registering module unloads. There is no unregister call.
  • Register in construct(), so the resolver is active before the API serves requests.

ApplyPermissionsResolvers(userId, tenantId, basePermissions, context) runs the pipeline, hands context to every resolver, and resolves to the effective set. GetEffectiveUserPermissions computes the base set and calls it, so prefer that function.

A resolver shapes a permission set. It cannot deny a surface that consults no permission set, and it cannot revoke a defaultGranted permission, which HasPermission grants after the resolvers ran. To cut a tenant off from the product entirely, register a tenant access gate instead (Tenancy).

Role previews

Preview as role in the roles editor runs the resolvers too, over the previewed role's set, and sets context.preview. The userId of such a call is the person previewing. A resolver that grants or withholds by the user's standing, such as handing an owner every permission of the plan or keeping a screen for owners, checks the flag and shapes the set as for an ordinary member holding only that role:

typescript
RegisterPermissionsResolver({
  id: "my_app.plan-limits",
  order: 100,
  resolver: async (userId, tenantId, currentPermissions, context) => {
    const allowed = await loadPlanPermissions(tenantId);
    if (!context.preview && (await isWorkspaceOwner(userId, tenantId))) {
      return allowed;
    }
    return new Set([...currentPermissions].filter((p) => allowed.has(p)));
  },
});

The DMS always passes context, and passes {} outside a preview.

Guard a route

Three decorators from @antelopejs/interface-dms/guards gate a route on the caller.

AuthUserWithPermission

AuthUserWithPermission(target, options?) requires an authenticated user who holds the registered permission of target. target is a Component, a child position, a page controller class, or an Action (Components). A child component resolves to its full positional path. options is a TenantGuardOptions.

typescript
import { Controller, Get } from "@antelopejs/interface-api";
import { AuthUserWithPermission } from "@antelopejs/interface-dms/guards";
import type { User } from "@antelopejs/interface-dms/auth/db";
import { InvoicesPage } from "../pages/invoices";

export class InvoiceReportController extends Controller("/api/invoices") {
  @Get("/summary")
  async summary(@AuthUserWithPermission(InvoicesPage) user: User) {
    return { requestedBy: user._id };
  }
}

The guard runs these steps:

  1. It authenticates the token. A request without a valid user fails authentication.
  2. When the token carries a tenant claim, it runs the tenant access gate, unless options.bypassTenantAccessGate is set.
  3. It resolves the target's permission id. A target with no permission id passes with the authenticated user.
  4. When the token carries no tenant claim, it answers 403, because a permission is granted only inside a tenant.
  5. It loads the caller's membership in that tenant, computes the effective permissions and calls HasPermission. A missing permission answers 403 with $dms.refusals.permissions.missing_permission and the missing permission id as its permissionId param.

bypassTenantAccessGate skips step 2 and keeps the permission check.

AuthTenantOwner and AuthTenantMember

AuthTenantMember(options?) requires a member of the request's tenant. AuthTenantOwner(options?) also requires isTenantOwner on that membership. The tenant comes from the verified credential: the JWT's tenantId claim, or DEFAULT_TENANT_ID ("default") when the claim is empty. Each guard answers 401 without a valid token and 403 when the requirement fails, with the body error.tenant_member_required or error.tenant_owner_required. Each then runs the tenant access gate before it returns the user.

typescript
import { Controller, Post } from "@antelopejs/interface-api";
import {
  AuthTenantMember,
  AuthTenantOwner,
} from "@antelopejs/interface-dms/guards";
import type { User } from "@antelopejs/interface-dms/auth/db";

export class BillingController extends Controller("/api/billing") {
  @Post("/portal-session")
  async portalSession(
    @AuthTenantOwner({ bypassTenantAccessGate: true }) user: User,
  ) {
    return { owner: user._id };
  }

  @Post("/usage")
  async usage(@AuthTenantMember() user: User) {
    return { member: user._id };
  }
}

The portal route stays reachable for a tenant that a gate denies. The usage route admits any member of the request's tenant.

TenantGuardOptions has one field, and all three guards accept it:

OptionTypeDescription
bypassTenantAccessGatebooleanSkips the tenant access gate for this route. Reserved for routes that must stay reachable when a gate denies the tenant, such as billing status, a payment portal or invoices.

The two tenant guards accept TenantRequestGuardOptions, which extends it:

OptionTypeDescription
authenticatorsreadonly RequestAuthenticator[]Credential handlers this route accepts before the JWT fallback. The handler whose recognizes(token) returns true authenticates the request. Two handlers that recognize the same token answer 401.
requireOwnerbooleanRequires tenant ownership, not platform ownership. AuthTenantOwner sets it.

RequestAuthenticator comes from @antelopejs/interface-dms/auth (Authentication).

authenticateTenantRequest(ctx, options?) runs the same check as a function and resolves to the User. It authenticates the credential again, and checks membership and the tenant gate, on every call, so a long-lived request can call it repeatedly. Product permissions stay the caller's job.

The opt-out has two mirrors for the surfaces a route guard does not cover. MenuOptions.bypassTenantAccessGate keeps a page and its menu entry reachable (Pages and modules). TableViewOptions.bypassTenantAccessGate covers a table view's data routes, which belong to a controller and not to any one page.

A denial from a gate answers 403 with the gate's code as its body (Tenancy).

Guards as properties

All three guards are parameter and property decorators. Declared as a class property, a guard gates every route on that controller:

typescript
import { Controller, Post } from "@antelopejs/interface-api";
import { AuthTenantMember } from "@antelopejs/interface-dms/guards";
import type { User } from "@antelopejs/interface-dms/auth/db";

export class FilesController extends Controller("/api/files") {
  @AuthTenantMember()
  declare user: User;

  @Post("/presign")
  async presign(): Promise<{ ok: true }> {
    return { ok: true };
  }
}

The property provider runs on every request to a route of the controller, whether or not the handler reads the property. The presign route above never reads this.user, and the guard still runs. That makes the property form a guard: removing the read does not remove the check.

Next steps

Tenancy covers the tenant the guards resolve, the roles the permission sets come from, and the access gates.