authlet 0.0.0-stage → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ import { getBrowserUser, toConsentPage } from "../context.js";
2
+ import { redirect, withParams } from "../http.js";
3
+ /** The consent behind a sealed value, if it is valid and shown to the user signed in now. */
4
+ const loadConsent = async (ctx, value) => {
5
+ const { issuer } = ctx.urls;
6
+ const consent = await ctx.sealer.unseal({ issuer, type: "consent", value });
7
+ const client = consent &&
8
+ (await ctx.sealer.unseal({
9
+ issuer,
10
+ type: "client",
11
+ value: consent.clientId,
12
+ }));
13
+ const user = await getBrowserUser(ctx);
14
+ if (!consent || !client || user?.id !== consent.userId) {
15
+ return null;
16
+ }
17
+ return {
18
+ consent,
19
+ client: {
20
+ id: consent.clientId,
21
+ name: client.name,
22
+ redirectUri: consent.redirectUri,
23
+ },
24
+ user,
25
+ };
26
+ };
27
+ const readConsent = async (ctx, value) => {
28
+ const loaded = await loadConsent(ctx, value);
29
+ return (loaded && {
30
+ client: loaded.client,
31
+ user: loaded.user,
32
+ resource: loaded.consent.resource,
33
+ });
34
+ };
35
+ /**
36
+ * Whether the request is a top-level form submission from this site. The consent page may be
37
+ * framed by other sites or copied to them; browsers send `Sec-Fetch-*` headers to tell. Older
38
+ * browsers without them must at least send no foreign `Origin`: the request's own origin, or
39
+ * the issuer's for requests that reach the app through a proxy. The consent page should also
40
+ * refuse to be framed.
41
+ */
42
+ const isSameOriginNavigation = (req, issuer) => {
43
+ const destination = req.headers.get("Sec-Fetch-Dest");
44
+ const site = req.headers.get("Sec-Fetch-Site");
45
+ const origin = req.headers.get("Origin");
46
+ if (destination && destination !== "document") {
47
+ return false;
48
+ }
49
+ if (site) {
50
+ return site === "same-origin";
51
+ }
52
+ return (!origin ||
53
+ origin === new URL(req.url).origin ||
54
+ origin === new URL(issuer).origin);
55
+ };
56
+ const decide = async (ctx, args) => {
57
+ if (!isSameOriginNavigation(ctx.req, ctx.urls.issuer)) {
58
+ return new Response(null, { status: 403 });
59
+ }
60
+ const loaded = await loadConsent(ctx, args.consent);
61
+ if (!loaded) {
62
+ return toConsentPage(ctx, { error: "expired" }, 303);
63
+ }
64
+ const { consent, client, user } = loaded;
65
+ // `iss` lets clients that use several authorization servers tell which one answered (RFC 9207).
66
+ const toClient = (params) => redirect(withParams(consent.redirectUri, {
67
+ ...params,
68
+ iss: ctx.urls.issuer,
69
+ state: consent.state,
70
+ }), 303);
71
+ if (!args.allow) {
72
+ return toClient({ error: "access_denied" });
73
+ }
74
+ const issued = await ctx.options.tokens.issue({
75
+ user,
76
+ client,
77
+ grant: args.grant,
78
+ resource: consent.resource,
79
+ });
80
+ if (!issued) {
81
+ return toConsentPage(ctx, { error: "forbidden" }, 303);
82
+ }
83
+ const code = await ctx.sealer.seal({
84
+ issuer: ctx.urls.issuer,
85
+ type: "code",
86
+ data: {
87
+ clientId: consent.clientId,
88
+ redirectUri: consent.redirectUri,
89
+ codeChallenge: consent.codeChallenge,
90
+ resource: consent.resource,
91
+ refreshToken: issued.refreshToken,
92
+ },
93
+ });
94
+ return toClient({ code });
95
+ };
96
+ export { decide, readConsent };
@@ -0,0 +1,11 @@
1
+ import type { AuthletUrls } from "../urls.js";
2
+ /**
3
+ * Authorization server metadata (RFC 8414), served at every discovery location. It also
4
+ * carries the fields OpenID discovery requires, since MCP clients may read it from
5
+ * `openid-configuration`; no ID tokens are issued.
6
+ */
7
+ declare const authorizationServerMetadata: (urls: AuthletUrls) => Response;
8
+ /** Protected resource metadata (RFC 9728) for the MCP endpoint. */
9
+ declare const resourceMetadata: (urls: AuthletUrls) => Response;
10
+ declare const jwks: () => Response;
11
+ export { authorizationServerMetadata, jwks, resourceMetadata };
@@ -0,0 +1,28 @@
1
+ import { json } from "../http.js";
2
+ /**
3
+ * Authorization server metadata (RFC 8414), served at every discovery location. It also
4
+ * carries the fields OpenID discovery requires, since MCP clients may read it from
5
+ * `openid-configuration`; no ID tokens are issued.
6
+ */
7
+ const authorizationServerMetadata = (urls) => json({
8
+ issuer: urls.issuer,
9
+ authorization_endpoint: urls.authorizationEndpoint,
10
+ token_endpoint: urls.tokenEndpoint,
11
+ registration_endpoint: urls.registrationEndpoint,
12
+ jwks_uri: urls.jwksUri,
13
+ response_types_supported: ["code"],
14
+ grant_types_supported: ["authorization_code", "refresh_token"],
15
+ code_challenge_methods_supported: ["S256"],
16
+ token_endpoint_auth_methods_supported: ["none"],
17
+ authorization_response_iss_parameter_supported: true,
18
+ subject_types_supported: ["public"],
19
+ id_token_signing_alg_values_supported: ["RS256"],
20
+ });
21
+ /** Protected resource metadata (RFC 9728) for the MCP endpoint. */
22
+ const resourceMetadata = (urls) => json({
23
+ resource: urls.resource,
24
+ authorization_servers: [urls.issuer],
25
+ bearer_methods_supported: ["header"],
26
+ });
27
+ const jwks = () => json({ keys: [] });
28
+ export { authorizationServerMetadata, jwks, resourceMetadata };
@@ -0,0 +1,9 @@
1
+ import type { Context } from "../context.js";
2
+ import type { AuthletUser } from "../types.js";
3
+ /**
4
+ * Dynamic client registration (RFC 7591) for public clients. Nothing is stored: the client's
5
+ * name and redirect URIs are sealed into its `client_id`. Requested auth methods, grant and
6
+ * response types are replaced by the only ones supported, as section 3.2.1 allows.
7
+ */
8
+ declare const register: ({ req, urls, sealer, }: Pick<Context<unknown, AuthletUser>, "req" | "urls" | "sealer">) => Promise<Response>;
9
+ export { register };
@@ -0,0 +1,51 @@
1
+ import { json, oauthError, readBody } from "../http.js";
2
+ import { isValidRedirectUri } from "../redirect-uri.js";
3
+ const parseJson = (text) => {
4
+ try {
5
+ return JSON.parse(text);
6
+ }
7
+ catch {
8
+ return null;
9
+ }
10
+ };
11
+ const DEFAULT_CLIENT_NAME = "An MCP client";
12
+ /** Limits that keep the sealed `client_id` short enough to travel in URLs. */
13
+ const MAX_NAME_LENGTH = 100;
14
+ const MAX_REDIRECT_URIS = 10;
15
+ /**
16
+ * Dynamic client registration (RFC 7591) for public clients. Nothing is stored: the client's
17
+ * name and redirect URIs are sealed into its `client_id`. Requested auth methods, grant and
18
+ * response types are replaced by the only ones supported, as section 3.2.1 allows.
19
+ */
20
+ const register = async ({ req, urls, sealer, }) => {
21
+ const text = await readBody(req);
22
+ const body = text === null ? null : parseJson(text);
23
+ if (typeof body !== "object" || body === null) {
24
+ return oauthError("invalid_client_metadata");
25
+ }
26
+ const { client_name: clientName, redirect_uris: redirectUris } = body;
27
+ if (!Array.isArray(redirectUris) ||
28
+ redirectUris.length === 0 ||
29
+ redirectUris.length > MAX_REDIRECT_URIS ||
30
+ !redirectUris.every(isValidRedirectUri)) {
31
+ return oauthError("invalid_redirect_uri");
32
+ }
33
+ const name = typeof clientName === "string" && clientName.trim()
34
+ ? clientName.trim().slice(0, MAX_NAME_LENGTH)
35
+ : DEFAULT_CLIENT_NAME;
36
+ const clientId = await sealer.seal({
37
+ issuer: urls.issuer,
38
+ type: "client",
39
+ data: { name, redirectUris },
40
+ });
41
+ return json({
42
+ client_id: clientId,
43
+ client_id_issued_at: Math.floor(Date.now() / 1000),
44
+ client_name: name,
45
+ redirect_uris: redirectUris,
46
+ grant_types: ["authorization_code", "refresh_token"],
47
+ response_types: ["code"],
48
+ token_endpoint_auth_method: "none",
49
+ }, 201);
50
+ };
51
+ export { register };
@@ -0,0 +1,5 @@
1
+ import type { Context } from "../context.js";
2
+ import type { AuthletUser } from "../types.js";
3
+ /** The token endpoint for public clients: authorization code (PKCE) and refresh token grants. */
4
+ declare const token: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>) => Promise<Response>;
5
+ export { token };
@@ -0,0 +1,85 @@
1
+ import { json, oauthError, readBody } from "../http.js";
2
+ import { verifyCodeChallenge } from "../pkce.js";
3
+ /** A parameter the client may leave out, but that must match when sent. */
4
+ const matchesIfSent = (form, name, expected) => !form.has(name) || form.get(name) === expected;
5
+ /** The grant behind a code, if the code is valid for this client and its PKCE verifier. */
6
+ const unsealCode = async ({ urls, sealer }, form, clientId) => {
7
+ const code = await sealer.unseal({
8
+ issuer: urls.issuer,
9
+ type: "code",
10
+ value: form.get("code"),
11
+ });
12
+ if (code?.clientId !== clientId ||
13
+ // OAuth 2.1 clients leave it out, since PKCE does its job; OAuth 2.0 clients send it.
14
+ !matchesIfSent(form, "redirect_uri", code.redirectUri) ||
15
+ !matchesIfSent(form, "resource", code.resource) ||
16
+ !(await verifyCodeChallenge(form.get("code_verifier") ?? "", code.codeChallenge))) {
17
+ return null;
18
+ }
19
+ return { refreshToken: code.refreshToken, resource: code.resource };
20
+ };
21
+ /** The grant behind a refresh token, if it was issued to this client. */
22
+ const unsealRefreshToken = async ({ urls, sealer }, form, clientId) => {
23
+ const wrapper = await sealer.unseal({
24
+ issuer: urls.issuer,
25
+ type: "refresh",
26
+ value: form.get("refresh_token"),
27
+ });
28
+ return wrapper?.clientId === clientId &&
29
+ matchesIfSent(form, "resource", wrapper.resource)
30
+ ? { refreshToken: wrapper.refreshToken, resource: wrapper.resource }
31
+ : null;
32
+ };
33
+ const REQUIRED_PARAMS = {
34
+ authorization_code: ["code", "code_verifier"],
35
+ refresh_token: ["refresh_token"],
36
+ };
37
+ /** The token endpoint for public clients: authorization code (PKCE) and refresh token grants. */
38
+ const token = async (ctx) => {
39
+ const body = await readBody(ctx.req);
40
+ if (body === null) {
41
+ return oauthError("invalid_request");
42
+ }
43
+ const form = new URLSearchParams(body);
44
+ const grantType = form.get("grant_type");
45
+ const clientId = form.get("client_id");
46
+ if (grantType !== "authorization_code" && grantType !== "refresh_token") {
47
+ return oauthError(grantType ? "unsupported_grant_type" : "invalid_request");
48
+ }
49
+ if (!clientId || REQUIRED_PARAMS[grantType].some((name) => !form.get(name))) {
50
+ return oauthError("invalid_request");
51
+ }
52
+ const isCode = grantType === "authorization_code";
53
+ const grant = isCode
54
+ ? await unsealCode(ctx, form, clientId)
55
+ : await unsealRefreshToken(ctx, form, clientId);
56
+ /*
57
+ * Redeeming a code rotates the refresh token sealed in it. The app refuses a used one, so a
58
+ * code works only once.
59
+ */
60
+ const tokens = grant &&
61
+ (await ctx.options.tokens.refresh({
62
+ refreshToken: grant.refreshToken,
63
+ client: { id: clientId },
64
+ kind: isCode ? "code" : "refresh",
65
+ }));
66
+ if (!grant || !tokens) {
67
+ return oauthError("invalid_grant");
68
+ }
69
+ const refreshToken = await ctx.sealer.seal({
70
+ issuer: ctx.urls.issuer,
71
+ type: "refresh",
72
+ data: {
73
+ clientId,
74
+ resource: grant.resource,
75
+ refreshToken: tokens.refreshToken,
76
+ },
77
+ });
78
+ return json({
79
+ access_token: tokens.accessToken,
80
+ token_type: "Bearer",
81
+ refresh_token: refreshToken,
82
+ ...(tokens.expiresIn === undefined ? {} : { expires_in: tokens.expiresIn }),
83
+ });
84
+ };
85
+ export { token };
package/dist/http.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** A JSON response for the CORS-enabled endpoints; never cached, since URLs may come from the request. */
2
+ declare const json: (body: unknown, status?: number) => Response;
3
+ /** An OAuth error response (RFC 6749 section 5.2). */
4
+ declare const oauthError: (error: string, status?: number) => Response;
5
+ /**
6
+ * The request body as text, or `null` when it is too large.
7
+ * shortcut: a chunked body without `Content-Length` is buffered before the check; stream it with
8
+ * a byte cap if hosts don't limit bodies themselves.
9
+ */
10
+ declare const readBody: (req: Request) => Promise<string | null>;
11
+ /** 302 for GET requests; 303 after a form POST, so the browser follows with a GET. */
12
+ declare const redirect: (location: string, status?: 302 | 303) => Response;
13
+ /**
14
+ * Adds query parameters to a URL, skipping `undefined` ones. A relative URL stays relative, so
15
+ * a `Location` built from it never carries an internal host from behind a proxy. It must start
16
+ * with a single `/`: `//evil.example` or `/\evil.example` would leave the site.
17
+ */
18
+ declare const withParams: (target: string, params: Record<string, string | undefined>) => string;
19
+ declare const preflight: (method: string) => Response;
20
+ declare const methodNotAllowed: (method: string) => Response;
21
+ export { json, methodNotAllowed, oauthError, preflight, readBody, redirect, withParams, };
package/dist/http.js ADDED
@@ -0,0 +1,57 @@
1
+ /** Public clients without cookies, so any origin may call the CORS-enabled endpoints. */
2
+ const CORS_HEADERS = { "Access-Control-Allow-Origin": "*" };
3
+ /** A JSON response for the CORS-enabled endpoints; never cached, since URLs may come from the request. */
4
+ const json = (body, status = 200) => Response.json(body, {
5
+ status,
6
+ headers: { "Cache-Control": "no-store", ...CORS_HEADERS },
7
+ });
8
+ /** An OAuth error response (RFC 6749 section 5.2). */
9
+ const oauthError = (error, status = 400) => json({ error }, status);
10
+ /** Larger than any legitimate registration or token request. */
11
+ const MAX_BODY_LENGTH = 16_384;
12
+ /**
13
+ * The request body as text, or `null` when it is too large.
14
+ * shortcut: a chunked body without `Content-Length` is buffered before the check; stream it with
15
+ * a byte cap if hosts don't limit bodies themselves.
16
+ */
17
+ const readBody = async (req) => {
18
+ if (Number(req.headers.get("Content-Length")) > MAX_BODY_LENGTH) {
19
+ return null;
20
+ }
21
+ const body = await req.text();
22
+ return body.length > MAX_BODY_LENGTH ? null : body;
23
+ };
24
+ /** 302 for GET requests; 303 after a form POST, so the browser follows with a GET. */
25
+ const redirect = (location, status = 302) => new Response(null, { status, headers: { Location: location } });
26
+ /**
27
+ * Adds query parameters to a URL, skipping `undefined` ones. A relative URL stays relative, so
28
+ * a `Location` built from it never carries an internal host from behind a proxy. It must start
29
+ * with a single `/`: `//evil.example` or `/\evil.example` would leave the site.
30
+ */
31
+ const withParams = (target, params) => {
32
+ const absolute = URL.canParse(target);
33
+ if (!absolute && !/^\/(?![/\\])/.test(target)) {
34
+ throw new Error(`A relative authlet URL must start with a single "/", got "${target}".`);
35
+ }
36
+ const url = new URL(target, "http://relative.invalid");
37
+ for (const [key, value] of Object.entries(params)) {
38
+ if (value !== undefined) {
39
+ url.searchParams.set(key, value);
40
+ }
41
+ }
42
+ return absolute ? url.href : url.pathname + url.search + url.hash;
43
+ };
44
+ const preflight = (method) => new Response(null, {
45
+ status: 204,
46
+ headers: {
47
+ ...CORS_HEADERS,
48
+ "Access-Control-Allow-Methods": `${method}, OPTIONS`,
49
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
50
+ "Access-Control-Max-Age": "86400",
51
+ },
52
+ });
53
+ const methodNotAllowed = (method) => new Response(null, {
54
+ status: 405,
55
+ headers: { ...CORS_HEADERS, Allow: `${method}, OPTIONS` },
56
+ });
57
+ export { json, methodNotAllowed, oauthError, preflight, readBody, redirect, withParams, };
@@ -0,0 +1,2 @@
1
+ export { createAuthlet } from "./authlet.js";
2
+ export type * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createAuthlet } from "./authlet.js";
package/dist/pkce.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare const isCodeChallenge: (value: string) => boolean;
2
+ /** Whether the verifier hashes to the challenge (PKCE S256, RFC 7636 section 4.6). */
3
+ declare const verifyCodeChallenge: (verifier: string, challenge: string) => Promise<boolean>;
4
+ export { isCodeChallenge, verifyCodeChallenge };
package/dist/pkce.js ADDED
@@ -0,0 +1,15 @@
1
+ import { base64url } from "jose";
2
+ /** A code verifier as RFC 7636 section 4.1 defines it. */
3
+ const VERIFIER = /^[\w.~-]{43,128}$/;
4
+ /** An S256 code challenge: a base64url SHA-256 digest, 43 characters. */
5
+ const CHALLENGE = /^[\w-]{43}$/;
6
+ const isCodeChallenge = (value) => CHALLENGE.test(value);
7
+ /** Whether the verifier hashes to the challenge (PKCE S256, RFC 7636 section 4.6). */
8
+ const verifyCodeChallenge = async (verifier, challenge) => {
9
+ if (!VERIFIER.test(verifier)) {
10
+ return false;
11
+ }
12
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
13
+ return base64url.encode(new Uint8Array(digest)) === challenge;
14
+ };
15
+ export { isCodeChallenge, verifyCodeChallenge };
@@ -0,0 +1,18 @@
1
+ declare const LOOPBACK_HOSTS: Set<string>;
2
+ /**
3
+ * Accepts https, plain http only to the user's own machine (the code would otherwise travel
4
+ * unencrypted), and app schemes such as `cursor://` that desktop clients register. Fragments
5
+ * are rejected, as OAuth requires.
6
+ *
7
+ * The URI must already be in the form the browser will follow, without credentials: otherwise
8
+ * `https://good.example@evil.example/cb` would read as good.example on the consent page while
9
+ * the code goes to evil.example.
10
+ */
11
+ declare const isValidRedirectUri: (uri: unknown) => uri is string;
12
+ /**
13
+ * Whether a requested redirect URI is one the client registered: an exact match, or for http
14
+ * to a loopback host a match on everything but the port (RFC 8252 section 7.3), since native
15
+ * clients pick a free port per sign-in.
16
+ */
17
+ declare const isRegisteredRedirectUri: (requested: string, registered: readonly string[]) => boolean;
18
+ export { isRegisteredRedirectUri, isValidRedirectUri, LOOPBACK_HOSTS };
@@ -0,0 +1,68 @@
1
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
2
+ /** Schemes the browser handles itself instead of handing the code to an app. */
3
+ const BLOCKED_PROTOCOLS = new Set([
4
+ "about:",
5
+ "blob:",
6
+ "data:",
7
+ "file:",
8
+ "filesystem:",
9
+ "javascript:",
10
+ "vbscript:",
11
+ "view-source:",
12
+ "ws:",
13
+ "wss:",
14
+ "intent:",
15
+ "chrome:",
16
+ ]);
17
+ /** Operating-system protocol handlers, such as `ms-msdt:` and `search-ms:`. */
18
+ const BLOCKED_PROTOCOL_PREFIXES = ["ms-", "search-ms"];
19
+ /** Caps the size of sealed client IDs, which carry redirect URIs and travel in URLs. */
20
+ const MAX_LENGTH = 2048;
21
+ /**
22
+ * Accepts https, plain http only to the user's own machine (the code would otherwise travel
23
+ * unencrypted), and app schemes such as `cursor://` that desktop clients register. Fragments
24
+ * are rejected, as OAuth requires.
25
+ *
26
+ * The URI must already be in the form the browser will follow, without credentials: otherwise
27
+ * `https://good.example@evil.example/cb` would read as good.example on the consent page while
28
+ * the code goes to evil.example.
29
+ */
30
+ const isValidRedirectUri = (uri) => {
31
+ if (typeof uri !== "string" ||
32
+ uri.length > MAX_LENGTH ||
33
+ uri.includes("#") ||
34
+ !URL.canParse(uri)) {
35
+ return false;
36
+ }
37
+ const url = new URL(uri);
38
+ if (url.href !== uri || url.username || url.password) {
39
+ return false;
40
+ }
41
+ return url.protocol === "http:"
42
+ ? LOOPBACK_HOSTS.has(url.hostname)
43
+ : !BLOCKED_PROTOCOLS.has(url.protocol) &&
44
+ !BLOCKED_PROTOCOL_PREFIXES.some((prefix) => url.protocol.startsWith(prefix));
45
+ };
46
+ /** The URI without its port when it is http to a loopback host, otherwise `null`. */
47
+ const loopbackWithoutPort = (uri) => {
48
+ if (!URL.canParse(uri)) {
49
+ return null;
50
+ }
51
+ const url = new URL(uri);
52
+ if (url.protocol !== "http:" || !LOOPBACK_HOSTS.has(url.hostname)) {
53
+ return null;
54
+ }
55
+ url.port = "";
56
+ return url.href;
57
+ };
58
+ /**
59
+ * Whether a requested redirect URI is one the client registered: an exact match, or for http
60
+ * to a loopback host a match on everything but the port (RFC 8252 section 7.3), since native
61
+ * clients pick a free port per sign-in.
62
+ */
63
+ const isRegisteredRedirectUri = (requested, registered) => {
64
+ const loopback = loopbackWithoutPort(requested);
65
+ return registered.some((uri) => uri === requested ||
66
+ (loopback !== null && loopbackWithoutPort(uri) === loopback));
67
+ };
68
+ export { isRegisteredRedirectUri, isValidRedirectUri, LOOPBACK_HOSTS };
package/dist/seal.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Everything authlet hands to clients and browsers instead of storing it, keyed by seal type.
3
+ * This is the complete list of state that leaves the server, encrypted.
4
+ */
5
+ interface SealedValues {
6
+ /** The `client_id` from dynamic registration (RFC 7591). */
7
+ client: {
8
+ name: string;
9
+ redirectUris: string[];
10
+ };
11
+ /** The pending authorization behind `consentPage?consent=`. Holds the user ID, never the user. */
12
+ consent: {
13
+ clientId: string;
14
+ redirectUri: string;
15
+ codeChallenge: string;
16
+ state?: string;
17
+ resource: string;
18
+ userId: string;
19
+ };
20
+ /** The authorization code, carrying the refresh token the app issued on consent. */
21
+ code: {
22
+ clientId: string;
23
+ redirectUri: string;
24
+ codeChallenge: string;
25
+ resource: string;
26
+ refreshToken: string;
27
+ };
28
+ /** The `refresh_token` handed to the client, wrapping the app's own refresh token. */
29
+ refresh: {
30
+ clientId: string;
31
+ resource: string;
32
+ refreshToken: string;
33
+ };
34
+ }
35
+ type SealType = keyof SealedValues;
36
+ interface SealArgs<K extends SealType> {
37
+ /** The issuer the value belongs to. A value sealed for one issuer never unseals for another. */
38
+ issuer: string;
39
+ type: K;
40
+ data: SealedValues[K];
41
+ }
42
+ interface UnsealArgs<K extends SealType> {
43
+ issuer: string;
44
+ type: K;
45
+ value: string | null | undefined;
46
+ }
47
+ /**
48
+ * Authenticated encryption of `SealedValues` as compact JWE (`dir`, `A256GCM`) via jose. The
49
+ * type is the protected `typ` header and the issuer is the `iss` claim, both checked on unseal,
50
+ * so a client ID never passes as a code and a code from one issuer never redeems at another.
51
+ */
52
+ interface Sealer {
53
+ seal: <K extends SealType>(args: SealArgs<K>) => Promise<string>;
54
+ /** The sealed data, or `undefined` when the value is malformed, tampered, of another type or issuer, or expired. */
55
+ unseal: <K extends SealType>(args: UnsealArgs<K>) => Promise<SealedValues[K] | undefined>;
56
+ }
57
+ /**
58
+ * Creates a sealer from a secret string (at least 32 characters, stretched with HKDF) or a
59
+ * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages.
60
+ */
61
+ declare const createSealer: (secret: string | CryptoKey) => Sealer;
62
+ export { createSealer };
63
+ export type { Sealer, SealedValues };
package/dist/seal.js ADDED
@@ -0,0 +1,77 @@
1
+ import { EncryptJWT, jwtDecrypt } from "jose";
2
+ /** Seconds each value stays valid, or `undefined` for values that live as long as their contents. */
3
+ const LIFETIMES = {
4
+ client: undefined,
5
+ consent: 20 * 60,
6
+ code: 60,
7
+ refresh: undefined,
8
+ };
9
+ const MIN_SECRET_LENGTH = 32;
10
+ const encoder = new TextEncoder();
11
+ /** Versioned, so a later change to a value's shape can refuse old values instead of misreading them. */
12
+ const typHeader = (type) => `authlet-${type}.v1+jwt`;
13
+ /** Seconds of clock skew allowed between instances, small against the 60-second code lifetime. */
14
+ const CLOCK_TOLERANCE = 5;
15
+ const deriveKey = async (secret) => {
16
+ const material = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, ["deriveKey"]);
17
+ return await crypto.subtle.deriveKey({
18
+ name: "HKDF",
19
+ hash: "SHA-256",
20
+ salt: new Uint8Array(),
21
+ info: encoder.encode("authlet/seal/v1"),
22
+ }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
23
+ };
24
+ const isSealingKey = (key) => key.algorithm.name === "AES-GCM" &&
25
+ key.algorithm.length === 256 &&
26
+ key.usages.includes("encrypt") &&
27
+ key.usages.includes("decrypt");
28
+ /**
29
+ * Creates a sealer from a secret string (at least 32 characters, stretched with HKDF) or a
30
+ * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages.
31
+ */
32
+ const createSealer = (secret) => {
33
+ // Checked here, not in deriveKey, so a bad secret fails at setup instead of as an unhandled rejection.
34
+ if (typeof secret === "string" && secret.length < MIN_SECRET_LENGTH) {
35
+ throw new Error(`The authlet secret must be at least ${String(MIN_SECRET_LENGTH)} characters long.`);
36
+ }
37
+ if (typeof secret !== "string" && !isSealingKey(secret)) {
38
+ throw new Error("The authlet key must be a 256-bit AES-GCM CryptoKey with the encrypt and decrypt usages.");
39
+ }
40
+ const key = typeof secret === "string" ? deriveKey(secret) : Promise.resolve(secret);
41
+ return {
42
+ seal: async ({ issuer, type, data }) => {
43
+ const jwt = new EncryptJWT({ data })
44
+ .setProtectedHeader({
45
+ alg: "dir",
46
+ enc: "A256GCM",
47
+ typ: typHeader(type),
48
+ })
49
+ .setIssuer(issuer)
50
+ .setIssuedAt();
51
+ const lifetime = LIFETIMES[type];
52
+ if (lifetime !== undefined) {
53
+ jwt.setExpirationTime(`${String(lifetime)}s`);
54
+ }
55
+ return await jwt.encrypt(await key);
56
+ },
57
+ unseal: async ({ issuer, type, value, }) => {
58
+ if (!value) {
59
+ return undefined;
60
+ }
61
+ try {
62
+ const { payload } = await jwtDecrypt(value, await key, {
63
+ issuer,
64
+ typ: typHeader(type),
65
+ clockTolerance: CLOCK_TOLERANCE,
66
+ keyManagementAlgorithms: ["dir"],
67
+ contentEncryptionAlgorithms: ["A256GCM"],
68
+ });
69
+ return payload.data;
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ },
75
+ };
76
+ };
77
+ export { createSealer };