JS Server SDK Overview
What is @authrim/server?
Section titled “What is @authrim/server?”@authrim/server is Authrim’s server-side SDK for resource servers. It validates JWT access tokens, verifies DPoP proofs, manages issuer-scoped JWKS key sets, and provides framework middleware for popular Node.js frameworks. It also exposes server-side helpers for introspection, revocation, Native SSO device secrets, canonical Step-Up, customer profile protected resources, cookie-session CSRF, and back-channel logout.
Architecture
Section titled “Architecture”The following diagram shows where @authrim/server fits in the OAuth 2.0 architecture:
sequenceDiagram
participant Client as Client App<br>(@authrim/web or<br>@authrim/core)
participant AuthServer as Authrim<br>Authorization Server
participant Resource as Resource Server<br>(@authrim/server)
Client->>AuthServer: 1. Authorization Request
AuthServer-->>Client: 2. Access Token (JWT)
Client->>Resource: 3. API Request + Access Token
Resource->>AuthServer: 4. Fetch JWKS (cached)
Resource->>Resource: 5. Validate Token
Resource-->>Client: 6. Protected Resource
The SDK handles steps 4 and 5 automatically, fetching and caching the authorization server’s public keys, then validating token signatures and claims.
Package Entry Points
Section titled “Package Entry Points”| Export Path | Purpose | Key Exports |
|---|---|---|
@authrim/server | Main entry — client factory, types, validators, JWKS, Step-Up, customer profiles, session utilities | createAuthrimServer, AuthrimServer, StepUpClient, CustomerProfileClient, BackChannelLogoutValidator |
@authrim/server/providers | Provider interfaces and utilities | CryptoProvider, HttpProvider, ClockProvider, CacheProvider |
@authrim/server/adapters/express | Express middleware | authrimMiddleware, authrimOptionalMiddleware |
@authrim/server/adapters/fastify | Fastify hooks and plugins | authrimPreHandler, authrimPlugin, authrimOptionalPreHandler, authrimOptionalPlugin |
@authrim/server/adapters/hono | Hono middleware | authrimMiddleware, authrimOptionalMiddleware, getAuth, getAuthTokenType |
@authrim/server/adapters/koa | Koa middleware | authrimMiddleware, authrimOptionalMiddleware |
@authrim/server/adapters/nestjs | NestJS guard and utilities | createAuthrimGuard, createAuthrimOptionalGuard, getAuthFromRequest, getAuthTokenTypeFromRequest |
Core Features
Section titled “Core Features”- JWT Access Token Validation — Signature verification, claims validation (iss, aud, exp, nbf, iat), scope enforcement
- DPoP Proof Validation (RFC 9449) — Sender-constrained token verification with JWK Thumbprint binding
- JWKS Management — Auto-discovery, caching with Cache-Control, key rotation support, single-flight fetch
- Multi-Issuer Resource Servers — Allow-list multiple issuers and configure issuer-specific JWKS, introspection, revocation, and Step-Up endpoints
- Token Introspection (RFC 7662) — Query the authorization server for opaque token status
- Token Revocation (RFC 7009) — Revoke tokens at the authorization server
- Native SSO Device Secret Operations — Introspect and revoke
device_secretvalues without logging the raw secret - Canonical Step-Up — Start, inspect, complete, resend, and cancel Step-Up actions from server code
- Customer Profile Protected Resource API — Read profiles with elevation grants and perform delegated writes
- Cookie Session Security — Direct Auth artifact redemption helpers, double-submit CSRF helpers, and cookie attribute resolution
- Back-Channel Logout (OIDC 1.0) — Validate logout tokens from the authorization server
- Framework Middleware — Ready-to-use adapters for Express, Fastify, Hono, Koa, and NestJS
- Security Hardened — Timing-safe comparisons,
alg:nonerejection, SSRF protection, JWT size limits
Supported Algorithms
Section titled “Supported Algorithms”| Family | Algorithms |
|---|---|
| RSA PKCS#1 v1.5 | RS256, RS384, RS512 |
| RSA-PSS | PS256, PS384, PS512 |
| ECDSA | ES256, ES384, ES512 |
| EdDSA | EdDSA |
Supported Runtimes
Section titled “Supported Runtimes”@authrim/server runs on any JavaScript runtime with standard Web Crypto API support:
- Node.js 18+
- Bun
- Deno
- Cloudflare Workers
- Vercel Edge Runtime
How It Works
Section titled “How It Works”@authrim/server validates access tokens in three phases:
- Initialization — On startup, the SDK fetches the authorization server’s OIDC Discovery document and JWKS (public keys). These are cached in memory.
- Token Validation — For each incoming request, the SDK parses the JWT, selects the correct signing key by
kid, verifies the cryptographic signature, and validates all standard claims (issuer, audience, expiration, etc.). - Ongoing Key Management — The SDK monitors key freshness, handles Cache-Control headers, and automatically refetches keys when a new
kidis encountered (key rotation).
All of this is encapsulated in two method calls: init() at startup and validateToken() per request.
AuthrimServer Methods
Section titled “AuthrimServer Methods”| Method | Description |
|---|---|
init() | Fetch OIDC Discovery document and JWKS. Call once at startup. |
validateToken(token) | Validate a JWT access token using the configured validation rules. |
validateDPoP(proof, options) | Validate a DPoP proof JWT (RFC 9449). |
introspect(token, tokenTypeHint?, issuerOptions?) | Query the authorization server for token status (RFC 7662). |
revoke(token, tokenTypeHint?, issuerOptions?) | Revoke a token at the authorization server (RFC 7009). |
introspectDeviceSecret(deviceSecret, issuerOptions?) | Query Native SSO device_secret status. |
revokeDeviceSecret(deviceSecret, issuerOptions?) | Revoke a Native SSO device_secret. |
stepUp.start() / startStepUp() | Start a canonical Step-Up action from a step_up_token. |
customerProfiles.getWithElevationGrant() | Read a customer profile with an elevation grant. |
customerProfiles.updateDelegated() | Perform a delegated customer profile write. |
invalidateJwksCache() | Force the next validation to refetch the JWKS. |
Quick Example
Section titled “Quick Example”import { createAuthrimServer } from '@authrim/server';
const authrim = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com', tokenValidation: { requiredScopes: ['profile:read'], requireTenantClaim: true, },});
// Initialize once at startup (fetches JWKS)await authrim.init();
// Validate an incoming access tokenconst result = await authrim.validateToken(bearerToken);if (result.error) { throw new Error(result.error.message);}
console.log(result.data.claims.sub); // Subject (user ID)console.log(result.data.claims.scope); // Granted scopesconsole.log(result.data.issuer); // Validated issuerconsole.log(result.data.tenantId); // Tenant claim when presentconsole.log(result.data.tokenType); // 'Bearer' or 'DPoP'console.log(result.data.expiresIn); // Seconds until expirationWith Framework Middleware
Section titled “With Framework Middleware”Instead of calling validateToken() manually, use a framework adapter for automatic token extraction and validation:
import express from 'express';import { createAuthrimServer } from '@authrim/server';import { authrimMiddleware } from '@authrim/server/adapters/express';
const app = express();const authrim = createAuthrimServer({ issuer: 'https://auth.example.com', audience: 'https://api.example.com',});await authrim.init();
// Protected route — token validated automaticallyapp.get('/api/me', authrimMiddleware(authrim), (req, res) => { res.json({ userId: req.auth.claims.sub });});
// Protected route with required scopesapp.delete('/api/users/:id', authrimMiddleware(authrim, { requiredScopes: ['admin:write'] }), (req, res) => { res.json({ deleted: true });});
app.listen(3000);When to Use @authrim/server
Section titled “When to Use @authrim/server”| Scenario | Package | Description |
|---|---|---|
| Validate tokens on your API | @authrim/server | This SDK — for resource servers |
| Log users in via browser | @authrim/web | Browser-based OAuth/OIDC flows |
| Full-stack SvelteKit auth | @authrim/sveltekit | Server hooks + Svelte stores |
| Build a custom OAuth client | @authrim/core | Platform-agnostic protocol library |
RFC Compliance
Section titled “RFC Compliance”| Specification | RFC | Coverage |
|---|---|---|
| JSON Web Token (JWT) | RFC 7519 | Token parsing and claims validation |
| JSON Web Key (JWK) | RFC 7517 | JWKS fetch, key import, key selection |
| JWK Thumbprint | RFC 7638 | DPoP thumbprint computation and binding |
| Token Introspection | RFC 7662 | Full introspection client |
| Token Revocation | RFC 7009 | Full revocation client |
| DPoP | RFC 9449 | Stateless proof validation, thumbprint binding |
| OIDC Core 1.0 | — | ID token and claims validation |
| OIDC Back-Channel Logout 1.0 | — | Logout token validation |
Next Steps
Section titled “Next Steps”- Installation & Quick Start — Install the SDK and set up your first protected API
- Security Considerations — Essential security guidance for production deployments
- Token Validation — Detailed token validation API and pipeline
- DPoP Validation — Sender-constrained token verification
- JWKS Management — Key discovery, caching, and rotation
- Introspection & Revocation — Query and revoke tokens at the authorization server