---
title: luna/auth
description: Check JWTs, bearer tokens, DPoP proofs, signed cookies, webhook signatures and password hashes in your lunas.
related:
  - /http/check-who-is-calling
  - /http/receive-webhooks
  - /sdk/errors
---

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

```ts luna/lunas/room.ts
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`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `jwks?` | `JwksKeySet` | - | A key set from `jwks()`. Give this or `key`, not both. |
| `key?` | `Secret \| Jwk` | - | An HS256 secret, or a public key as PEM text or a JWK. |
| `issuer?` | `string` | - | The `iss` the token must have. |
| `audience?` | `string \| string[]` | - | The token's `aud` must name at least one of these. |
| `algorithms?` | `JwtAlgorithm[]` | `["RS256", "ES256"]` | The algorithms allowed, and `["HS256"]` alone when `key` is a secret. |
| `clockSkewSeconds?` | `number` | `30` | How far `exp` and `nbf` may be off. |
| `requireExp?` | `boolean` | `true` | Refuses a token with no `exp` as `malformed`. |
| `now?` | `number` | - | The time in Unix seconds, for tests. |

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.

| Prop | Type | Default | Description |
| - | - | - | - |
| `url` | `string` | - | The provider's JWKS URL, `http` or `https`. |
| `options.timeoutSeconds?` | `number` | `5` | How long one fetch may take. |
| `options.fetch?` | `(url, init) => Promise<JwksResponse>` | - | Stands in for the global `fetch`. |
| `options.now?` | `() => number` | - | The time in Unix seconds, for tests. |

### JwtClaims

| Prop | Type | Default | Description |
| - | - | - | - |
| `iss?` | `string` | - | The issuer. |
| `sub?` | `string` | - | The subject, often the id of the person signed in. |
| `aud?` | `string \| string[]` | - | The audience. |
| `exp?` | `number` | - | When it expires, in Unix seconds. |
| `nbf?` | `number` | - | When it starts to hold, in Unix seconds. |
| `iat?` | `number` | - | When it was issued, in Unix seconds. |
| `[claim]?` | `unknown` | - | Any other claim the token carries. |

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

| Prop | Type | Default | Description |
| - | - | - | - |
| `code` | `JwtErrorCode` | - | Why it failed. |
| `message` | `string` | - | The code and a short reason. |
| `cause?` | `unknown` | - | The error underneath, such as a JWKS fetch that failed. |

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

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `string` | - | The text to sign. |
| `secret` | `Secret` | - | The signing secret, a non-empty string or bytes. |
| `options.maxAgeSeconds?` | `number` | - | How long the cookie holds, and with none, it never expires. |

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

| Prop | Type | Default | Description |
| - | - | - | - |
| `body` | `string \| Uint8Array` | - | The raw body, exactly as it arrived. |
| `signature` | `string` | - | The signature the sender put in a header. |
| `secret` | `Secret` | - | The secret you share with the sender. |
| `options.prefix?` | `string` | - | Text before the signature, such as `"sha256="`, which the signature must have. |
| `options.encoding?` | `"hex" \| "base64"` | `"hex"` | How the signature is written. |
| `options.timestamp?` | `string \| number` | - | The sender's timestamp in Unix seconds, and then `${timestamp}.${body}` is what was signed. |
| `options.toleranceSeconds?` | `number` | `300` | How far the timestamp may be from now, and when set, a timestamp is required. |

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

| Prop | Type | Default | Description |
| - | - | - | - |
| `dpop(request)` | `{ token: string; proof: string } \| null` | - | The access token and the proof of a DPoP-bound request. |
| `verifyDpop(proof, options)` | `Promise<DpopProof>` | - | Checks a proof for this request and returns who signed it, or throws a `JwtError`. |
| `jwkThumbprint(jwk)` | `string` | - | A public key's SHA-256 thumbprint, which a bound token's `cnf.jkt` names. |

`verifyDpop` takes these options.

| Prop | Type | Default | Description |
| - | - | - | - |
| `method` | `string` | - | The request's method. |
| `url` | `string` | - | The request's URL, whose query and fragment are ignored. |
| `accessToken?` | `string` | - | The access token sent with the proof, whose hash the proof must carry. |
| `jkt?` | `string` | - | The token's `cnf.jkt`: the proof must be signed by that key. |
| `nonce?` | `string` | - | The nonce your server last gave the client, if it requires one. |
| `maxAgeSeconds?` | `number` | `300` | How old a proof may be. |
| `clockSkewSeconds?` | `number` | `30` | How far in the future a proof may be. |
| `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`. |
| `now?` | `number` | - | The time in Unix seconds, for tests. |

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

### Types

| Prop | Type | Default | Description |
| - | - | - | - |
| `Secret?` | `string \| Uint8Array` | - | A shared secret. |
| `Jwk?` | `{ kty: string; [field: string]: unknown }` | - | A key in JWK form. |
| `JwtAlgorithm?` | `"RS256" \| "ES256" \| "HS256"` | - | An algorithm `verifyJwt` knows. |
| `JwtErrorCode?` | `string` | - | One of the codes in the table under `JwtError`. |
| `JwksResponse?` | `{ ok; status; headers; json() }` | - | What a stand-in `fetch` for `jwks` returns. |

## 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

```ts luna/lunas/shop.ts
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

```ts luna/lunas/user.ts
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

```ts luna/lunas/user.ts
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](/develop/store-secrets).
