luna/auth
Check JWTs, bearer tokens, DPoP proofs, signed cookies, webhook signatures and password hashes in your lunas.
luna/auth checks what an outside sign-in provider or sender hands your app: JWTs, bearer tokens, DPoP proofs, signed cookies and webhook signatures. It also hashes passwords for apps that keep their own logins.
import { defineLuna, t } from "luna";
import { bearer, jwks, verifyJwt } from "luna/auth";
const keys = jwks("https://auth.example.com/.well-known/jwks.json");
export const Room = defineLuna({
name: "Room",
visibility: "public",
key: { id: t.string() },
hooks: {
onBeforeConnect: async (ctx, request) => {
const token = bearer(request.headers.authorization);
if (!token) return ctx.fail("Unauthorized");
const claims = await verifyJwt(token, { jwks: keys, issuer: "https://auth.example.com", audience: "chat" });
return { user: claims.sub };
},
},
handlers: (h) => ({
whoami: h({}, (ctx) => ctx.caller),
}),
});
Luna has no users or sign-in of its own. These functions are the pieces to check someone else’s.
Reference
verifyJwt(token, options)
Verifies a JWT and returns its claims as Promise<JwtClaims>, or throws a JwtError.
jwks?JwksKeySet
A key set from `jwks()`. Give this or `key`, not both.
JwksKeySetkey?Secret | Jwk
An HS256 secret, or a public key as PEM text or a JWK.
Secret | Jwkissuer?string
The `iss` the token must have.
stringaudience?string | string[]
The token's `aud` must name at least one of these.
string | string[]algorithms?JwtAlgorithm[]
The algorithms allowed, and `["HS256"]` alone when `key` is a secret.
JwtAlgorithm[]["RS256", "ES256"]clockSkewSeconds?number
How far `exp` and `nbf` may be off.
number30requireExp?boolean
Refuses a token with no `exp` as `malformed`.
booleantruenow?number
The time in Unix seconds, for tests.
numberA public key must be RSA of 2048 bits or more, or EC on P-256. JwtAlgorithm is "RS256" | "ES256" | "HS256".
jwks(url, options)
Returns a JwksKeySet: a provider’s public keys, fetched when needed and cached. Make one per issuer at module level, since the cache lives as long as the object.
urlstring
The provider's JWKS URL, `http` or `https`.
stringoptions.timeoutSeconds?number
How long one fetch may take.
number5options.fetch?(url, init) => Promise<JwksResponse>
Stands in for the global `fetch`.
(url, init) => Promise<JwksResponse>options.now?() => number
The time in Unix seconds, for tests.
() => numberJwtClaims
iss?string
The issuer.
stringsub?string
The subject, often the id of the person signed in.
stringaud?string | string[]
The audience.
string | string[]exp?number
When it expires, in Unix seconds.
numbernbf?number
When it starts to hold, in Unix seconds.
numberiat?number
When it was issued, in Unix seconds.
number[claim]?unknown
Any other claim the token carries.
unknownJwtError
A token or proof that did not verify. It extends LunaError, so when onBeforeConnect lets it through, the caller is refused with its code, as with ctx.fail(code).
codeJwtErrorCode
Why it failed.
JwtErrorCodemessagestring
The code and a short reason.
stringcause?unknown
The error underneath, such as a JWKS fetch that failed.
unknowncode |
Means |
|---|---|
malformed |
Not a JWT, a bad encoding, a missing or wrong claim, or a crit header |
bad_signature |
The signature does not match |
expired |
Past exp, or a DPoP proof older than maxAgeSeconds |
not_yet_valid |
Before nbf, or a DPoP proof from the future |
wrong_issuer |
iss is not issuer |
wrong_audience |
aud names none of audience |
unknown_key |
No key in the set fits the token’s kid |
bad_algorithm |
An algorithm that is not allowed, or that the key cannot verify |
bad_proof |
A DPoP proof that does not fit the request |
replayed |
A DPoP proof that was used before |
bearer(from)
Returns the token in Authorization: Bearer <token>, or null. from is a request with headers.get, or the header’s value as a string.
signCookie(value, secret, options) and verifyCookie(signed, secret, options)
valuestring
The text to sign.
stringsecretSecret
The signing secret, a non-empty string or bytes.
Secretoptions.maxAgeSeconds?number
How long the cookie holds, and with none, it never expires.
numbersignCookie returns a string of letters, digits, _, . and -, safe as a cookie value. verifyCookie returns the value, or null if the cookie is not genuine or has expired. Give it a list of secrets to accept any of them while you rotate.
verifyWebhook(body, signature, secret, options)
Returns whether signature is the HMAC-SHA256 of the raw request body.
bodystring | Uint8Array
The raw body, exactly as it arrived.
string | Uint8Arraysignaturestring
The signature the sender put in a header.
stringsecretSecret
The secret you share with the sender.
Secretoptions.prefix?string
Text before the signature, such as `"sha256="`, which the signature must have.
stringoptions.encoding?"hex" | "base64"
How the signature is written.
"hex" | "base64""hex"options.timestamp?string | number
The sender's timestamp in Unix seconds, and then `${timestamp}.${body}` is what was signed.
string | numberoptions.toleranceSeconds?number
How far the timestamp may be from now, and when set, a timestamp is required.
number300hashPassword(password) and verifyPassword(password, hash)
hashPassword returns a hash to keep in place of the password, as one string with its own parameters: scrypt$N$r$p$salt$hash. verifyPassword returns whether a password is the one the hash was made from, and false for a hash it cannot read. Python’s luna.auth reads and writes the same strings.
DPoP
A DPoP-bound request sends Authorization: DPoP <token> and a proof in the DPoP header.
dpop(request){ token: string; proof: string } | null
The access token and the proof of a DPoP-bound request.
{ token: string; proof: string } | nullverifyDpop(proof, options)Promise<DpopProof>
Checks a proof for this request and returns who signed it, or throws a `JwtError`.
Promise<DpopProof>jwkThumbprint(jwk)string
A public key's SHA-256 thumbprint, which a bound token's `cnf.jkt` names.
stringverifyDpop takes these options.
methodstring
The request's method.
stringurlstring
The request's URL, whose query and fragment are ignored.
stringaccessToken?string
The access token sent with the proof, whose hash the proof must carry.
stringjkt?string
The token's `cnf.jkt`: the proof must be signed by that key.
stringnonce?string
The nonce your server last gave the client, if it requires one.
stringmaxAgeSeconds?number
How old a proof may be.
number300clockSkewSeconds?number
How far in the future a proof may be.
number30remember?(jti, expiresAt) => boolean | Promise<boolean>
Keeps a proof's `jti` until `expiresAt` and says whether it was new, and `false` refuses the proof as `replayed`.
(jti, expiresAt) => boolean | Promise<boolean>now?number
The time in Unix seconds, for tests.
numberA DpopProof is { jkt, jwk, jti, iat }: the signing key’s thumbprint, the key, the proof’s id and when it was made.
Types
Secret?string | Uint8Array
A shared secret.
string | Uint8ArrayJwk?{ kty: string; [field: string]: unknown }
A key in JWK form.
{ kty: string; [field: string]: unknown }JwtAlgorithm?"RS256" | "ES256" | "HS256"
An algorithm `verifyJwt` knows.
"RS256" | "ES256" | "HS256"JwtErrorCode?string
One of the codes in the table under `JwtError`.
stringJwksResponse?{ ok; status; headers; json() }
What a stand-in `fetch` for `jwks` returns.
{ ok; status; headers; json() }Good to know
- A key set caches its keys for the
max-agethe provider sends, 10 minutes without one, and never less than 30 seconds. - A token whose
kidthe cache does not know fetches the keys again, at most once every 30 seconds. A rotated key works at once. - When a fetch fails, the key set keeps the keys it had and waits 30 seconds before it tries again.
- A key set cannot verify HS256 tokens, and
alg: noneis always refused. - Text that is a PEM or JWK public key is never used as an HS256 secret.
- A wrong option, such as both
jwksandkey, throws aTypeErrorrather than aJwtError. - A webhook signature is checked against the raw body. Read it with
req.text()before you parse it.
Examples
Check a webhook’s signature
import { defineLuna, t } from "luna";
import { verifyWebhook } from "luna/auth";
export const Shop = defineLuna({
name: "Shop",
key: { id: t.string() },
handlers: (h) => ({
paid: h({ args: t.request(), route: { path: "POST /shops/:id/paid", auth: "none" } }, async (ctx, req) => {
const body = await req.text();
const ok = verifyWebhook(body, req.headers.get("x-signature") ?? "", ctx.env.PAYMENTS_SECRET, {
prefix: "sha256=",
timestamp: req.headers.get("x-timestamp") ?? undefined,
});
if (!ok) return new Response("bad signature", { status: 401 });
ctx.send(Shop, { id: ctx.key.id }).settle({ event: JSON.parse(body) });
return new Response(null, { status: 204 });
}),
settle: h({ args: { event: t.json() } }, () => {}),
}),
});
Keep your own logins
import { defineLuna, t, table } from "luna";
import { hashPassword, signCookie, verifyCookie, verifyPassword } from "luna/auth";
export const User = defineLuna({
name: "User",
key: { id: t.string() },
schema: { login: table({ hash: t.string() }, { singleRow: true }) },
handlers: (h) => ({
setPassword: h({ args: { password: t.string() } }, async (ctx, { password }) => {
ctx.db.login.set({ hash: await hashPassword(password) });
}),
logIn: h({ args: { password: t.string() }, errors: { WrongPassword: t.json() } }, async (ctx, { password }) => {
const row = ctx.db.login.get();
if (!row || !(await verifyPassword(password, row.hash))) ctx.fail("WrongPassword");
return signCookie(ctx.key.id, ctx.env.COOKIE_SECRET, { maxAgeSeconds: 86_400 });
}),
}),
});
Accept cookies signed by an old secret
session: h({ args: { cookie: t.string() } }, (ctx, { cookie }) =>
verifyCookie(cookie, [ctx.env.COOKIE_SECRET, ctx.env.OLD_COOKIE_SECRET]),
),
Set both secrets with luna secrets set. See Store secrets.