@obeliskgate/obelisk-auth
v1.1.0
Published
Drop-in OIDC client SDK for Obelisk Gate. Point any project at Obelisk and get login, tokens, refresh, userinfo, local JWKS verification, receipt checks against the signed tree head, an MCP resource-server kit (./mcp), an Express adapter (./express) and a
Maintainers
Readme
@obeliskgate/obelisk-auth
Passport v2 client — unknown clients, unregistered callbacks, scopes, grants, and resources are rejected before sign-in.
Drop-in OIDC client for Obelisk Gate. Point any project at Obelisk and get
login, tokens, refresh, userinfo, and local token verification — no per-project
auth engine, no custom crypto. Replaces what you'd otherwise stand up GoTrue or
NextAuth for. Zero dependencies; TypeScript declarations included for the
., ./next, ./mcp and ./express entry points.
Local development: obelisk-auth init
npx @obeliskgate/obelisk-auth init # in a Next.js or Express project
npx @obeliskgate/obelisk-auth doctor # re-check the setup at any timeinit does four things, each a standard flow:
- Listens on
127.0.0.1on an ephemeral port and opens the Gate's sign-in for its first-party CLI client (PKCE S256,state,nonce, RFC 9207iss). The Gate issues that code only to a session strong enough for account changes: a passkey sign-in, not a remembered, TOTP or magic-link one. - Shows you the Gate Toll pricing contract the Gate names and asks you to accept
it (
--yesaccepts it without asking), then asks the Gate for a dev client: a public client in your personal account whose callbacks are limited tohttp://localhostandhttp://127.0.0.1, on any port (RFC 8252 §7.3). - Writes
.env.local(OBELISK_ISSUER,OBELISK_CLIENT_ID,OBELISK_REDIRECT_URI,OBELISK_COOKIE_SECRET). The cookie secret is generated on your machine and never sent anywhere. Keys already in the file are kept;.env.localis added to.gitignore. - Writes the route files (Next.js:
lib/obelisk-auth.jsplusapp/auth/{login,callback,refresh,logout}/route.js; Express: oneobelisk-auth.jsmodule). Existing files are never overwritten without--force. Then it runsdoctor.
The CLI sign-in works only on a Gate that serves its CLI client document at
/integrations/cimd/obelisk-cli.json (operators enable it with
OBELISK_DEV_CLIENTS=open). On a Gate that does not, init stops before opening
a browser and tells you so; register an app at /account/apps and run
init --client-id=<id> to write the same files without signing in.
doctor reports PASS/FAIL for the configuration, the discovery document, the
JWKS, and an authorize preflight that shows whether the Gate accepts your
client_id and redirect URI (--json prints a receipt-shaped report).
Framework-agnostic core
import { createObeliskAuth } from "@obeliskgate/obelisk-auth";
const auth = createObeliskAuth({
issuer: "https://obeliskgate.com",
clientId: "rp-statvault", // your active registered client_id
redirectUri: "https://statvault.org/auth/callback",
resource: "https://statvault.org/api", // access-token audience
requireVerifiedEmail: true, // fail closed before account linking
});
// 1. start login — stash codeVerifier/state/nonce in the user's session, redirect to url
const { url, codeVerifier, state, nonce } = await auth.beginLogin(); // openid email profile offline_access
// 2. on the callback — pass back ALL FOUR values you stashed, plus the `iss` query
// parameter Obelisk returns. Each one closes a specific attack, and the SDK now
// refuses rather than skipping a check you forgot:
// state + expectedState CSRF on the callback (pass both, or neither)
// nonce id_token replay — REQUIRED when the token carries one
// iss issuer mix-up (RFC 9207)
const { tokens, claims } = await auth.completeLogin({
code,
codeVerifier,
nonce, // from the session
state: url_query.state, // from the callback URL
expectedState: session.state, // from the session
iss: url_query.iss, // from the callback URL
});
// For an existing account, never attach by email alone. Require an authenticated
// legacy session + this fresh Obelisk login, then call assessLegacyAccountLink()
// and persist the issuer/subject binding only when its decision is "link".
// 3. protect a request — LOCAL ES256 verification, no network round-trip
const { ok, claims } = await auth.verifyAccessToken(bearerToken);
// 4. keep alive — rotation-aware (Obelisk revokes the family on refresh reuse)
const next = await auth.refresh(tokens.refresh_token);Resource servers: pin the clients you accept
aud says who a token is for; client_id says which app it was issued to.
verifyAccessToken checks both:
- No
resourceconfigured — the audience is your ownclientId, and only tokens issued to thatclientIdare accepted (reason: "client-not-allowed"otherwise). Nothing to do. resourceconfigured (an API or MCP server other apps call) — tokens from any client that was allowed to request your resource pass, because that is what a resource server is for. Name the clients you actually serve:
const auth = createObeliskAuth({
issuer: "https://obeliskgate.com",
clientId: "rp-statvault",
resource: "https://statvault.org/api",
allowedClients: ["rp-statvault", "rp-statvault-mobile"], // client_id claim must be one of these
});
// or per call: await auth.verifyAccessToken(bearer, { allowedClients: [...] })Next.js (App Router) — four route files
// lib/auth.js
import { createNextHandlers } from "@obeliskgate/obelisk-auth/next";
export const handlers = createNextHandlers({
issuer: process.env.OBELISK_ISSUER,
clientId: process.env.OBELISK_CLIENT_ID,
redirectUri: process.env.OBELISK_REDIRECT_URI,
cookieSecret: process.env.OBELISK_COOKIE_SECRET, // ≥32 chars of high entropy
// (`openssl rand -base64 33`);
// you hold this, Obelisk never sees it
loginRedirect: "/dashboard",
});
// app/auth/login/route.js → export const GET = () => handlers.login();
// app/auth/callback/route.js → export const GET = (req) => handlers.callback(req);
// app/auth/refresh/route.js → export const GET = (req) => handlers.refresh(req);
// app/auth/logout/route.js → export const GET = () => handlers.logout();
// in a server component / middleware:
import { handlers } from "@/lib/auth";
const session = await handlers.getSession(req); // { sub, claims } or null
// on null, bounce through the refresh route (it returns with a fresh session
// or falls through to login — never loops):
// redirect(`/auth/refresh?to=${encodeURIComponent(currentPath)}`)That's the whole integration. The login flow runs Obelisk's immersive passkey/TOTP
ceremony; your app only ever sees standard OIDC tokens. PKCE (S256) is mandatory,
the ID token is verified against the published JSON Web Key Set (cached by kid,
refetched on rotation), and access-token audience is bound to the registered resource.
Session cookies are sealed (AES-256-GCM), split, and least-exposed: the access
session rides every request; the refresh token lives in its own sealed cookie,
path-scoped to the refresh route (SameSite=Strict) so the long-lived credential
never travels with ordinary page requests and is never returned to your app code —
only the refresh handler can spend it. Refresh tokens rotate with reuse detection
on the Gate. email is optional unless the client requires verified-email
admission; safe account linking requires email_verified === true. Every auth
event is an Obelisk Ledger receipt; verifyReceiptInclusion (below) checks one
against the Gate's signed tree head and tells you exactly what it could and could
not prove.
Express (./express)
The same sealed-cookie handlers as ./next, adapted to Node's request/response.
No express dependency: it uses only what http.ServerResponse provides.
import express from "express";
import { createExpressHandlers } from "@obeliskgate/obelisk-auth/express";
const auth = createExpressHandlers({
issuer: process.env.OBELISK_ISSUER,
clientId: process.env.OBELISK_CLIENT_ID,
redirectUri: process.env.OBELISK_REDIRECT_URI,
cookieSecret: process.env.OBELISK_COOKIE_SECRET,
});
const app = express();
auth.mount(app); // GET /auth/login, <callback path>, /auth/refresh, /auth/logout
app.get("/me", auth.requireSession, (req, res) => res.json({ sub: req.obelisk.sub }));Protect a remote MCP server (./mcp)
Your MCP server is the resource server and Obelisk is the authorization server.
The kit does the three resource-server steps of the MCP authorization profile:
it advertises RFC 9728 Protected Resource Metadata, answers 401/403 with a
WWW-Authenticate challenge that names it, and verifies each bearer token
locally. One resource value is canonicalised once and used for the metadata,
the challenge URL and the audience check.
import { createObeliskMcpAuth } from "@obeliskgate/obelisk-auth/mcp";
const obelisk = createObeliskMcpAuth({
resource: "https://your-mcp.example.com/mcp", // issuer defaults to https://obeliskgate.com
requiredScopes: ["mcp:tools"], // optional
});
obelisk.metadataPath; // "/.well-known/oauth-protected-resource/mcp" (RFC 9728 §3.1)
obelisk.metadataResponse(req); // serve it there: 200 JSON, or 204 for a CORS preflight
const v = await obelisk.authenticate(req); // Web Request or Node IncomingMessage
if (!v.ok) return obelisk.unauthorizedResponse(v); // 401 / 403 / 503 with the challenge
v.authInfo; // MCP AuthInfo: { token, clientId, scopes, expiresAt, resource, extra: { sub, iss } }
// adapters
withMcpAuth(handler, obelisk.verifyToken, { required: true, resourceMetadataPath: obelisk.metadataPath }); // Vercel mcp-handler
app.use("/mcp", obelisk.nodeMiddleware()); // Express + the MCP TypeScript SDK (sets req.auth)A token is admitted only if it is an ES256 Obelisk access token for this
resource: right issuer, unexpired, aud equal to the resource, JWS typ an
access-token type, access-token shaped (an id_token is refused), with every
required scope. It is refused with a named reason otherwise:
audience-mismatch, not-an-access-token, unexpected-typ, expired,
insufficient-scope (403), and so on. A token with a cnf claim is refused as
sender-constrained, because the kit does not verify DPoP proofs. If discovery
or the JWKS cannot be fetched, the verdict is 503 verifier-unavailable and
nothing is admitted. The challenge text comes from a fixed vocabulary and never
echoes the request.
verifyToken (the mcp-handler adapter) returns undefined for every refusal,
including a missing scope, so mcp-handler answers 401 there. The adapters
follow the documented contracts of mcp-handler and the MCP TypeScript SDK; the
SDK's tests exercise those contracts, not a running app of either. The Python
twin, obelisk_auth.mcp, is tested end to end against FastMCP from the MCP
Python SDK.
Verify a receipt against the signed tree head
import { verifyReceiptInclusion } from "@obeliskgate/obelisk-auth";
const r = await verifyReceiptInclusion(receipt.currentHash, {
issuer: "https://obeliskgate.com",
receipt, // optional: the full ledger row you hold
// anchoredJkt: "...", // optional: the signing key's RFC 7638 thumbprint, obtained out of band
// jwks: pinnedJwks, // optional: a key set you obtained out of band
// maxAgeSec: 172800, // optional: refuse a head anchored longer ago than this
});
r.verdict; // "consistent" | "not-found" | "failed"
r.committed; // false — see below
r.trusts; // what the verdict still takes on the Gate's wordIt makes three GETs: /api/proof/<hash>, /.well-known/obelisk-transparency.json
and /.well-known/jwks.json. Redirects are refused. Network and HTTP failures
come back as results (reason: "unreachable:proof" and so on), never as
exceptions. Each check is reported on its own. A check that did not run is
{ checked: false, ok: null }, never a pass.
| check | what it verifies |
|---|---|
| head | ES256 signature of the Signed Tree Head against the JWKS, typ pinned to obelisk-sth+jwt, signed fields equal to the document's (no equivocation), optional key-thumbprint pin and freshness bound |
| proof | the Gate's index returned this hash at a position inside its chain |
| path | the Merkle path folds the leaf to the stated root |
| leaf | the leaf commits to this hash (needs receipt: its actor, action and timestamp form the leaf key) |
| body | the receipt you hold hashes to this hash, and its prevHash is the one the ledger has at that position (needs receipt) |
| anchor | the receipt's position against the ledger head the anchor store recorded; signed: true when that anchor recomputes to the signed headAnchorHash |
What it cannot prove yet. The signed head commits to the anchor store. It
does not commit to the Merkle root the path folds to. A path that folds shows the
proof is consistent with the Gate's own index, not that the receipt is in a tree
the Gate signed. So committed is always false in this version and trusts
always contains merkle-root. The codes in trusts:
merkle-root: the root the path reaches is not committed by the signed head.receipt-position: the index, kind and timestamp come from the unsigned proof response.leaf-binding: the leaf was not bound to this hash (noreceipt, or no leaf).receipt-body: the body was not checked against this hash (noreceipt).anchor-link: the anchored ledger head could not be linked to the signed head.signing-key: the key came from the Gate's own JWKS (passanchoredJktorjwksto remove this).
verifyReceiptProof({ hash, proof, transparency, jwks, ... }) runs the same
checks offline over documents you saved, and auth.verifyReceiptInclusion(hash)
is the same call bound to a client's issuer.
CAEP / Shared Signals (real-time security events)
Obelisk pushes RFC 8417 Security Event Tokens (session-revoked, credential-change,
assurance-level-change) to any RP that registers a caepPushUrl, and queues them
for POST /auth/caep/poll otherwise. Mount a verified receiver in one call:
const rx = await auth.caepReceiver({ handlers: {
"session-revoked": ({ event }) => endLocalSession(event.sub_id),
"credential-change": ({ event }) => refreshUserCredentials(event.sub_id),
}});
// behind your push endpoint (or feed it SETs drained from /auth/caep/poll):
const { status, body } = await rx.receive(rawRequestBody);
res.writeHead(status).end(body ? JSON.stringify(body) : undefined); // RFC 8935 ackSignature (ES256 against Obelisk's JWKS, rotation handled), issuer, audience,
freshness window, and jti replay are all enforced before your handler runs.
Duplicate deliveries ack 202 without re-dispatching (push is at-least-once),
and a replay-store outage acks 503 — retryable, never a 400 that could make
a transmitter drop the event.
Running multiple replicas behind one push URL? Inject an atomic claim against your shared store — one method by design, so replicas can't race:
const rx = await auth.caepReceiver({
handlers,
// return true iff THIS call won the jti; keep it stored ≥ ttlSec.
claimJti: (jti, ttlSec) => redis.set(`set:${jti}`, 1, "EX", ttlSec, "NX"),
});Lower-level pieces are exported too: verifySecurityEventToken,
createCaepReceiver, CAEP_EVENT_TYPES.
API keys (server-to-server)
// mint a scoped, expiring, revocable key (needs a Bearer access token or the console token)
POST /grants/mint { cap, scope, ttlMs } → { api_key, key_id, expires_at }
POST /grants/verify { api_key, scope } → { ok, cap, scope }
POST /grants/revoke { key_id } → { revoked: true }License
Proprietary — licensed, not sold, under the Obelisk Client SDK License Agreement (see LICENSE). This is not open source. You may install and use the SDK, unmodified, solely to integrate your application with the official Obelisk Gate Service. Forking, modification, redistribution, reverse engineering, and use with any other service are prohibited.
This package is a client SDK only. The Obelisk Gate service — the identity provider, the Obelisk Rating engine, the tamper-evident receipt chain, and the Warden risk engine — is a proprietary hosted service, is not part of or disclosed by this package, and is governed by the Gate Toll Terms at https://obeliskgate.com/legal/terms.
"Obelisk", "Obelisk Gate", and "VaultSpark" are trademarks of VaultSpark Studios LLC — see TRADEMARKS.md.
