Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

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.

PropType
jwks?JwksKeySet

A key set from `jwks()`. Give this or `key`, not both.

TypeJwksKeySet
key?Secret | Jwk

An HS256 secret, or a public key as PEM text or a JWK.

TypeSecret | Jwk
issuer?string

The `iss` the token must have.

Typestring
audience?string | string[]

The token's `aud` must name at least one of these.

Typestring | string[]
algorithms?JwtAlgorithm[]

The algorithms allowed, and `["HS256"]` alone when `key` is a secret.

TypeJwtAlgorithm[]
Default["RS256", "ES256"]
clockSkewSeconds?number

How far `exp` and `nbf` may be off.

Typenumber
Default30
requireExp?boolean

Refuses a token with no `exp` as `malformed`.

Typeboolean
Defaulttrue
now?number

The time in Unix seconds, for tests.

Typenumber

A 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.

PropType
urlstring

The provider's JWKS URL, `http` or `https`.

Typestring
options.timeoutSeconds?number

How long one fetch may take.

Typenumber
Default5
options.fetch?(url, init) => Promise<JwksResponse>

Stands in for the global `fetch`.

Type(url, init) => Promise<JwksResponse>
options.now?() => number

The time in Unix seconds, for tests.

Type() => number

JwtClaims

PropType
iss?string

The issuer.

Typestring
sub?string

The subject, often the id of the person signed in.

Typestring
aud?string | string[]

The audience.

Typestring | string[]
exp?number

When it expires, in Unix seconds.

Typenumber
nbf?number

When it starts to hold, in Unix seconds.

Typenumber
iat?number

When it was issued, in Unix seconds.

Typenumber
[claim]?unknown

Any other claim the token carries.

Typeunknown

JwtError

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).

PropType
codeJwtErrorCode

Why it failed.

TypeJwtErrorCode
messagestring

The code and a short reason.

Typestring
cause?unknown

The error underneath, such as a JWKS fetch that failed.

Typeunknown
code 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)

PropType
valuestring

The text to sign.

Typestring
secretSecret

The signing secret, a non-empty string or bytes.

TypeSecret
options.maxAgeSeconds?number

How long the cookie holds, and with none, it never expires.

Typenumber

signCookie 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.

PropType
bodystring | Uint8Array

The raw body, exactly as it arrived.

Typestring | Uint8Array
signaturestring

The signature the sender put in a header.

Typestring
secretSecret

The secret you share with the sender.

TypeSecret
options.prefix?string

Text before the signature, such as `"sha256="`, which the signature must have.

Typestring
options.encoding?"hex" | "base64"

How the signature is written.

Type"hex" | "base64"
Default"hex"
options.timestamp?string | number

The sender's timestamp in Unix seconds, and then `${timestamp}.${body}` is what was signed.

Typestring | number
options.toleranceSeconds?number

How far the timestamp may be from now, and when set, a timestamp is required.

Typenumber
Default300

hashPassword(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.

PropType
dpop(request){ token: string; proof: string } | null

The access token and the proof of a DPoP-bound request.

Type{ token: string; proof: string } | null
verifyDpop(proof, options)Promise<DpopProof>

Checks a proof for this request and returns who signed it, or throws a `JwtError`.

TypePromise<DpopProof>
jwkThumbprint(jwk)string

A public key's SHA-256 thumbprint, which a bound token's `cnf.jkt` names.

Typestring

verifyDpop takes these options.

PropType
methodstring

The request's method.

Typestring
urlstring

The request's URL, whose query and fragment are ignored.

Typestring
accessToken?string

The access token sent with the proof, whose hash the proof must carry.

Typestring
jkt?string

The token's `cnf.jkt`: the proof must be signed by that key.

Typestring
nonce?string

The nonce your server last gave the client, if it requires one.

Typestring
maxAgeSeconds?number

How old a proof may be.

Typenumber
Default300
clockSkewSeconds?number

How far in the future a proof may be.

Typenumber
Default30
remember?(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`.

Type(jti, expiresAt) => boolean | Promise<boolean>
now?number

The time in Unix seconds, for tests.

Typenumber

A DpopProof is { jkt, jwk, jti, iat }: the signing key’s thumbprint, the key, the proof’s id and when it was made.

Types

PropType
Secret?string | Uint8Array

A shared secret.

Typestring | Uint8Array
Jwk?{ kty: string; [field: string]: unknown }

A key in JWK form.

Type{ kty: string; [field: string]: unknown }
JwtAlgorithm?"RS256" | "ES256" | "HS256"

An algorithm `verifyJwt` knows.

Type"RS256" | "ES256" | "HS256"
JwtErrorCode?string

One of the codes in the table under `JwtError`.

Typestring
JwksResponse?{ ok; status; headers; json() }

What a stand-in `fetch` for `jwks` returns.

Type{ ok; status; headers; json() }

Good to know

  • A key set caches its keys for the max-age the provider sends, 10 minutes without one, and never less than 30 seconds.
  • A token whose kid the 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: none is always refused.
  • Text that is a PEM or JWK public key is never used as an HS256 secret.
  • A wrong option, such as both jwks and key, throws a TypeError rather than a JwtError.
  • 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.

Was this page helpful?