@edgetime/auth
Sealed tokens, bearer and OAuth resource-server helpers and scope checks on Web Crypto, plus JWT verification and encrypted sessions on jose.
npm install @edgetime/authAuthentication helpers on Web Crypto. The main entry point has no dependencies; /jwt and
/session use jose.
| Entry point | Contents |
|---|---|
@edgetime/auth |
Sealed tokens, bearer and OAuth resource-server helpers, scope checks, encoding |
@edgetime/auth/jwt |
JWT verification and router middleware |
@edgetime/auth/session |
Encrypted cookie sessions |
import { type AuthInfo, requireScopes } from '@edgetime/auth';import { createJwtVerifier, jwtAuth } from '@edgetime/auth/jwt';import { perEnv, Router } from '@edgetime/router';
type App = { env: Env; vars: { auth: AuthInfo } };
const verifier = perEnv((env: Env) => createJwtVerifier({ keys: { jwksUrl: `${env.ISSUER}/.well-known/jwks.json` }, issuer: env.ISSUER, audience: env.AUDIENCE, }),);
const api = new Router<App>() .use(jwtAuth<App>({ verifier: (c) => verifier(c.env) })) .get('/me', (c) => c.json({ subject: c.get('auth').subject })) .post('/orders', requireScopes('orders:write'), createOrder);createJwtVerifier(options) returns (token) => Promise<claims>. It throws a 401 HttpError
for a token that fails verification and a 503 when the signing keys cannot be fetched, so an
outage at the issuer does not tell clients their tokens are bad. Creating a verifier throws if
issuer or audience is missing or empty.
| Option | Default | Purpose |
|---|---|---|
keys |
required | { jwksUrl } (https, or http on localhost), { secret }, { key } or a jose key resolver. Never taken from the token. A resolver that throws counts as an outage (503); to refuse a token whose key it does not know, throw jose’s JWKSNoMatchingKey. |
issuer, audience |
required | Expected iss and aud. |
algorithms |
HS256 for a secret; otherwise RS256, ES256, EdDSA |
Accepted signature algorithms. |
typ |
any | Expected typ header. Set at+jwt when the issuer marks access tokens that way (RFC 9068), so an ID token from the same issuer cannot stand in for one. |
requiredClaims |
exp, sub |
Further claims that must be present. |
clockTolerance |
5 |
Allowed clock skew in seconds. |
maxTokenLength |
8192 |
Longer tokens are refused before parsing. |
maxTokenAge |
none | The oldest token accepted, from its iat: seconds, or a duration such as '1h' or '30 minutes'. When set, iat is required. A value jose would not understand throws when the verifier is built. |
jwtAuth({ verifier, token?, challenge?, subject? }) reads the token from Authorization: Bearer
(or from token(c)), verifies it and stores { subject, scopes, claims } as the auth var. A
missing or invalid token gets 401 with a WWW-Authenticate challenge. The subject is the sub
claim unless subject(claims) picks another; an empty one is refused.
Its callbacks fail closed. A token or subject function that throws answers 401, and a
verifier function that throws or returns no verifier answers 503, unless the callback threw
an HttpError of its own.
A JWT or session token is accepted in one spelling only. A copy that differs just in the unused trailing bits of a base64url part is refused, so tokens can safely be compared or revoked by their text.
requireScopes(...scopes) answers 403 with an insufficient_scope challenge unless the caller
holds every scope. Scopes come from the scope or scp claim. Each name must be a scope token
(printable ASCII without spaces, quotes or backslashes), or it throws when the middleware is
made.
OAuth resource server
Section titled “OAuth resource server”| Export | Purpose |
|---|---|
bearerToken(request) |
The credential from Authorization: Bearer. |
bearerChallenge(challenge) |
A WWW-Authenticate: Bearer value (RFC 6750). |
unauthorized(challenge?, detail?) |
A 401 HttpError carrying the challenge. |
protectedResourceMetadata(metadata) |
The RFC 9728 metadata response; serve it at PROTECTED_RESOURCE_PATH. |
Sealed tokens
Section titled “Sealed tokens”seal signs a JSON value for one audience until an expiry; unseal returns it, or undefined
when the signature, audience or expiry does not hold. The value is signed with HMAC-SHA256, not
encrypted, so do not put secrets in it. Both throw when the key or the audience is missing, so
an unset variable is never mistaken for an invalid token.
import { seal, unseal } from '@edgetime/auth';
const expires = Math.floor(Date.now() / 1000) + 600;const token = await seal(env.SEAL_KEY, 'download', { file: 'report.pdf' }, expires);const grant = await unseal<{ file: string }>(token, 'download', env.SEAL_KEY, [env.SEAL_KEY_OLD]);A key is a string or anything with get(): Promise<string>, such as a secret-store client. To
rotate, deploy the new key and pass the old one in the previous list until its seals expire.
A secret read through get() is reused for up to a minute, per key object, by seals and sessions
alike; a changed secret is picked up within that minute. A read that fails or returns fewer than
32 characters is not remembered.
Sessions
Section titled “Sessions”createSessionCodec<T>(options) keeps session data in an encrypted cookie (JWE, dir with
A256GCM). Nothing is stored server-side, so a session cannot be revoked before it expires. The
encryption key is derived from the secret and the cookie name, so two codecs with the same secret
and different names cannot read each other’s sessions. Sealing data that would not fit in a cookie
(more than 4096 characters once encrypted, counting the cookie name) throws instead of producing a cookie browsers drop.
import { createSessionCodec } from '@edgetime/auth/session';
const sessions = createSessionCodec<{ userId: string }>({ secret: env.SESSION_SECRET, ttl: 3600 });
const session = await sessions.read(c.req);headers.append('set-cookie', await sessions.cookie({ userId }));headers.append('set-cookie', sessions.clear());| Option | Default | Purpose |
|---|---|---|
secret |
required | The secret the encryption key is derived from. |
previous |
none | Retired secrets still accepted when reading. |
ttl |
required | Lifetime in whole seconds, 1 or more, for both the token and the cookie. |
name |
__Host-session |
Cookie name. |
cookie |
secure defaults | Cookie attributes, as in @edgetime/http. |
Encoding
Section titled “Encoding”base64urlEncode, base64urlDecode, hexEncode, sha256Hex, randomToken(bytes = 32) and
timingSafeEqual(a, b), which compares two secrets in constant time. It throws unless both are
strings and returns false when either is empty, so two missing values never match.
randomToken takes 16 to 1024 bytes.
Source: packages/auth on GitHub.