233 lines
16 KiB
Plaintext
233 lines
16 KiB
Plaintext
page wrnexusauthz {
|
|
seo {
|
|
title = "@wrnexus/authz"
|
|
description = "Role, permission, policy, and authorization guards."
|
|
}
|
|
|
|
view {
|
|
<div class="docs-shell">
|
|
<header class="topbar">
|
|
<a class="brand" href="/"><span>W</span> WRNexusJS</a>
|
|
<nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
|
|
<button data-wire-theme-toggle class="theme-button" aria-label="Toggle theme">Theme</button>
|
|
</header>
|
|
<main class="page package-page">
|
|
<aside class="sidebar"><a href="/packages">← All packages</a><span class="category">Security</span><h1>@wrnexus/authz</h1><p>Role, permission, policy, and authorization guards.</p><code>bun add @wrnexus/authz@0.2.14</code><nav><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
|
|
<article class="documentation"><section class="doc-intro"><span class="eyebrow">Security</span><h1>@wrnexus/authz</h1><p>Role, permission, policy, and authorization guards.</p><pre><code>bun add @wrnexus/authz@0.2.14</code></pre></section><section id="guide" class="prose"><blockquote>Composable authorization for WRNexusJS — role-based (RBAC), policy-based (PBAC), and attribute-based (ABAC) access control that reduces to a boolean check plus an <code>authorize()</code> guard.</blockquote>
|
|
<p>Part of the <strong>WRNexusJS</strong> framework — an SSR-first, Bun-native full-stack web framework.</p>
|
|
<h3 id="overview">Overview</h3>
|
|
<p><code>@wrnexus/authz</code> is a small, server-side authorization toolkit. It gives you three interchangeable models — RBAC (roles → permissions), PBAC (policy predicates), and ABAC (attribute matchers) — that all collapse to a <code>boolean | Promise<boolean></code> decision. Wrap any decision in a <code>Middleware</code> guard (<code>authorize</code>, <code>requireRole</code>, <code>requirePermission</code>) to protect WRNexusJS routes. Reach for it whenever a route or action needs to be gated on who the user is, what roles they hold, or attributes of the user and the resource. It plugs into <code>@wrnexus/core</code> by reading <code>ctx.user</code> as the authorization subject.</p>
|
|
<h3 id="installation">Installation</h3>
|
|
<pre data-language="bash"><code>bun add @wrnexus/authz</code></pre>
|
|
<blockquote>Private package — the machine must be authenticated to the <code>wrnexus</code> npm org</blockquote>
|
|
<blockquote>(a read token in <code>~/.npmrc</code>). Requires <strong>Bun</strong> (Node is not supported).</blockquote>
|
|
<h3 id="api">API</h3>
|
|
<p>The package has a single entry point (<code>@wrnexus/authz</code>) exporting the following.</p>
|
|
<h4 id="types">Types</h4>
|
|
<div class="table-wrap"><table>
|
|
<thead><tr><th>Symbol</th><th>Description</th></tr></thead>
|
|
<tbody><tr><td><code>Subject</code></td><td>The authorized principal: <code>{ id?: string; roles?: string[]; [attribute: string]: unknown }</code>.</td></tr><tr><td><code>Rbac</code></td><td>An RBAC checker: <code>{ can(subject, permission): boolean; permissionsFor(roles): Set<string> }</code>.</td></tr><tr><td><code>Policy<S = Subject, R = unknown></code></td><td>A predicate `(subject: S, resource?: R) => boolean \</td><td>Promise<boolean>`.</td></tr></tbody></table></div>
|
|
<h4 id="rbac">RBAC</h4>
|
|
<h4 id="definerbac-roles-record-string-string-rbac"><code>defineRbac(roles: Record<string, string[]>): Rbac</code></h4>
|
|
<p>Builds an RBAC checker from a role → permissions map. Supported permission forms:</p>
|
|
<ul>
|
|
<li><code>"*"</code> — grants every permission.</li>
|
|
<li><code>"ns:*"</code> — namespace wildcard (e.g. <code>"post:*"</code> grants <code>"post:write"</code>).</li>
|
|
<li><code>"role:<name>"</code> — inherits all permissions of another role (resolved recursively, cycle-safe).</li>
|
|
</ul>
|
|
<p>The returned <code>Rbac</code> provides:</p>
|
|
<ul>
|
|
<li><code>can(subject, permission)</code> — <code>true</code> if any of <code>subject.roles</code> grants <code>permission</code> (honouring <code>*</code> and namespace wildcards). Returns <code>false</code> when the subject has no roles.</li>
|
|
<li><code>permissionsFor(roles)</code> — the resolved <code>Set<string></code> of all permissions granted to a set of roles.</li>
|
|
</ul>
|
|
<h4 id="hasrole-subject-subject-undefined-required-string-boolean"><code>hasRole(subject: Subject | undefined, ...required: string[]): boolean</code></h4>
|
|
<p><code>true</code> if the subject holds <strong>all</strong> of the given roles.</p>
|
|
<h4 id="pbac-abac-combinators">PBAC / ABAC combinators</h4>
|
|
<ul>
|
|
<li><code>any<S, R>(...policies: Policy<S, R>[]): Policy<S, R></code> — allow if <strong>any</strong> policy passes (OR); awaits async policies.</li>
|
|
<li><code>all<S, R>(...policies: Policy<S, R>[]): Policy<S, R></code> — allow only if <strong>all</strong> policies pass (AND); awaits async policies.</li>
|
|
<li><code>attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S></code> — ABAC helper that allows when <code>subject[name]</code> equals <code>match</code>, or when <code>match</code> is a function, when <code>match(value)</code> is truthy.</li>
|
|
</ul>
|
|
<h4 id="guards-middleware">Guards (middleware)</h4>
|
|
<p>Each guard returns a <code>@wrnexus/core</code> <code>Middleware</code>. A denied request short-circuits with <code>Response.json({ ok: false, error: "Forbidden" }, { status: 403 })</code>.</p>
|
|
<ul>
|
|
<li><code>authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware</code> — runs <code>policy</code> against the request <code>Context</code>; calls <code>next()</code> when it resolves truthy, otherwise returns 403.</li>
|
|
<li><code>requireRole(...roles: string[]): Middleware</code> — allows when <code>ctx.user</code> holds <strong>any</strong> of the listed roles.</li>
|
|
<li><code>requirePermission(rbac: Rbac, permission: string): Middleware</code> — allows when <code>rbac.can(ctx.user, permission)</code> is <code>true</code>.</li>
|
|
</ul>
|
|
<h3 id="usage">Usage</h3>
|
|
<h4 id="rbac-2">RBAC</h4>
|
|
<pre data-language="ts"><code>import { defineRbac, hasRole } from "@wrnexus/authz";
|
|
|
|
const rbac = defineRbac({
|
|
admin: ["*"],
|
|
editor: ["post:read", "post:write"],
|
|
viewer: ["post:read"],
|
|
// role inheritance: lead gets everything an editor has, plus post:publish
|
|
lead: ["role:editor", "post:publish"],
|
|
});
|
|
|
|
const user = { id: "u1", roles: ["editor"] };
|
|
|
|
rbac.can(user, "post:write"); // true
|
|
rbac.can(user, "post:delete"); // false
|
|
rbac.permissionsFor(["lead"]); // Set { "post:read", "post:write", "post:publish" }
|
|
hasRole(user, "editor"); // true</code></pre>
|
|
<h4 id="guarding-routes">Guarding routes</h4>
|
|
<pre data-language="ts"><code>import { authorize, requireRole, requirePermission, defineRbac } from "@wrnexus/authz";
|
|
|
|
const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
|
|
|
|
// Only admins or editors
|
|
app.get("/dashboard", requireRole("admin", "editor"), handler);
|
|
|
|
// Requires a specific permission
|
|
app.post("/posts", requirePermission(rbac, "post:write"), handler);
|
|
|
|
// Arbitrary policy over the request context
|
|
app.delete(
|
|
"/posts/:id",
|
|
authorize((ctx) => hasRole(ctx.user, "admin")),
|
|
handler,
|
|
);</code></pre>
|
|
<h4 id="pbac-abac-policies">PBAC / ABAC policies</h4>
|
|
<pre data-language="ts"><code>import { any, all, attr, authorize, type Policy } from "@wrnexus/authz";
|
|
|
|
interface User {
|
|
id: string;
|
|
department?: string;
|
|
roles?: string[];
|
|
}
|
|
interface Post {
|
|
authorId: string;
|
|
}
|
|
|
|
// Ownership policy (subject + resource)
|
|
const ownsPost: Policy<User, Post> = (u, post) => u.id === post?.authorId;
|
|
|
|
// ABAC: attribute equality, or a predicate
|
|
const inEngineering = attr<User>("department", "engineering");
|
|
const isVerified = attr<User>("verified", (v) => v === true);
|
|
|
|
// Compose: allow if the user owns the post OR is in engineering AND verified
|
|
const canEdit = any(ownsPost, all(inEngineering, isVerified));
|
|
|
|
app.put(
|
|
"/posts/:id",
|
|
authorize((ctx) => canEdit(ctx.user as User, loadPost(ctx))),
|
|
handler,
|
|
);</code></pre>
|
|
<h3 id="requirements-notes">Requirements / Notes</h3>
|
|
<ul>
|
|
<li><strong>Bun-only</strong> — like the rest of WRNexusJS, this package targets the Bun runtime; Node is not supported.</li>
|
|
<li>Works with [<code>@wrnexus/core</code>](../core) — the guards return <code>Middleware</code> and read the subject from <code>ctx.user</code> on the request <code>Context</code>. Both types are imported from <code>@wrnexus/core</code>.</li>
|
|
<li>Policy combinators (<code>any</code>, <code>all</code>) and <code>authorize</code> are async-aware, so policies may return a <code>Promise<boolean></code> (e.g. for a database ownership check).</li>
|
|
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>import { Context, Middleware } from '@wrnexus/core';
|
|
|
|
/**
|
|
* @wrnexus/authz — authorization: role-based (RBAC), policy-based (PBAC), and
|
|
* attribute-based (ABAC). Compose freely; all three reduce to a boolean check
|
|
* plus an `authorize()` guard middleware.
|
|
*
|
|
* const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
|
|
* rbac.can(user, "post:write");
|
|
*
|
|
* // PBAC/ABAC: a policy is a predicate over subject + resource + attributes
|
|
* const ownsPost: Policy<User, Post> = (u, post) => u.id === post.authorId;
|
|
* authorize((ctx) => ownsPost(ctx.user, resource)) // middleware
|
|
*/
|
|
|
|
interface Subject {
|
|
id?: string;
|
|
roles?: string[];
|
|
[attribute: string]: unknown;
|
|
}
|
|
interface Rbac {
|
|
/** True if any of the subject's roles grants `permission` (supports "*" and "ns:*"). */
|
|
can(subject: Subject | undefined, permission: string): boolean;
|
|
/** All permissions granted to a set of roles. */
|
|
permissionsFor(roles: string[]): Set<string>;
|
|
}
|
|
/** Build an RBAC checker from a role → permissions map. */
|
|
declare function defineRbac(roles: Record<string, string[]>): Rbac;
|
|
/** True if the subject has ALL of the given roles. */
|
|
declare function hasRole(subject: Subject | undefined, ...required: string[]): boolean;
|
|
/** A policy predicate: subject (+ optional resource/attributes) → allowed. */
|
|
type Policy<S = Subject, R = unknown> = (subject: S, resource?: R) => boolean | Promise<boolean>;
|
|
/** Combine policies: allow if ANY passes (OR). */
|
|
declare function any<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
|
|
/** Combine policies: allow only if ALL pass (AND). */
|
|
declare function all<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
|
|
/** ABAC helper: allow when an attribute matches (equality or predicate). */
|
|
declare function attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S>;
|
|
/** Guard a route with a policy over `ctx` (reads `ctx.user` as the subject). */
|
|
declare function authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware;
|
|
/** Guard requiring one of the given roles. */
|
|
declare function requireRole(...roles: string[]): Middleware;
|
|
/** Guard requiring an RBAC permission. */
|
|
declare function requirePermission(rbac: Rbac, permission: string): Middleware;
|
|
|
|
export { type Policy, type Rbac, type Subject, all, any, attr, authorize, defineRbac, hasRole, requirePermission, requireRole };
|
|
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Copy-ready examples taken from this package's published documentation.</p><div class="example-grid"><article class="example-card"><h3>Example 1</h3><pre data-language="bash"><code>bun add @wrnexus/authz</code></pre></article><article class="example-card"><h3>Example 2</h3><pre data-language="ts"><code>import { defineRbac, hasRole } from "@wrnexus/authz";
|
|
|
|
const rbac = defineRbac({
|
|
admin: ["*"],
|
|
editor: ["post:read", "post:write"],
|
|
viewer: ["post:read"],
|
|
// role inheritance: lead gets everything an editor has, plus post:publish
|
|
lead: ["role:editor", "post:publish"],
|
|
});
|
|
|
|
const user = { id: "u1", roles: ["editor"] };
|
|
|
|
rbac.can(user, "post:write"); // true
|
|
rbac.can(user, "post:delete"); // false
|
|
rbac.permissionsFor(["lead"]); // Set { "post:read", "post:write", "post:publish" }
|
|
hasRole(user, "editor"); // true</code></pre></article><article class="example-card"><h3>Example 3</h3><pre data-language="ts"><code>import { authorize, requireRole, requirePermission, defineRbac } from "@wrnexus/authz";
|
|
|
|
const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
|
|
|
|
// Only admins or editors
|
|
app.get("/dashboard", requireRole("admin", "editor"), handler);
|
|
|
|
// Requires a specific permission
|
|
app.post("/posts", requirePermission(rbac, "post:write"), handler);
|
|
|
|
// Arbitrary policy over the request context
|
|
app.delete(
|
|
"/posts/:id",
|
|
authorize((ctx) => hasRole(ctx.user, "admin")),
|
|
handler,
|
|
);</code></pre></article><article class="example-card"><h3>Example 4</h3><pre data-language="ts"><code>import { any, all, attr, authorize, type Policy } from "@wrnexus/authz";
|
|
|
|
interface User {
|
|
id: string;
|
|
department?: string;
|
|
roles?: string[];
|
|
}
|
|
interface Post {
|
|
authorId: string;
|
|
}
|
|
|
|
// Ownership policy (subject + resource)
|
|
const ownsPost: Policy<User, Post> = (u, post) => u.id === post?.authorId;
|
|
|
|
// ABAC: attribute equality, or a predicate
|
|
const inEngineering = attr<User>("department", "engineering");
|
|
const isVerified = attr<User>("verified", (v) => v === true);
|
|
|
|
// Compose: allow if the user owns the post OR is in engineering AND verified
|
|
const canEdit = any(ownsPost, all(inEngineering, isVerified));
|
|
|
|
app.put(
|
|
"/posts/:id",
|
|
authorize((ctx) => canEdit(ctx.user as User, loadPost(ctx))),
|
|
handler,
|
|
);</code></pre></article></div></section></article>
|
|
<aside class="on-this-page"><h2>On this page</h2><nav><a class="toc-level-2" href="#guide">Guide</a><a class="toc-level-3" href="#overview">Overview</a><a class="toc-level-3" href="#installation">Installation</a><a class="toc-level-3" href="#api">API</a><a class="toc-level-4" href="#types">Types</a><a class="toc-level-4" href="#rbac">RBAC</a><a class="toc-level-4" href="#definerbac-roles-record-string-string-rbac">defineRbac(roles: Record<string, string[]>): Rbac</a><a class="toc-level-4" href="#hasrole-subject-subject-undefined-required-string-boolean">hasRole(subject: Subject | undefined, ...required: string[]): boolean</a><a class="toc-level-4" href="#pbac-abac-combinators">PBAC / ABAC combinators</a><a class="toc-level-4" href="#guards-middleware">Guards (middleware)</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-4" href="#rbac-2">RBAC</a><a class="toc-level-4" href="#guarding-routes">Guarding routes</a><a class="toc-level-4" href="#pbac-abac-policies">PBAC / ABAC policies</a><a class="toc-level-3" href="#requirements-notes">Requirements / Notes</a><a class="toc-level-2" href="#api">Complete API</a><a class="toc-level-2" href="#examples">Examples</a></nav></aside>
|
|
</main>
|
|
<footer>WRNexusJS 0.2.14 · SSR-first · Bun-native · Documentation generated from published package APIs.</footer>
|
|
</div>
|
|
}
|
|
}
|