Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

auth.ts

36 lines1.5 KB

1import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
2import { APIError } from "./protocol.js";
3import type { Config } from "./config.js";
4export type Identity = { id: string; expires: number };
5export type Authenticate = (request: Request) => Promise<Identity>;
6export function authentication(config: Config): Authenticate {
7 const jwks = createRemoteJWKSet(new URL(config.jwksURL));
8 return async (request) => {
9 const header = request.headers.get("authorization");
10 if (!header?.startsWith("Bearer "))
11 throw new APIError(401, "Sign in to this JOL server");
12 try {
13 const token = header.slice(7),
14 hint = decodeJwt(token);
15 // Session JWTs and OAuth resource tokens have distinct configured issuers.
16 // Unverified claims only select between these two fixed verification policies.
17 const oauth = hint.iss === config.authURL;
18 const { payload } = await jwtVerify(token, jwks, {
19 algorithms: ["EdDSA"],
20 issuer: oauth ? config.authURL : new URL(config.authURL).origin,
21 ...(oauth ? { audience: `${config.origin}/api` } : {}),
22 requiredClaims: ["sub", "exp", "iat"],
23 });
24 if (!payload.sub || !payload.exp) throw new Error("Missing claims");
25 return {
26 id: `${config.authURL}|${payload.sub}`,
27 expires: payload.exp * 1000,
28 };
29 } catch {
30 throw new APIError(
31 401,
32 "Your JOL sign-in has expired. Reconnect to continue.",
33 );
34 }
35 };