@aiquants/authz-core
v0.6.1
Published
Transport- and DB-agnostic RBAC authorization core: action/scope types (zod), scope merge/eval, and a DI guard factory.
Readme
@aiquants/authz-core
Transport- and DB-agnostic RBAC authorization core: action/scope types (zod), scope merge/eval, and a DI guard factory. No DB or framework dependency — pair it with a DB adapter and a framework adapter.
(user → role) × (resource × action) × (row / column scope) — answer "can this user do this action on this resource, and over which rows/columns?". This package owns the rules (the §-contract below); adapters translate the result into SQL and HTTP.
Ecosystem
This is the contract layer. To build a working authorization setup you also need a DB adapter (resolves a user's grants from your database and applies scope to queries) and a framework adapter (guards your endpoints).
| Layer | TypeScript | Python | Go |
| :--- | :--- | :--- | :--- |
| Contract (this) | @aiquants/authz-core | aiquants-authz-core | github.com/aiquants/authz |
| DB adapter (mssql) | @aiquants/authz-drizzle | aiquants-authz-sqlalchemy | …/authz/authzsql |
| Framework adapter | @aiquants/authz-react-router | aiquants-authz-fastapi | …/authz/authzhttp |
All three languages implement the identical row / column scope contract (same boundary tests). The required database schema (DDL) and a copy-paste bootstrap (seed) ship in the DB-adapter README (@aiquants/authz-drizzle). A full zero → guarded endpoint walkthrough ships in the framework-adapter README (@aiquants/authz-react-router).
For details on system-reserved roles (@authenticated and @anonymous), validation constraints, and database seeding, refer to the Reserved Roles User Guide.
Install
Inside this monorepo it is already wired as a pnpm workspace package — depend on it with the workspace:* protocol:
// consumer package.json
"dependencies": { "@aiquants/authz-core": "workspace:*" }External projects:
pnpm add @aiquants/authz-core zod # peer: zod ^3.25zod is a peer dependency (provide it in the host app). Build / test from the package dir:
pnpm run build # tsup → dist (ESM + CJS + d.ts)
pnpm run test # vitestPublishing is gated by prepublishOnly (clean → typecheck → test → build); cut a release with pnpm run publish:patch|minor|major (npm, --access public).
Quick start (just the core)
The core has no DB — you supply four functions: how to resolve the tenant and the user id from your request context, how to prove the caller may act as that tenant, and how to load that user's grants. The DB adapter normally provides the last one; here it is inlined to show the shape.
import { buildEffectivePermission, createRequirePermission } from "@aiquants/authz-core"
type Ctx = { tenantId: string; userId: number | null }
const requirePermission = createRequirePermission<Ctx, number>({
resolveTenantId: async (ctx) => ctx.tenantId, // blank → AuthzTenantError (never "all tenants")
resolveUserId: async (ctx) => ctx.userId ?? null, // null → anonymous, then denied (unresolved-user)
// may this caller act AS that tenant? REQUIRED, and never `() => true`: resolving a tenant only
// says WHICH tenant was named, and that name comes from a channel the client can influence.
assertTenantMembership: async ({ userId, tenantId }) => isMemberOf(userId, tenantId),
getEffectivePermissions: async ({ userId, tenantId }) =>
// normally: getEffectivePermissions(db, tables, {...}) (DB adapter)
buildEffectivePermission(userId, [
// tenantId is the grant row's OWN tenant, projected from the DB — not an echo of the argument
{ tenantId, action: "read", rowScope: '{"filters":[{"field":"dept","op":"in","values":["A"]}]}', columnScope: null },
], tenantId),
})
// in a handler (ctx is your transport context — here `{ tenantId, userId }`):
const { userId, tenantId, scope, effectivePermission } = await requirePermission(ctx, { appKey: "myapp", resourceKey: "report", action: "read" })
// allowed → apply scope.rowScope as a WHERE and scope.columnScope as a column mask (DB adapter),
// always together with the tenant predicate for the same tenantId.
// `effectivePermission` is the permission the decision was made from — describe it to a UI
// instead of loading it again, so the guard and what you show can never disagree.
// denied → AuthzDeniedError (map to HTTP 403).
// reason: "unresolved-user" | "no-permission" | "tenant-mismatch" | "not-a-tenant-member".Tenant contract
tenantId is a required, non-empty string on every tenant-scoped surface — parameters, DTOs and
EffectivePermission alike. There is no optional marker and no default:
- A missing / blank tenant is an error (
AuthzTenantError,kind: "invalid-tenant"), never "no filter" or "every tenant". That inversion is what turns a scoping bug into a cross-tenant leak. - Comparison is exact — no trimming, no case folding.
Tenant-Aandtenant-aare different tenants. buildEffectivePermissionproves every grant row belongs to the requested tenant and throwsAuthzTenantError(kind: "tenant-mismatch") otherwise, so a foreign row can never widen a result.- The guard verifies the permission it received was issued for the requested tenant and denies
(
reason: "tenant-mismatch") when it was not; it never stamps the requested tenant onto a foreign permission. - Helpers:
isTenantId,assertTenantId,isSameTenant,assertTenantMatch,AuthzTenantError.
Model
(user → role) × (resource × action) × (row / column scope)
- action ∈
read | create | update | delete(write= create ∪ update, derived, never stored). - row_scope / column_scope:
NULL= all rows / all columns; non-NULL = partial. - fail-close: unparseable / unresolved / unknown ⇒ deny (least privilege).
Scope contract (canonical)
// row_scope (NULL = all rows). filters are AND'd within one role.
{ "filters": [ { "field": "dept", "op": "in", "values": ["A","B"] } ] }
// column_scope (NULL = all columns)
{ "mode": "allow", "columns": ["amount","unit_price"] }op ∈ in | notIn | eq | ne. A null in values maps to IS NULL / IS NOT NULL on the SQL side.
Merge (multiple roles = UNION = wider)
- row → disjunction (DNF)
{ anyOf: RowScope[] }. Three canonical values (⚠️ fail-close):null= all rows ·{anyOf:[...]}= OR of groups ·{anyOf:[]}= NO rows (SQLWHERE 1=0).nulland{anyOf:[]}are opposites — never conflate them.- ⚠️ Prohibition of Nullish Coalescing (
??) fallbacks: Never usescope?.rowScope ?? { anyOf: [] }or similar coalescing. Becausenull(all rows) is a valid truthy value representing unrestricted access,??will incorrectly override it to{ anyOf: [] }(deny all), turning full access into zero access. Instead, check the existence of thescopeobject itself using ternary or explicit checks:scope ? scope.rowScope : { anyOf: [] }.
- column → normalized to deny form (no column universe needed):
allow A ∪ allow B = allow(A∪B)·NULL ∪ x = NULL·deny D1 ∪ deny D2 = deny(D1∩D2)·allow A ∪ deny D = deny(D∖A).
API
parseRowScope,parseColumnScope,parseActionScopemergeRowScopes,mergeColumnScopes,mergeScopes,buildEffectivePermission(userId, grants, tenantId)isColumnAllowed,can,canWriteisTenantId,assertTenantId,isSameTenant,assertTenantMatch,AuthzTenantError— the tenant contract.createRequirePermission({ resolveTenantId, resolveUserId, assertTenantMembership, getEffectivePermissions, onDeny })→requirePermission(ctx, { appKey, resourceKey, action })returns{ userId, tenantId, scope, effectivePermission }on allow (so callers can apply row WHERE / column mask and render the same decision without a second lookup); defaultonDenythrowsAuthzDeniedError(403).assertTenantMembershipis required (a missing port throwsTypeErrorat factory time) and runs before the permission is loaded —falsedenies withnot-a-tenant-member.wouldRemoveLastAdmin(rows, removal, tenantId)/tenantsLosingLastAdmin(rows, removal)/applyRemoval/fullAdmins— the lockout guard's pure logic (see below).@aiquants/authz-core/testing:makeEffectivePermission,makeMergedScopefixtures.
Lockout guard (last administrator)
An administrator is a user holding all four actions on the admin resource. wouldRemoveLastAdmin(rows, removal, tenantId) decides whether a destructive change would leave that tenant with zero administrators (it returns false when the tenant already has none, so recovery is never blocked).
tenantsLosingLastAdmin(rows, removal) answers the same question for every tenant present in rows and returns the offending ids. Use it for a removal that is not tenant-scoped by construction — above all deactivateUserId, since the host's user table carries no tenant and deactivating a user removes that user's admin paths in every tenant at once. Asking only about the acting tenant passes while another tenant is silently left with none. A tenant-scoped removal is unaffected: role / grant / group ids are globally unique, so its rows can only match inside their own tenant.
The evaluation is always tenant-scoped: the third argument is required, and every AdminGrantRow must carry its own real tenantId — a tenant-less row raises instead of quietly dropping out of the scoped set (which used to read as "no administrators here" and let the last one be deleted).
Permissions can be held through two paths, and AdminGrantRow.groupId records which: null = granted directly to the user, a number = granted via that group. The same (user, role) reached through both paths is passed as two rows — collapsing them would make one-sided removals undecidable.
AdminRemoval describes exactly one destructive change, and each variant strips only its own path:
| Variant | Removes |
| --- | --- |
| removeRoleId | every row for that role (either path) |
| removeAssignment: {userId, roleId} | the direct rows only |
| removeGroupAssignment: {groupId, roleId} | that group's rows, for all its members |
| removeGroupMembership: {groupId, userId} | that user's rows from that group |
| removeGroupId | every row from that group |
| deactivateUserId | every row for that user (both paths) |
removeAssignment deliberately spares group-derived rows: revoking a direct grant from someone who also holds the role through a group is safe, and treating it as unsafe would block a legitimate change.
Group support in the admin store port
AuthzAdminStore adds listGroups / listGroupRoles / assignGroupRole / removeGroupRole. The port knows only a groupId plus display-only groupKey / groupName / tenantId — group membership is an identity concern and lives outside this package.
Every port method — reads, writes and the destructive guardedWrite(tenantId, removal, op, write) — takes tenantId as its first argument. Payloads that carry a tenant-unique key or a cross-row reference (RoleInput, RoleUpdate, ResourceInput, GrantInput) also name the tenant they target; an implementation must verify that claim against the operation's tenantId with assertTenantMatch and reject a mismatch instead of preferring either side.
Next steps
- Create the database tables — see DDL in
@aiquants/authz-drizzle(oraiquants-authz-sqlalchemy). - Wire
getEffectivePermissions+ scope application — see the DB adapter README. - Guard your endpoints + bootstrap an initial admin — see the full walkthrough in
@aiquants/authz-react-router(TS) /aiquants-authz-fastapi(Python) /…/authz/authzhttp(Go).
MIT
