Skip to content

@xid-kit/backend

Networkless JWT verification, request authentication, and webhook signature validation for edge and server runtimes.

Runtime support

Registry status: UNPUBLISHED. Install this SDK only from the repository source checkout; do not use an external package registry.

  • Cloudflare Workers (primary target)
  • Vercel Edge Runtime and Node.js server runtimes
  • Any Web Crypto compatible runtime (Bun, Deno)

authenticateRequest

Verify a Bearer or explicit application JWT from an incoming Request. A same-origin Core browser session is first exchanged through /v1/sessions/token; its opaque refresh cookie is never verified locally.

import { authenticateRequest } from '@xid-kit/backend'

const state = await authenticateRequest(request, {
  jwtKey: env.XID_JWKS_PUBLIC_KEY,
  issuer: 'https://xid.dev',
  sessionTokenExchange: { endpoint: '/v1/sessions/token' },
})
if (state.isSignedIn) {
  console.log(state.userId)
}

verifyToken

Low-level access token verification. Pass jwtKey from JWKS to skip network round-trips on cold start. Expected failures return a Result type, not an exception.

import { verifyToken } from '@xid-kit/backend'

const result = await verifyToken(token, {
  jwtKey: env.XID_JWKS_PUBLIC_KEY,
  issuer: 'https://xid.dev',
  audience: 'my-api',
})
if (!result.ok) return new Response('Unauthorized', { status: 401 })

verifyWebhook

Validates Svix-style webhook signatures (svix-id, svix-timestamp, svix-signature) with a five-minute replay window.

import { verifyWebhook } from '@xid-kit/backend'

const result = await verifyWebhook(request, {
  secret: env.XID_WEBHOOK_SECRET,
})
if (!result.ok) {
  return new Response('Invalid webhook', { status: 400 })
}
const { type, data } = result.value.payload

Exported API

Export Kind Purpose
authenticateRequest function Verify Bearer or explicit app JWT credentials, with optional same-origin Core session exchange
exchangeSessionToken function Forward Core opaque cookies only to an exact same-origin session-token endpoint; the value is never verified locally
verifyToken function Low-level access token verification: signature, exp, nbf, iss, aud, azp
verifyWebhook function Svix-style HMAC-SHA256 webhook signature validation with 5-minute replay window
toVerifyKeySet function Convert JwtKey (JWK, JWKS, or CryptoKey) to VerifyKeySet for verification
JwksCache class Optional network-fetching JWKS cache with configurable TTL (default 3600 s); use only when jwtKey is not pre-loaded
AppError class Thrown for unrecoverable SDK errors: missing JWT key, JWKS fetch failure, invalid options, session-token exchange failure
BACKEND_ERROR_CODES as const tuple All BackendErrorCode values: missing_jwt_key, jwks_fetch_failed, invalid_options, session_token_exchange_failed
PACKAGE string constant Package name identifier ‘@xid-kit/backend’

Types

Type Description
JwtKey Accepted public key forms: PublicJwk, Jwks, or { alg, publicKey: CryptoKey }
JwksCacheOptions Constructor options for JwksCache: jwksUri, ttlSec, fetchFn
VerifyTokenOptions Options for verifyToken: jwtKey, issuer, audience, authorizedParties, clockToleranceSec, now
VerifyTokenError Structured error returned when token verification fails (expected failure; not thrown)
AuthenticateRequestOptions Options for authenticateRequest: jwtKey, issuer, audience, authorizedParties, clockToleranceSec, now, jwtCookieName, sessionTokenExchange
RequestState Discriminated union of SignedInState and SignedOutState
SignedInState Valid signed JWT state with userId, optional sessionId, and verified claims
SignedOutState No valid token present; reason field indicates cause
VerifyWebhookOptions Options for verifyWebhook: secret, toleranceSec (replay window seconds)
WebhookVerifyError Structured error for missing headers, invalid signatures, replay, or invalid payloads
VerifiedWebhook Verified message metadata and a typed type/data payload envelope
BackendErrorCode Union of BACKEND_ERROR_CODES values

Security boundaries

  • Uses public JWKS only. Never loads instance signing private keys.
  • Verification uses Web Crypto via @xid-kit/crypto.
  • Expected failures return Result types; unexpected errors throw AppError.
Navigation

Type to search...

Use arrow keys to navigateEnter to selectEscape to close