Skip to main content

archenstack-rbac-web

The front-end half of Archenstack: a tiny, framework-agnostic TypeScript library for consuming the permission matrix in your web apps. No UI-framework dependency, no runtime dependencies, and it ships its own types.

It has two faces:

  • a consumer facade — Permissions (check permissions in your UI from a /me/ payload), RbacClient (a typed fetch client), and MatrixEditor (headless admin-grid state); and
  • a resolving core — the same spec-conformant engine every Archenstack core ships (decide, evalScope, validate, canonicalJson, policy IO), so a client holding a snapshot can resolve levels locally with no round-trip.

This library speaks wire_version 1.

Install​

npm install @archenstack/rbac-web

Point npm at Archenstack's package registry first — see Installation. Working on the library itself? Build it from a checkout: npm install && npm run build (tsup → dist/: ESM + CJS + .d.ts); npm test runs node:test.

Check permissions from the current user​

import { RbacClient } from "@archenstack/rbac-web";

const client = new RbacClient({
baseUrl: "https://api.example.com/api/v1",
token: () => localStorage.getItem("access"), // string | getter | omit
});

const perms = await client.myPermissions(); // a Permissions object
perms.canRead("reports.view"); // show the nav item?
perms.canWrite("reports.export"); // enable the export button?
perms.level("billing.manage"); // 0–3 if you need the raw level

Permissions treats unknown features as no-access, so probing is always safe.

Multi-tenancy: withOrg

Against a multi-tenant backend, a single-org user needs no client change — the server resolves the org from their claim. A cross-org admin pins a client to a specific tenant with client.withOrg("acme"), a scoped clone that sends the X-Archenstack-Org header on every request (paths stay identical). List targetable orgs with client.listOrgs(). See Wiring multi-tenancy.

Check permissions in a React tree​

When you want the UI to react as permissions load, wrap the tree in one provider (it owns a single /me/ fetch) and check declaratively with the <Can> component and the useCan hook:

import { RbacProvider, useCan, Can } from "@archenstack/rbac-web/react";

<RbacProvider client={client}>
{/* Hide unless allowed */}
<Can feature="reports.export" need="write">
<ExportButton />
</Can>

{/* Or disable-with-reason — a function child owns HOW to disable */}
<Can feature="records.edit" need="write">
{(d) => <EditButton disabled={!d.allowed} title={d.allowed ? "" : "You can't edit records"} />}
</Can>
</RbacProvider>;

// The hook form, anywhere below the provider:
const canExport = useCan("reports.export", "write"); // "read" | "write" | "full" | a level

Object-level (row) access goes to the server via <CanObject> / useCanObjects. The full treatment — filtered nav, the security model, and batched object checks — lives in checking permissions in your own UI.

Build an admin editor (headless)​

MatrixEditor owns the grid state — dirty tracking and the exact PUT payload — so any view layer just renders and forwards changes:

import { RbacClient, MatrixEditor, LEVELS } from "@archenstack/rbac-web";

const editor = new MatrixEditor(await client.getMatrix());

editor.rows(); // [{ feature, label, group, cells: {role: {level, overridden, dirty}}, partialScopeLabel }]
editor.setCell("reports.export", "staff", 3);
editor.dirtyCount; // 1
editor.edits; // [{ feature: "reports.export", role: "staff", level: 3 }]

editor.apply(await client.saveMatrix(editor.edits)); // persist, then re-render
editor.apply(await client.resetMatrix()); // clear all overrides

LEVELS gives you the four { value, name, label, glyph } options for cell dropdowns.

Because PARTIAL is a scoped write ("write, but only your own records / your own department"), each row also carries partialScopeLabel — a human, one-line label for that feature's effective write scope (its own partial_scope, else the snapshot's default_partial_scope), resolved through the served scope catalogue — the list of scope atoms the backend actually resolves, served for the editor's dropdown. Show it next to the PARTIAL option so a cell reads "~ Partial · own records" instead of a bare "Partial"; it's null when no scope applies. The React PermissionMatrix does this out of the box, and the standalone scopeExprLabel(scope, catalogue) helper is exported if you build your own view. It's a display hint only — the server owns scope evaluation.

Manage roles​

await client.listRoles();
await client.createRole({ slug: "auditor", label: "Auditor", group: "Oversight" });
await client.updateRole("auditor", { label: "Chief Auditor" });
await client.updateRole("auditor", { is_active: false });

React admin UI​

A React management UI ships from the @archenstack/rbac-web/react subpath (React is a peer dependency). The fastest path is the one-import drop-in — hand it an authenticated client and it renders the whole editor:

import { PermissionsAdmin } from "@archenstack/rbac-web/react";
import "@archenstack/rbac-web/react/styles.css";

<PermissionsAdmin client={client} onError={notify} />

PermissionsAdmin composes seven of the eight panels — MyPermissions, RolesTable, GroupsTable, FeaturesTable, MembersTable, AssignmentsTable, PermissionMatrix — and owns the glue: a shared refresh so a mutation in one panel reloads the others, system-admin detection, and error routing. Authentication stays with your app — the component never logs in; it only uses the client you pass. Drop down to the individual panels when you want a custom layout. ServiceAccounts is the eighth panel and ships standalone — it is exported but not composed here.

For a multi-tenant backend it also renders an org picker when the caller can target more than one tenant: switching orgs re-scopes the client with withOrg(...) and reloads every panel against that tenant. Each panel is then a per-org view — a "slug already exists" 409 is scoped to the active org. See the org picker. It also adds an Assignments panel (for administrators) to manage the per-org (org, sub) → role assignments.

Class names are namespaced (wr-*) and colours read --wr-* CSS variables, so you can map them onto your app's palette.

Any framework (or none): the web component​

For non-React apps — plain HTML, Vue, Svelte, Angular — the @archenstack/rbac-web/element entry ships the same UI as a self-contained <archenstack-admin> custom element (a tiny Preact runtime, panels, and styles are all bundled in, and it renders into a shadow root):

<archenstack-admin id="rbac"></archenstack-admin>
<script type="module">
import "@archenstack/rbac-web/element"; // registers the element
import { RbacClient } from "@archenstack/rbac-web";
document.getElementById("rbac").client = new RbacClient({ baseUrl: "/api/v1", token });
</script>
Never put a token in a DOM attribute

Pass the token imperatively via the .client property (or a token getter), never as an HTML attribute or URL — a token in server-rendered HTML leaks to anyone who can read the page. The only attribute is base-url, for cookie/session auth where the browser sends credentials automatically.

API surface​

ExportPurpose
Permissions, Permissions.from(me)check permissions from /me/
RbacClientgetMatrix · saveMatrix · resetMatrix · me · myPermissions · check · checkMany · listRoles · createRole · updateRole · withOrg · listOrgs · listAssignments · assign · revokeAssignment
MatrixEditorrows · setCell · edits · dirtyCount · discard · apply
RbacErrorthrown on non-2xx (.status, .detail)
AccessLevel, LEVELS, levelInfo, canRead, canWrite, allowsActionthe level model + metadata
@archenstack/rbac-web/reactPermissionsAdmin + all eight panels, plus the permission layer (RbacProvider, useCan, <Can>, useFilteredItems, useCanObject, useCanObjects)
@archenstack/rbac-web/element<archenstack-admin> custom element + mount()

The resolving core (decide, evalScope, validate, canonicalJson, exportSnapshot/importSnapshot, …) is additive over the facade for clients that resolve a snapshot locally.

Auth transport is your choice

SPA apps pass a bearer token (or a getter) held in memory — never localStorage, which XSS can read. SSR/same-site apps use an httpOnly cookie session with credentials: "include" and a CSRF header on writes. See the security model.

Releasing​

Releases publish to Archenstack's GitLab npm registry from CI. Bump the version (npm version patch / minor / major), then push a archenstack-rbac-web/vX.Y.Z tag — the pipeline runs npm run build (tsup → dist/: ESM + CJS + .d.ts + the React stylesheet, the only thing the files field ships) and publishes. The committed manifest keeps "private": true; CI opts into the publish explicitly.

The published entry points are the exports map: @archenstack/rbac-web (core), @archenstack/rbac-web/react (+ /react/styles.css), and @archenstack/rbac-web/element. React is an optional peer dependency.

See also​