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

Check who is calling

Check the token your app's users sign in with, and give each call the caller's identity.

Luna does not sign your app’s users in. A publishable key says which app is calling, not which person, so a luna that trusts it alone lets anyone act as anyone.

Your app signs its users in with the provider of your choice and sends their token with each call. The luna checks the token in a hook, and every handler then knows who called.

Return the caller from onBeforeConnect

onBeforeConnect runs before each request from outside Luna reaches a luna. What it returns becomes ctx.caller.external in the handler. Here it checks a JWT with verifyJwt from luna/auth.

import { defineLuna, t, table } from "luna";
import { bearer, jwks, verifyJwt } from "luna/auth";

const keys = jwks("https://auth.example.com/.well-known/jwks.json");

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string(), by: t.string() }) },
  hooks: {
    async onBeforeConnect(ctx, request) {
      const token = bearer(request.headers.authorization) ?? request.query.token;
      if (!token) ctx.fail("SignIn");
      const claims = await verifyJwt(token, { jwks: keys, issuer: "https://auth.example.com/" });
      return { userId: claims.sub };
    },
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      const { userId } = ("external" in ctx.caller ? ctx.caller.external : {}) as { userId: string };
      ctx.db.items.insert({ text, by: userId });
    }),
  }),
});

ctx.fail(code) in the hook refuses the request with 403 and that code. A JwtError thrown by verifyJwt does the same with its own code, such as expired. A hook may fail with any code, without declaring it.

The hook runs before each call over HTTP and once when an app’s connection opens. Every call over that connection carries the identity it opened with, which is also the connection’s auth. Calls between lunas, schedules and routes skip the hook.

request field Holds
method, path The request’s method and path
headers Its headers, with lower-case names
query Its query parameters
handler The handler it calls
apiToken true when it carries a secret token, from one of your own servers

Send the token from an app

An app built on createClient passes the token in params. The client asks for them again on every reconnect, so a refreshed token is picked up.

import { createClient } from "luna/client";

export function connectAs(getToken: () => Promise<string>) {
  return createClient({
    url: process.env.LUNA_URL!,
    key: process.env.LUNA_KEY,
    params: async () => ({ token: await getToken() }),
  });
}

Over plain HTTP, send the token as Authorization: Bearer beside the publishable key.

curl -X POST "$LUNA_URL/List/groceries/add" \
  -H "luna-key: $LUNA_KEY" \
  -H "Authorization: Bearer <USER_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"text":"milk"}'

Choose how a JWT is checked

Option Does
jwks A key set from jwks(url). Give this or key
key An HS256 secret, or a public key as PEM or JWK
issuer The iss the token must have
audience One or more values, at least one of which the token’s aud must hold
algorithms RS256 and ES256 by default, or HS256 alone when key is a secret
clockSkewSeconds How far clocks may differ for exp and nbf, 30 seconds by default
requireExp Refuses a token with no exp, true by default

Make one jwks(url) for each issuer at the top of the file, since its cache lives as long as the object. It keeps the keys for the response’s max-age, or 10 minutes without one, and for at least 30 seconds. A token whose key it does not know makes it fetch again, at most once every 30 seconds, so a provider’s new key works at once.

A token that fails throws a JwtError, whose code is one of these. A mistake in the options throws a TypeError instead.

Code The token
malformed Is not a JWT, or lacks exp
bad_signature Has a signature that does not match
expired, not_yet_valid Is outside its exp or nbf
wrong_issuer, wrong_audience Has another iss, or no aud you allow
unknown_key Names a key the key set does not have
bad_algorithm Uses an algorithm you do not allow
bad_proof, replayed Has a DPoP proof that does not fit, or was used before

Check the caller in a route

Routes skip onBeforeConnect, and a stateless luna has no hooks. A route with auth: "none" checks the request in its handler.

me: h({ args: t.request(), route: { path: "GET /me", auth: "none" } }, async (ctx, req) => {
  const token = bearer(req);
  const claims = token ? await verifyJwt(token, { jwks: keys }).catch(() => null) : null;
  if (!claims) return new Response(null, { status: 401, headers: { "www-authenticate": "Bearer" } });
  return { userId: claims.sub };
}),

Catch the JwtError here. A handler that fails with a code it does not declare is answered as Internal.

signCookie(value, secret, { maxAgeSeconds }) signs a value and its expiry into text you can set as a cookie. verifyCookie(signed, secret) returns the value, or null when the cookie was changed or has expired.

A sign-in route sets the cookie on its answer.

const session = signCookie(userId, ctx.env.COOKIE_SECRET!, { maxAgeSeconds: 86_400 });
return new Response(null, { status: 204, headers: { "set-cookie": `session=${session}; HttpOnly; Secure; Path=/` } });

onBeforeConnect reads it back from the cookie header.

const session = /(?:^|; )session=([^;]+)/.exec(request.headers.cookie ?? "")?.[1] ?? "";
const userId = verifyCookie(session, [ctx.env.COOKIE_SECRET!, ctx.env.OLD_COOKIE_SECRET!]);
if (!userId) ctx.fail("SignIn");

Pass a list of secrets to verifyCookie while you change secrets. A cookie signed with any of them is accepted.

Keep your own passwords

For an app that keeps its own logins, hashPassword turns a password into a scrypt hash to store in its place. verifyPassword says whether a password is the one the hash came from.

const hash = await hashPassword(password);
const ok = await verifyPassword(attempt, hash);

The hash carries its own salt and settings as one string. Python’s luna.auth reads and writes the same strings, so lunas in both languages share them. See Write lunas in Python.

Check a DPoP proof

A DPoP-bound token comes as Authorization: DPoP <token> with a DPoP header holding a proof. dpop(req) returns both, and verifyDpop(proof, options) checks the proof against the request’s method and url. Pass accessToken, the token’s cnf.jkt as jkt, and a remember function that stores each proof’s jti, so a proof used twice fails with replayed.

Next steps

Was this page helpful?