153 lines
13 KiB
Plaintext
153 lines
13 KiB
Plaintext
page wrnexusjwt {
|
|
seo {
|
|
title = "@wrnexus/jwt"
|
|
description = "HS256 JWT signing, verification, and bearer authentication."
|
|
}
|
|
|
|
view {
|
|
<div class="docs-shell">
|
|
<a class="skip-link" href="#main">Skip to content</a>
|
|
<header class="topbar">
|
|
<a class="brand" href="/"><span>W</span> WRNexusJS</a>
|
|
<nav aria-label="Primary"><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
|
|
<div class="topbar-actions"><a class="preview-pill" href="/access">Private preview · v0.2.19</a><button data-wire-theme-toggle class="theme-button" aria-label="Toggle color theme" title="Toggle color theme">◐</button></div>
|
|
</header>
|
|
<div class="mobile-doc-nav"><details><summary>Browse documentation</summary><nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a><a href="/tutorial">Tutorial</a><a href="/guides/project-structure">Guides</a><a href="/examples">Examples</a><a href="/search">Search</a></nav></details></div>
|
|
<main class="page package-page">
|
|
<aside class="sidebar"><a href="/packages">← All packages</a><span class="category">Security</span><h2>@wrnexus/jwt</h2><p>HS256 JWT signing, verification, and bearer authentication.</p><span class="status status-beta">Private preview · 0.2.19</span><nav><a href="#access">Access</a><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
|
|
<article id="main" class="documentation"><section class="doc-intro"><span class="eyebrow">Security · Preview</span><h1>@wrnexus/jwt</h1><p>HS256 JWT signing, verification, and bearer authentication.</p><section id="access" class="access-callout"><h2>Private registry access required</h2><p>This package is not available from the public npm registry. After WorkRoot approves access and supplies private registry instructions, install the release-aligned package:</p><pre><code>bun add @wrnexus/jwt@0.2.19</code><button type="button" class="copy-button" aria-label="Copy installation command">Copy</button></pre><p><a href="/access">Request preview access</a>. Never put registry tokens in source control.</p></section></section><section id="guide" class="prose"><blockquote>Dependency-free JSON Web Tokens (HS256) via Web Crypto, plus a bearer-token auth middleware for WRNexusJS.</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/jwt</code> signs and verifies stateless JSON Web Tokens using the <strong>HS256</strong> (HMAC-SHA-256) algorithm. It has no runtime dependencies — signing and verification are implemented directly on the standard <strong>Web Crypto</strong> API (<code>crypto.subtle</code>), which Bun provides natively. It runs server-side and pairs with the session-based auth in <code>@wrnexus/core</code>, giving you a stateless option for API and mobile clients. Reach for it when you need bearer-token auth rather than cookie sessions.</p>
|
|
<pre data-language="bash"><code>bun add @wrnexus/jwt</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>Single entry point (<code>@wrnexus/jwt</code>). All functions are async and return Promises.</p>
|
|
<div class="table-wrap"><table>
|
|
<thead><tr><th>Export</th><th>Kind</th><th>Description</th></tr></thead>
|
|
<tbody><tr><td><code>signJwt(payload, secret, options?)</code></td><td>function</td><td>Sign claims into an HS256 token string.</td></tr><tr><td><code>verifyJwt<T>(token, secret, options?)</code></td><td>function</td><td>Verify a token and return its claims, or throw.</td></tr><tr><td><code>jwtAuth(options)</code></td><td>function</td><td>Middleware that verifies a bearer JWT and sets <code>ctx.user</code>.</td></tr><tr><td><code>JwtError</code></td><td>class</td><td>Error thrown on any signature/payload/expiry failure.</td></tr><tr><td><code>JwtClaims</code></td><td>interface</td><td>Claims shape (<code>sub</code>, <code>iat</code>, <code>exp</code>, <code>nbf</code>, plus arbitrary keys).</td></tr><tr><td><code>SignOptions</code></td><td>interface</td><td>Options for <code>signJwt</code>.</td></tr><tr><td><code>JwtAuthOptions</code></td><td>interface</td><td>Options for <code>jwtAuth</code>.</td></tr></tbody></table></div>
|
|
<h4 id="signjwt-payload-secret-options"><code>signJwt(payload, secret, options?)</code></h4>
|
|
<pre data-language="ts"><code>function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;</code></pre>
|
|
<p>Signs <code>payload</code> with <code>secret</code> using HS256 and returns the encoded token (<code>header.body.signature</code>). An <code>iat</code> (issued-at) claim is always added.</p>
|
|
<p><code>SignOptions</code>:</p>
|
|
<ul>
|
|
<li><code>expiresIn?: number</code> — seconds until expiry; sets the <code>exp</code> claim.</li>
|
|
<li><code>now?: number</code> — override the issued-at time (seconds), useful for testing.</li>
|
|
</ul>
|
|
<h4 id="verifyjwt-t-token-secret-options"><code>verifyJwt<T>(token, secret, options?)</code></h4>
|
|
<pre data-language="ts"><code>function verifyJwt<T extends JwtClaims = JwtClaims>(
|
|
token: string,
|
|
secret: string,
|
|
options?: { now?: number },
|
|
): Promise<T>;</code></pre>
|
|
<p>Verifies the HS256 signature and returns the decoded claims typed as <code>T</code>. Throws <code>JwtError</code> when the token is malformed, the signature is invalid, the payload is not valid JSON, the token is expired (<code>exp</code>), or not yet valid (<code>nbf</code>). Pass <code>now</code> (seconds) to override the reference time for the <code>exp</code>/<code>nbf</code> checks.</p>
|
|
<h4 id="jwtauth-options"><code>jwtAuth(options)</code></h4>
|
|
<pre data-language="ts"><code>function jwtAuth(options: JwtAuthOptions): Middleware;</code></pre>
|
|
<p>Returns a WRNexusJS <code>Middleware</code> that reads a token, verifies it, and assigns the claims to <code>ctx.user</code>.</p>
|
|
<p><code>JwtAuthOptions</code>:</p>
|
|
<ul>
|
|
<li><code>secret: string</code> — the HMAC secret used to verify tokens.</li>
|
|
<li><code>getToken?: (ctx: Context) => string | undefined</code> — how to extract the token.</li>
|
|
<p>Defaults to reading <code>Authorization: Bearer <token></code>.</p>
|
|
<li><code>required?: boolean</code> — when <code>true</code> (default), a missing or invalid token</li>
|
|
<p>responds with <code>401 { ok: false, error: "Unauthorized" }</code>. When <code>false</code>, requests pass through and <code>ctx.user</code> is only set if a valid token is present.</p>
|
|
</ul>
|
|
<h3 id="usage">Usage</h3>
|
|
<pre data-language="ts"><code>import { signJwt, verifyJwt, jwtAuth, JwtError } from "@wrnexus/jwt";
|
|
|
|
const secret = process.env.JWT_SECRET!;
|
|
|
|
// Sign a token that expires in one hour
|
|
const token = await signJwt({ sub: user.id, role: "admin" }, secret, {
|
|
expiresIn: 3600,
|
|
});
|
|
|
|
// Verify it later
|
|
try {
|
|
const claims = await verifyJwt<{ sub: string; role: string }>(token, secret);
|
|
console.log(claims.sub, claims.role);
|
|
} catch (err) {
|
|
if (err instanceof JwtError) {
|
|
// invalid signature, expired, malformed, etc.
|
|
}
|
|
}</code></pre>
|
|
<p>Protecting routes with the middleware:</p>
|
|
<pre data-language="ts"><code>import { jwtAuth } from "@wrnexus/jwt";
|
|
|
|
// Require a valid bearer token; ctx.user holds the verified claims
|
|
app.use(jwtAuth({ secret: process.env.JWT_SECRET! }));
|
|
|
|
// Optional auth — populate ctx.user when present, but don't 401
|
|
app.use(jwtAuth({ secret: process.env.JWT_SECRET!, required: false }));</code></pre>
|
|
<h3 id="requirements-notes">Requirements / Notes</h3>
|
|
<ul>
|
|
<li><strong>Bun-only.</strong> Uses the standard Web Crypto API (<code>crypto.subtle.importKey</code>,</li>
|
|
<p><code>sign</code>, <code>verify</code>) plus <code>btoa</code>/<code>atob</code> and <code>TextEncoder</code>/<code>TextDecoder</code> — all provided by Bun. No third-party crypto dependency.</p>
|
|
<li><strong>Algorithm:</strong> HS256 (HMAC with SHA-256) only. Asymmetric algorithms (RS/ES)</li>
|
|
<p>are not supported.</p>
|
|
<li>Integrates with [<code>@wrnexus/core</code>](../core) for <code>Context</code>, <code>Middleware</code>, and</li>
|
|
<p><code>ctx.user</code>; it complements the framework's cookie/session auth with a stateless bearer-token flow for API and mobile clients.</p>
|
|
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration comes from the exact installed package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>import { Context, Middleware } from '@wrnexus/core';
|
|
|
|
/**
|
|
* @wrnexus/jwt — dependency-free JSON Web Tokens (HS256) via WebCrypto, plus a
|
|
* bearer-token auth middleware. Pairs with the session auth in @wrnexus/core for
|
|
* stateless (API/mobile) authentication.
|
|
*
|
|
* const token = await signJwt({ sub: user.id, role: "admin" }, secret, { expiresIn: 3600 });
|
|
* const claims = await verifyJwt(token, secret); // throws JwtError if invalid/expired
|
|
*/
|
|
|
|
declare class JwtError extends Error {
|
|
constructor(message: string);
|
|
}
|
|
interface JwtClaims {
|
|
/** Subject (user id). */
|
|
sub?: string;
|
|
/** Issued-at (seconds). */
|
|
iat?: number;
|
|
/** Expiry (seconds). */
|
|
exp?: number;
|
|
/** Not-before (seconds). */
|
|
nbf?: number;
|
|
[key: string]: unknown;
|
|
}
|
|
interface SignOptions {
|
|
/** Seconds until expiry (sets `exp`). */
|
|
expiresIn?: number;
|
|
/** Override issued-at (seconds). */
|
|
now?: number;
|
|
}
|
|
/** Sign a payload into a JWT (HS256). */
|
|
declare function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;
|
|
/** Verify a JWT and return its claims. Throws `JwtError` on any failure. */
|
|
declare function verifyJwt<T extends JwtClaims = JwtClaims>(token: string, secret: string, options?: {
|
|
now?: number;
|
|
}): Promise<T>;
|
|
interface JwtAuthOptions {
|
|
secret: string;
|
|
/** Where to read the token. Default: `Authorization: Bearer <token>`. */
|
|
getToken?: (ctx: Context) => string | undefined;
|
|
/** Reject unauthenticated requests with 401. Default true. */
|
|
required?: boolean;
|
|
}
|
|
/**
|
|
* Middleware that verifies a bearer JWT and sets `ctx.user` to its claims.
|
|
* When `required` (default), a missing/invalid token gets a 401.
|
|
*/
|
|
declare function jwtAuth(options: JwtAuthOptions): Middleware;
|
|
|
|
export { type JwtAuthOptions, type JwtClaims, JwtError, type SignOptions, jwtAuth, signJwt, verifyJwt };
|
|
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Examples are taken from this package's installed documentation and must be evaluated with its requirements and stability notes.</p><div class="example-grid"><article class="example-card"><h3>Example 1</h3><pre data-language="bash"><code>bun add @wrnexus/jwt</code></pre></article><article class="example-card"><h3>Example 2</h3><pre data-language="ts"><code>function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;</code></pre></article><article class="example-card"><h3>Example 3</h3><pre data-language="ts"><code>function verifyJwt<T extends JwtClaims = JwtClaims>(
|
|
token: string,
|
|
secret: string,
|
|
options?: { now?: number },
|
|
): Promise<T>;</code></pre></article><article class="example-card"><h3>Example 4</h3><pre data-language="ts"><code>function jwtAuth(options: JwtAuthOptions): Middleware;</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="#api">API</a><a class="toc-level-4" href="#signjwt-payload-secret-options">signJwt(payload, secret, options?)</a><a class="toc-level-4" href="#verifyjwt-t-token-secret-options">verifyJwt<T>(token, secret, options?)</a><a class="toc-level-4" href="#jwtauth-options">jwtAuth(options)</a><a class="toc-level-3" href="#usage">Usage</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.19 · Private Developer Preview · Bun-native · Documentation generated from installed package APIs.</footer>
|
|
</div>
|
|
}
|
|
}
|