@aooth/auth 0.1.7 → 0.1.9

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.
package/dist/authz.cjs ADDED
@@ -0,0 +1,378 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_clock = require("./clock-Bl-H3eqE.cjs");
3
+ let node_crypto = require("node:crypto");
4
+ let jose = require("jose");
5
+ //#region src/authz/authz-errors.ts
6
+ /** A typed authorization-server failure. */
7
+ var AuthorizeError = class extends Error {
8
+ code;
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.name = "AuthorizeError";
12
+ this.code = code;
13
+ }
14
+ };
15
+ //#endregion
16
+ //#region src/authz/client-policy.ts
17
+ /**
18
+ * `true` when `uri` is a syntactically valid http(s) URL whose host is a
19
+ * **loopback literal** — `127.0.0.1`, `::1`, or `localhost` — on any port (RFC
20
+ * 8252 §7.3). Rejects everything else, including the classic bypasses: a
21
+ * host-suffix (`127.0.0.1.evil.com`, `localhost.evil.com`), embedded credentials
22
+ * (`http://127.0.0.1@evil.com` → host `evil.com`), a non-http scheme, and a bare
23
+ * `0.0.0.0`. Only a local process can receive a loopback redirect, which is why
24
+ * an arbitrary port is safe — the binding is the loopback host + PKCE.
25
+ */
26
+ function isLoopbackRedirectUri(uri) {
27
+ let url;
28
+ try {
29
+ url = new URL(uri);
30
+ } catch {
31
+ return false;
32
+ }
33
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
34
+ if (url.username !== "" || url.password !== "") return false;
35
+ const host = url.hostname.replace(/^\[|\]$/g, "");
36
+ return host === "127.0.0.1" || host === "::1" || host === "localhost";
37
+ }
38
+ const DEFAULT_CLI_TOKEN_POLICY = {
39
+ kind: "cli-session",
40
+ ttl: 720 * 60 * 6e4
41
+ };
42
+ /**
43
+ * Tier-1 policy: accept any **loopback** `redirect_uri`, treat the client as a
44
+ * public client (no `client_id` / secret — PKCE is the binding), and mint the
45
+ * configured CLI token policy. Rejects every non-loopback redirect.
46
+ */
47
+ var LoopbackClientPolicy = class {
48
+ tokenPolicy;
49
+ constructor(opts) {
50
+ this.tokenPolicy = opts?.tokenPolicy ?? DEFAULT_CLI_TOKEN_POLICY;
51
+ }
52
+ resolveClient(args) {
53
+ if (!isLoopbackRedirectUri(args.redirectUri)) throw new AuthorizeError("invalid_redirect", "redirect_uri must be a loopback address");
54
+ return {
55
+ redirectUri: args.redirectUri,
56
+ tokenPolicy: structuredClone(this.tokenPolicy),
57
+ ...args.scope !== void 0 && { scope: args.scope }
58
+ };
59
+ }
60
+ };
61
+ //#endregion
62
+ //#region src/authz/oidc-claims-resolver.ts
63
+ /**
64
+ * Resolves the OIDC profile claims to embed in an `id_token` for a given user +
65
+ * granted scope (AUTH-SERVER.md §4.9). The authorization server already controls
66
+ * the registered claims (`iss`/`aud`/`sub`/`iat`/`exp`/`nonce`) itself — this seam
67
+ * supplies the **profile** claims that depend on the consumer's user shape
68
+ * (`email`/`email_verified`/`name`/`picture`), which `@aooth/auth` cannot know.
69
+ *
70
+ * Pluggable like every other store/policy: the no-op default ({@link NoopOidcClaimsResolver},
71
+ * `sub`-only tokens) ships, and a consumer subclasses it to read its own user
72
+ * record. Bound in `@aooth/auth-moost` under `OIDC_CLAIMS_RESOLVER_TOKEN`.
73
+ *
74
+ * The map's keys are standard OIDC claim names; values MUST be JSON-safe. Honour
75
+ * the granted `scope` — only emit `email`/`email_verified` under `email`, and
76
+ * `name`/`picture`/etc. under `profile`, so a client receives only what it asked
77
+ * for (and was allowed).
78
+ */
79
+ var OidcClaimsResolver = class {};
80
+ /** Default resolver: emits no profile claims, so the `id_token` carries only `sub` + the registered claims. */
81
+ var NoopOidcClaimsResolver = class extends OidcClaimsResolver {
82
+ resolveClaims() {
83
+ return {};
84
+ }
85
+ };
86
+ /** `true` when `scope` (space-joined) grants `claim` — `"email"`/`"profile"` etc. */
87
+ function scopeGrants(scope, claim) {
88
+ if (!scope) return false;
89
+ return scope.split(/\s+/u).includes(claim);
90
+ }
91
+ //#endregion
92
+ //#region src/authz/registered-client-policy.ts
93
+ /**
94
+ * Tier-2 policy: a static registry of first-party clients. `resolveClient`
95
+ * authorizes the client + `redirect_uri` (against the registered allowlist) and
96
+ * resolves the granted scope + what the grant delivers (`id_token`/`access_token`,
97
+ * `aud = client_id`); `authenticateClient` authenticates the client at `/token`
98
+ * (`client_secret` for confidential clients; PKCE is the binding for public ones).
99
+ * An unregistered client or an unlisted redirect is rejected.
100
+ */
101
+ var RegisteredClientPolicy = class {
102
+ clients = /* @__PURE__ */ new Map();
103
+ constructor(opts) {
104
+ for (const c of opts.clients) this.clients.set(c.clientId, c);
105
+ }
106
+ resolveClient(args) {
107
+ const client = this.requireClient(args.clientId);
108
+ if (!this.redirectAllowed(client, args.redirectUri)) throw new AuthorizeError("invalid_redirect", "redirect_uri is not registered for this client");
109
+ const scope = this.grantScope(client, args.scope);
110
+ const idToken = client.idToken !== false && scopeGrants(scope, "openid");
111
+ return {
112
+ clientId: client.clientId,
113
+ redirectUri: args.redirectUri,
114
+ audience: client.clientId,
115
+ idToken,
116
+ accessToken: client.accessToken === true,
117
+ tokenPolicy: client.tokenPolicy ? structuredClone(client.tokenPolicy) : {},
118
+ ...scope !== void 0 && { scope }
119
+ };
120
+ }
121
+ authenticateClient(args) {
122
+ const client = this.requireClient(args.clientId);
123
+ if ((client.type ?? "public") !== "confidential") return;
124
+ if (!client.clientSecret || !args.clientSecret || !timingSafeEqualStr(args.clientSecret, client.clientSecret)) throw new AuthorizeError("invalid_client", "client authentication failed");
125
+ }
126
+ requireClient(clientId) {
127
+ const client = clientId ? this.clients.get(clientId) : void 0;
128
+ if (!client) throw new AuthorizeError("invalid_client", "unknown client");
129
+ return client;
130
+ }
131
+ redirectAllowed(client, uri) {
132
+ if (client.redirectUris?.includes(uri)) return true;
133
+ if (!client.redirectPrefixes?.length) return false;
134
+ let normalized;
135
+ try {
136
+ normalized = new URL(uri).href;
137
+ } catch {
138
+ return false;
139
+ }
140
+ return client.redirectPrefixes.some((p) => {
141
+ if (p.length === 0 || !normalized.startsWith(p)) return false;
142
+ if (p.endsWith("/")) return true;
143
+ const next = normalized[p.length];
144
+ return next === void 0 || next === "/" || next === "?" || next === "#";
145
+ });
146
+ }
147
+ grantScope(client, requested) {
148
+ if (!requested) return void 0;
149
+ const req = requested.split(/\s+/u).filter(Boolean);
150
+ const granted = client.scopes ? req.filter((s) => client.scopes.includes(s)) : req;
151
+ return granted.length > 0 ? granted.join(" ") : void 0;
152
+ }
153
+ };
154
+ /** Constant-time string compare that also fails closed on a length mismatch. */
155
+ function timingSafeEqualStr(a, b) {
156
+ const ab = Buffer.from(a, "utf8");
157
+ const bb = Buffer.from(b, "utf8");
158
+ if (ab.length !== bb.length) return false;
159
+ return (0, node_crypto.timingSafeEqual)(ab, bb);
160
+ }
161
+ //#endregion
162
+ //#region src/authz/composite-client-policy.ts
163
+ /**
164
+ * Runs Tier-1 and Tier-2 side by side, dispatching on the **presence of
165
+ * `client_id`** (AUTH-SERVER.md §10): a request with a `client_id` is a
166
+ * registered client, one without is a loopback CLI. The split is the safety
167
+ * boundary — a registered client is routed only to {@link RegisteredClientPolicy}
168
+ * (which enforces ITS redirect allowlist, so it cannot smuggle a loopback
169
+ * redirect), and a no-`client_id` request is routed only to the loopback policy
170
+ * (so it cannot claim to be a registered client). Each sub-policy still owns its
171
+ * own redirect validation; this only picks which one runs.
172
+ */
173
+ var CompositeClientPolicy = class {
174
+ loopback;
175
+ registered;
176
+ constructor(opts) {
177
+ this.loopback = opts.loopback;
178
+ this.registered = opts.registered;
179
+ }
180
+ resolveClient(args) {
181
+ return args.clientId ? this.registered.resolveClient(args) : this.loopback.resolveClient(args);
182
+ }
183
+ authenticateClient(args) {
184
+ if (args.clientId) return this.registered.authenticateClient?.(args);
185
+ }
186
+ };
187
+ //#endregion
188
+ //#region src/authz/id-token-signer.ts
189
+ /**
190
+ * Signs OIDC `id_token`s and publishes the matching JWKS (AUTH-SERVER.md §4.9).
191
+ * Holds one asymmetric keypair; mints short-lived RS256/ES256 tokens with the
192
+ * issuer + audience + subject a relying `OidcProvider` validates, and exports the
193
+ * public half as a JWKS for `GET /auth/jwks`. Keys are imported lazily and cached
194
+ * (the Apple-client-secret pattern), so construction is cheap and synchronous.
195
+ *
196
+ * Never used for the access token (that stays in `AuthCredential`'s store) — the
197
+ * `id_token` is a separate, audience-bound identity assertion.
198
+ */
199
+ var IdTokenSigner = class {
200
+ /** The `iss` claim + discovery `issuer` (read by `/.well-known/openid-configuration`). */
201
+ issuer;
202
+ /** Signature algorithm — published in discovery's `id_token_signing_alg_values_supported`. */
203
+ alg;
204
+ /** Key id — the JWS header + JWKS entry `kid`. */
205
+ kid;
206
+ privateKeyPem;
207
+ publicKeyPem;
208
+ ttlSec;
209
+ clock;
210
+ privateKeyPromise;
211
+ jwksPromise;
212
+ constructor(opts) {
213
+ this.issuer = opts.issuer.replace(/\/$/u, "");
214
+ this.alg = opts.alg ?? "RS256";
215
+ this.kid = opts.kid;
216
+ this.privateKeyPem = opts.privateKey;
217
+ this.publicKeyPem = opts.publicKey;
218
+ this.ttlSec = opts.ttlSec ?? 300;
219
+ this.clock = opts.clock ?? require_clock.defaultClock;
220
+ }
221
+ /** Mint a signed `id_token` JWT. Iat/exp come from the injected clock. */
222
+ async sign(claims) {
223
+ const key = await this.importPrivateKey();
224
+ const nowSec = Math.floor(this.clock.now() / 1e3);
225
+ const ttl = claims.ttlSec ?? this.ttlSec;
226
+ const payload = { ...claims.extra };
227
+ if (claims.nonce !== void 0) payload.nonce = claims.nonce;
228
+ return new jose.SignJWT(payload).setProtectedHeader({
229
+ alg: this.alg,
230
+ kid: this.kid,
231
+ typ: "JWT"
232
+ }).setIssuer(this.issuer).setSubject(claims.sub).setAudience(claims.aud).setIssuedAt(nowSec).setExpirationTime(nowSec + ttl).sign(key);
233
+ }
234
+ /**
235
+ * The JWKS document served at `/auth/jwks` — the public key as a single
236
+ * `use: "sig"` entry tagged with the same `kid`/`alg` as the minted tokens, so
237
+ * a verifier selects it by `kid`. Computed once and cached.
238
+ */
239
+ async jwks() {
240
+ this.jwksPromise ??= (async () => {
241
+ const jwk = await (0, jose.exportJWK)(await (0, jose.importSPKI)(this.publicKeyPem, this.alg, { extractable: true }));
242
+ jwk.kid = this.kid;
243
+ jwk.alg = this.alg;
244
+ jwk.use = "sig";
245
+ return { keys: [jwk] };
246
+ })();
247
+ return this.jwksPromise;
248
+ }
249
+ importPrivateKey() {
250
+ this.privateKeyPromise ??= (0, jose.importPKCS8)(this.privateKeyPem, this.alg);
251
+ return this.privateKeyPromise;
252
+ }
253
+ };
254
+ //#endregion
255
+ //#region src/authz/pending-authorization-store.ts
256
+ /**
257
+ * Storage seam for in-flight authorizations (AUTH-SERVER.md §4.3). Short-lived
258
+ * (≈ the login-session ceiling): created at `/authorize`, read+deleted at the
259
+ * wf terminal. An in-memory impl ships for single-process apps + tests; a
260
+ * multi-pod deployment provides a durable (e.g. Redis) impl under the same
261
+ * `PENDING_AUTHORIZATION_STORE_TOKEN` (from `@aooth/auth-moost`).
262
+ */
263
+ var PendingAuthorizationStore = class {};
264
+ const DEFAULT_PENDING_TTL_MS = 15 * 6e4;
265
+ /**
266
+ * In-memory {@link PendingAuthorizationStore} — the reference impl for a
267
+ * single-process app + tests. `structuredClone` on read/write isolates callers.
268
+ */
269
+ var PendingAuthorizationStoreMemory = class extends PendingAuthorizationStore {
270
+ store = /* @__PURE__ */ new Map();
271
+ clock;
272
+ ttlMs;
273
+ constructor(opts) {
274
+ super();
275
+ this.clock = opts?.clock ?? require_clock.defaultClock;
276
+ this.ttlMs = opts?.ttlMs ?? DEFAULT_PENDING_TTL_MS;
277
+ }
278
+ async create(rec) {
279
+ const now = this.clock.now();
280
+ const row = {
281
+ handle: (0, node_crypto.randomUUID)(),
282
+ redirectUri: rec.redirectUri,
283
+ codeChallenge: rec.codeChallenge,
284
+ tokenPolicy: structuredClone(rec.tokenPolicy),
285
+ createdAt: now,
286
+ expiresAt: now + this.ttlMs,
287
+ ...rec.clientId !== void 0 && { clientId: rec.clientId },
288
+ ...rec.clientState !== void 0 && { clientState: rec.clientState },
289
+ ...rec.scope !== void 0 && { scope: rec.scope },
290
+ ...rec.nonce !== void 0 && { nonce: rec.nonce },
291
+ ...rec.idToken !== void 0 && { idToken: rec.idToken },
292
+ ...rec.accessToken !== void 0 && { accessToken: rec.accessToken },
293
+ ...rec.audience !== void 0 && { audience: rec.audience }
294
+ };
295
+ this.store.set(row.handle, structuredClone(row));
296
+ return { handle: row.handle };
297
+ }
298
+ async get(handle) {
299
+ const row = this.store.get(handle);
300
+ if (!row) return null;
301
+ if (row.expiresAt <= this.clock.now()) {
302
+ this.store.delete(handle);
303
+ return null;
304
+ }
305
+ return structuredClone(row);
306
+ }
307
+ async delete(handle) {
308
+ return this.store.delete(handle);
309
+ }
310
+ };
311
+ //#endregion
312
+ //#region src/authz/auth-code-store.ts
313
+ /**
314
+ * Storage seam for issued authorization codes (AUTH-SERVER.md §4.3). Very
315
+ * short-lived (≈ 30–60 s) and **single-use**: {@link consume} returns the row
316
+ * AND invalidates it in one atomic step, so a concurrent double-redeem (or a
317
+ * back-button replay) yields the code to exactly one caller. An in-memory impl
318
+ * ships (atomic for free in single-threaded JS); a durable impl must implement
319
+ * `consume` as an atomic check-and-delete (e.g. `withCas` / `@db.column.version`,
320
+ * or a Redis `GETDEL`).
321
+ */
322
+ var AuthCodeStore = class {};
323
+ const DEFAULT_CODE_TTL_MS = 6e4;
324
+ /**
325
+ * In-memory {@link AuthCodeStore} — the reference impl. `consume` is atomic
326
+ * because the `get` + `delete` run with no intervening `await`, so a second
327
+ * concurrent `consume` of the same code always misses.
328
+ */
329
+ var AuthCodeStoreMemory = class extends AuthCodeStore {
330
+ store = /* @__PURE__ */ new Map();
331
+ clock;
332
+ ttlMs;
333
+ constructor(opts) {
334
+ super();
335
+ this.clock = opts?.clock ?? require_clock.defaultClock;
336
+ this.ttlMs = opts?.ttlMs ?? DEFAULT_CODE_TTL_MS;
337
+ }
338
+ async mint(rec) {
339
+ const code = (0, node_crypto.randomUUID)();
340
+ const row = {
341
+ code,
342
+ userId: rec.userId,
343
+ codeChallenge: rec.codeChallenge,
344
+ redirectUri: rec.redirectUri,
345
+ tokenPolicy: structuredClone(rec.tokenPolicy),
346
+ expiresAt: this.clock.now() + this.ttlMs,
347
+ ...rec.clientId !== void 0 && { clientId: rec.clientId },
348
+ ...rec.scope !== void 0 && { scope: rec.scope },
349
+ ...rec.nonce !== void 0 && { nonce: rec.nonce },
350
+ ...rec.idToken !== void 0 && { idToken: rec.idToken },
351
+ ...rec.accessToken !== void 0 && { accessToken: rec.accessToken },
352
+ ...rec.audience !== void 0 && { audience: rec.audience }
353
+ };
354
+ this.store.set(code, structuredClone(row));
355
+ return { code };
356
+ }
357
+ async consume(code) {
358
+ const row = this.store.get(code);
359
+ if (!row) return null;
360
+ this.store.delete(code);
361
+ if (row.expiresAt <= this.clock.now()) return null;
362
+ return structuredClone(row);
363
+ }
364
+ };
365
+ //#endregion
366
+ exports.AuthCodeStore = AuthCodeStore;
367
+ exports.AuthCodeStoreMemory = AuthCodeStoreMemory;
368
+ exports.AuthorizeError = AuthorizeError;
369
+ exports.CompositeClientPolicy = CompositeClientPolicy;
370
+ exports.IdTokenSigner = IdTokenSigner;
371
+ exports.LoopbackClientPolicy = LoopbackClientPolicy;
372
+ exports.NoopOidcClaimsResolver = NoopOidcClaimsResolver;
373
+ exports.OidcClaimsResolver = OidcClaimsResolver;
374
+ exports.PendingAuthorizationStore = PendingAuthorizationStore;
375
+ exports.PendingAuthorizationStoreMemory = PendingAuthorizationStoreMemory;
376
+ exports.RegisteredClientPolicy = RegisteredClientPolicy;
377
+ exports.isLoopbackRedirectUri = isLoopbackRedirectUri;
378
+ exports.scopeGrants = scopeGrants;