@blamejs/core 0.4.1

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.
Files changed (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,691 @@
1
+ "use strict";
2
+ /**
3
+ * oauth — OAuth 2 / OIDC client.
4
+ *
5
+ * "Login with Google / GitHub / Microsoft / Apple / etc." — table
6
+ * stakes for B2C and SSO B2B. Without this, operators reach for
7
+ * `passport-*` packages and we lose control of the request flow.
8
+ *
9
+ * The framework's PQC-first stance applies to outbound crypto we
10
+ * emit. OIDC IdPs sign ID tokens with classical-algo JWS (RS256,
11
+ * ES256, etc.) — third-party crypto we MUST verify. This module
12
+ * carries an OIDC-specific verifier for that interop case;
13
+ * `lib/auth/jwt.js` remains PQC-only for tokens the FRAMEWORK signs.
14
+ *
15
+ * Public API:
16
+ *
17
+ * var oauth = b.auth.oauth.create({
18
+ * provider: "google", // preset
19
+ * clientId: "...", clientSecret: "...",
20
+ * redirectUri: "https://app/auth/callback",
21
+ * scope: ["openid", "email", "profile"],
22
+ * });
23
+ *
24
+ * // Or generic:
25
+ * var oauth = b.auth.oauth.create({
26
+ * issuer: "https://auth.example.com", // OIDC discovery
27
+ * clientId, clientSecret, redirectUri, scope: [...],
28
+ * });
29
+ *
30
+ * // Step 1 — Build the authorize URL. Operator persists the
31
+ * // returned `verifier` and `state` in their session.
32
+ * var auth = await oauth.authorizationUrl();
33
+ * // → { url, state, nonce, verifier, challenge }
34
+ * res.redirect(302, auth.url);
35
+ *
36
+ * // Step 2 — In the callback handler, verify state + exchange code.
37
+ * var stored = req.session.get("oauth-state");
38
+ * if (req.query.state !== stored.state) throw new ForbiddenError();
39
+ * var tokens = await oauth.exchangeCode({
40
+ * code: req.query.code,
41
+ * state: req.query.state,
42
+ * verifier: stored.verifier,
43
+ * });
44
+ * // → { accessToken, idToken, refreshToken, tokenType, expiresIn,
45
+ * // scope, claims, profile }
46
+ *
47
+ * // Step 3 — operator decides: create user, link to existing, etc.
48
+ *
49
+ * // Refresh:
50
+ * var fresh = await oauth.refreshAccessToken(tokens.refreshToken);
51
+ *
52
+ * // Revoke (RFC 7009; not all providers support it — checked at
53
+ * // discovery, throws if unavailable):
54
+ * await oauth.revokeToken(tokens.refreshToken, { type: "refresh_token" });
55
+ *
56
+ * // Userinfo (OIDC standard endpoint):
57
+ * var profile = await oauth.fetchUserInfo(tokens.accessToken);
58
+ *
59
+ * Vendor presets (b.auth.oauth.PRESETS):
60
+ * google OIDC discovery via accounts.google.com
61
+ * microsoft OIDC via login.microsoftonline.com (common tenant)
62
+ * apple "Sign in with Apple" — RSA-PSS signed ID tokens
63
+ * auth0 OIDC via {tenant}.auth0.com (operator passes tenant)
64
+ * keycloak OIDC via {host}/realms/{realm}/.well-known/...
65
+ * github OAuth 2 only (NOT OIDC — no ID token; GitHub uses
66
+ * a userinfo-equivalent endpoint /user)
67
+ * generic operator passes endpoints manually
68
+ *
69
+ * Discovery:
70
+ * When `issuer` (or a preset's discovery URL) is set, the client
71
+ * fetches `/.well-known/openid-configuration` on first use and
72
+ * caches authorization_endpoint, token_endpoint, jwks_uri,
73
+ * userinfo_endpoint, revocation_endpoint, supported algos. Cache
74
+ * default 1 hour; operators tune via `discoveryCacheMs`.
75
+ *
76
+ * PKCE:
77
+ * ON BY DEFAULT. RFC 7636. The framework refuses to build an
78
+ * authorization URL without PKCE unless the operator explicitly
79
+ * passes `pkce: false` (and even then it logs a warning). Operators
80
+ * on legacy IdPs that don't support PKCE — vanishingly rare in 2026
81
+ * — must opt out explicitly.
82
+ *
83
+ * State + nonce:
84
+ * Generated fresh per-call. The framework returns them but doesn't
85
+ * store them — that's the operator's session's job. The state
86
+ * verifies the OAuth callback came from the same browser session
87
+ * (CSRF defense); the nonce verifies the ID token wasn't replayed
88
+ * from a different login flow.
89
+ *
90
+ * ID token verification (when an ID token is present):
91
+ * - Header alg must be on `acceptedAlgorithms` (default RS256, RS384,
92
+ * RS512, ES256, ES384, ES512, PS256, PS384, PS512). HS256 is
93
+ * refused — symmetric-keyed ID tokens are an anti-pattern.
94
+ * - kid lookup against the discovered JWKS.
95
+ * - Signature verification via node:crypto for the matching algo.
96
+ * - Claim validation: iss matches issuer, aud contains clientId,
97
+ * exp not past, iat not future, nonce matches the call's nonce.
98
+ *
99
+ * HTTPS:
100
+ * All endpoints must be https except localhost during dev. The
101
+ * discovery / token / userinfo / revocation / jwks fetches go
102
+ * through `b.httpClient` which enforces the framework's PQC-locked
103
+ * posture by default (operators with mixed-protocol setups pass
104
+ * `allowedProtocols`).
105
+ */
106
+
107
+ var nodeCrypto = require("node:crypto");
108
+ var cache = require("../cache");
109
+ var safeUrl = require("../safe-url");
110
+ var C = require("../constants");
111
+ var { defineClass } = require("../framework-error");
112
+ var { boot } = require("../log");
113
+
114
+ var OAuthError = defineClass("OAuthError", { alwaysPermanent: true });
115
+ var log = boot("auth.oauth");
116
+
117
+ // Vendor presets. Each entry has either { issuer } (OIDC) or explicit
118
+ // endpoints { authorizationEndpoint, tokenEndpoint, userinfoEndpoint }.
119
+ var PRESETS = Object.freeze({
120
+ google: {
121
+ issuer: "https://accounts.google.com",
122
+ defaultScope: ["openid", "email", "profile"],
123
+ isOidc: true,
124
+ },
125
+ microsoft: {
126
+ issuer: "https://login.microsoftonline.com/common/v2.0",
127
+ defaultScope: ["openid", "email", "profile"],
128
+ isOidc: true,
129
+ },
130
+ apple: {
131
+ issuer: "https://appleid.apple.com",
132
+ defaultScope: ["openid", "email", "name"],
133
+ isOidc: true,
134
+ // Apple wants form_post response_mode (browser POSTs back to redirect).
135
+ responseMode: "form_post",
136
+ },
137
+ auth0: {
138
+ // Operator passes auth0Domain: "tenant.auth0.com" via opts; we
139
+ // expand it into the issuer URL.
140
+ issuerTemplate: function (opts) {
141
+ if (!opts.auth0Domain) {
142
+ throw new OAuthError("auth-oauth/auth0-domain",
143
+ "auth0 preset requires opts.auth0Domain ('your-tenant.auth0.com')");
144
+ }
145
+ return "https://" + opts.auth0Domain;
146
+ },
147
+ defaultScope: ["openid", "email", "profile"],
148
+ isOidc: true,
149
+ },
150
+ keycloak: {
151
+ // Keycloak realms: opts.keycloakUrl + opts.keycloakRealm
152
+ issuerTemplate: function (opts) {
153
+ if (!opts.keycloakUrl || !opts.keycloakRealm) {
154
+ throw new OAuthError("auth-oauth/keycloak-config",
155
+ "keycloak preset requires opts.keycloakUrl and opts.keycloakRealm");
156
+ }
157
+ return opts.keycloakUrl.replace(/\/$/, "") + "/realms/" + opts.keycloakRealm;
158
+ },
159
+ defaultScope: ["openid", "email", "profile"],
160
+ isOidc: true,
161
+ },
162
+ github: {
163
+ // GitHub is OAuth 2 only — no OIDC, no ID tokens, no JWKS.
164
+ authorizationEndpoint: "https://github.com/login/oauth/authorize",
165
+ tokenEndpoint: "https://github.com/login/oauth/access_token",
166
+ userinfoEndpoint: "https://api.github.com/user",
167
+ defaultScope: ["read:user", "user:email"],
168
+ isOidc: false,
169
+ },
170
+ generic: {
171
+ // Operator-defined endpoints (or issuer-driven discovery). The
172
+ // preset itself adds nothing — its presence makes provider:'generic'
173
+ // a valid explicit selector instead of falling through to "unknown
174
+ // provider preset". Operators pass authorizationEndpoint /
175
+ // tokenEndpoint / userinfoEndpoint (or issuer + isOidc:true to
176
+ // discover) on opts.
177
+ },
178
+ });
179
+
180
+ var DEFAULT_ACCEPTED_ALGS = Object.freeze([
181
+ "RS256", "RS384", "RS512",
182
+ "ES256", "ES384", "ES512",
183
+ "PS256", "PS384", "PS512",
184
+ ]);
185
+
186
+ var DEFAULT_DISCOVERY_CACHE_MS = C.TIME.hours(1);
187
+ var DEFAULT_CLOCK_SKEW_MS = C.TIME.minutes(1);
188
+
189
+ // ---- helpers ----
190
+
191
+ function _b64urlEncode(buf) {
192
+ if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
193
+ return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
194
+ }
195
+
196
+ function _b64urlDecode(s) {
197
+ if (typeof s !== "string") throw new OAuthError("auth-oauth/bad-base64", "expected base64url string");
198
+ var padded = s.replace(/-/g, "+").replace(/_/g, "/");
199
+ while (padded.length % 4) padded += "=";
200
+ return Buffer.from(padded, "base64");
201
+ }
202
+
203
+ function _generateRandomToken(bytes) {
204
+ return _b64urlEncode(nodeCrypto.randomBytes(bytes));
205
+ }
206
+
207
+ function _generatePkce() {
208
+ // RFC 7636: code_verifier is 43–128 chars [A-Za-z0-9-._~].
209
+ // base64url of 32 random bytes = 43 chars, all valid.
210
+ var verifier = _b64urlEncode(nodeCrypto.randomBytes(32));
211
+ var challenge = _b64urlEncode(nodeCrypto.createHash("sha256").update(verifier).digest());
212
+ return { verifier: verifier, challenge: challenge };
213
+ }
214
+
215
+ function _validateUrl(url, allowHttp, label) {
216
+ if (typeof url !== "string" || url.length === 0) {
217
+ throw new OAuthError("auth-oauth/bad-url", label + ": URL is required");
218
+ }
219
+ var parsed;
220
+ try { parsed = new URL(url); }
221
+ catch (_e) {
222
+ throw new OAuthError("auth-oauth/bad-url", label + ": invalid URL '" + url + "'");
223
+ }
224
+ if (parsed.protocol === "https:") return url;
225
+ if (parsed.protocol === "http:" && allowHttp) return url;
226
+ throw new OAuthError("auth-oauth/insecure-url",
227
+ label + ": must be https (got '" + parsed.protocol + "//" + parsed.host + "')");
228
+ }
229
+
230
+ // ---- JOSE alg → node:crypto verify parameters ----
231
+
232
+ function _verifyParamsForAlg(alg) {
233
+ // Returns { hash, padding, dsaEncoding } for node:crypto.verify.
234
+ if (alg === "RS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
235
+ if (alg === "RS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
236
+ if (alg === "RS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
237
+ if (alg === "PS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: 32 };
238
+ if (alg === "PS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: 48 };
239
+ if (alg === "PS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: 64 };
240
+ if (alg === "ES256") return { hash: "sha256", dsaEncoding: "ieee-p1363" };
241
+ if (alg === "ES384") return { hash: "sha384", dsaEncoding: "ieee-p1363" };
242
+ if (alg === "ES512") return { hash: "sha512", dsaEncoding: "ieee-p1363" };
243
+ throw new OAuthError("auth-oauth/unsupported-alg",
244
+ "alg '" + alg + "' is not supported for ID-token verification");
245
+ }
246
+
247
+ // ---- JWKS → KeyObject ----
248
+
249
+ function _jwkToKey(jwk) {
250
+ // node's createPublicKey accepts JWK directly since Node 16.
251
+ try { return nodeCrypto.createPublicKey({ key: jwk, format: "jwk" }); }
252
+ catch (e) {
253
+ throw new OAuthError("auth-oauth/bad-jwk",
254
+ "could not import JWK (kid=" + (jwk && jwk.kid) + "): " + ((e && e.message) || String(e)));
255
+ }
256
+ }
257
+
258
+ // ---- core ----
259
+
260
+ function create(opts) {
261
+ opts = opts || {};
262
+ var clientId = opts.clientId;
263
+ var clientSecret = opts.clientSecret || null; // public clients can omit
264
+ var redirectUri = opts.redirectUri;
265
+ var pkce = opts.pkce !== false;
266
+ var clockSkewMs = typeof opts.clockSkewMs === "number" ? opts.clockSkewMs : DEFAULT_CLOCK_SKEW_MS;
267
+ var discoveryCacheMs = typeof opts.discoveryCacheMs === "number"
268
+ ? opts.discoveryCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
269
+ var acceptedAlgorithms = Array.isArray(opts.acceptedAlgorithms) && opts.acceptedAlgorithms.length > 0
270
+ ? opts.acceptedAlgorithms.slice() : DEFAULT_ACCEPTED_ALGS.slice();
271
+ var allowHttp = !!opts.allowHttp; // localhost dev opt-in
272
+ var httpClientOpts = opts.httpClient || {};
273
+ var responseMode = opts.responseMode || null;
274
+
275
+ if (!clientId) {
276
+ throw new OAuthError("auth-oauth/no-client-id", "create: opts.clientId is required");
277
+ }
278
+ if (!redirectUri) {
279
+ throw new OAuthError("auth-oauth/no-redirect-uri", "create: opts.redirectUri is required");
280
+ }
281
+ _validateUrl(redirectUri, allowHttp, "redirectUri");
282
+ if (!pkce) {
283
+ log("WARNING: PKCE disabled — modern IdPs require it; this should only be used for legacy providers");
284
+ }
285
+
286
+ // Resolve preset → effective config.
287
+ var preset = null;
288
+ if (opts.provider) {
289
+ if (!Object.prototype.hasOwnProperty.call(PRESETS, opts.provider)) {
290
+ throw new OAuthError("auth-oauth/unknown-provider",
291
+ "unknown provider preset '" + opts.provider + "' (known: " +
292
+ Object.keys(PRESETS).join(", ") + ")");
293
+ }
294
+ preset = PRESETS[opts.provider];
295
+ }
296
+ var isOidc = (preset && typeof preset.isOidc === "boolean") ? preset.isOidc
297
+ : (opts.isOidc !== undefined ? !!opts.isOidc : true);
298
+ var issuer = opts.issuer
299
+ || (preset && typeof preset.issuerTemplate === "function" && preset.issuerTemplate(opts))
300
+ || (preset && preset.issuer)
301
+ || null;
302
+ var scope = Array.isArray(opts.scope) && opts.scope.length > 0
303
+ ? opts.scope.slice()
304
+ : (preset && preset.defaultScope ? preset.defaultScope.slice() : ["openid"]);
305
+ if (!responseMode && preset && preset.responseMode) responseMode = preset.responseMode;
306
+
307
+ // Endpoints — either from preset (explicit), discovery, or operator opts.
308
+ var staticEndpoints = {
309
+ authorizationEndpoint: opts.authorizationEndpoint || (preset && preset.authorizationEndpoint) || null,
310
+ tokenEndpoint: opts.tokenEndpoint || (preset && preset.tokenEndpoint) || null,
311
+ userinfoEndpoint: opts.userinfoEndpoint || (preset && preset.userinfoEndpoint) || null,
312
+ revocationEndpoint: opts.revocationEndpoint || (preset && preset.revocationEndpoint) || null,
313
+ jwksUri: opts.jwksUri || (preset && preset.jwksUri) || null,
314
+ };
315
+
316
+ // Discovery + JWKS caches use b.cache.create + .wrap so concurrent
317
+ // boot races for the same IdP collapse to one fetch (single-flight)
318
+ // and operators can wire b.audit / observability without us
319
+ // re-implementing those hooks here. Per-cache namespaces are unique
320
+ // per oauth-client instance (clientId-scoped) so two clients pointed
321
+ // at different IdPs don't collide in a future cluster-cache backend.
322
+ var jwksCacheMs = typeof opts.jwksCacheMs === "number" ? opts.jwksCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
323
+ var _discoveryCache = cache.create({
324
+ namespace: "oauth.discovery." + clientId,
325
+ ttlMs: discoveryCacheMs,
326
+ });
327
+ var _jwksCache = cache.create({
328
+ namespace: "oauth.jwks." + clientId,
329
+ ttlMs: jwksCacheMs,
330
+ });
331
+
332
+ function _httpClient() {
333
+ return require("../http-client");
334
+ }
335
+
336
+ async function _fetchJson(url, fetchOpts) {
337
+ fetchOpts = fetchOpts || {};
338
+ var hc = _httpClient();
339
+ var req = Object.assign({
340
+ url: url,
341
+ method: "GET",
342
+ }, fetchOpts);
343
+ if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
344
+ Object.assign(req, httpClientOpts);
345
+ var res = await hc.request(req);
346
+ if (res.statusCode < 200 || res.statusCode >= 300) {
347
+ var bodyText = res.body ? res.body.toString("utf8") : "";
348
+ throw new OAuthError("auth-oauth/http-" + res.statusCode,
349
+ url + " returned " + res.statusCode + ": " + bodyText.slice(0, 500));
350
+ }
351
+ if (!res.body) return null;
352
+ try { return JSON.parse(res.body.toString("utf8")); }
353
+ catch (e) {
354
+ throw new OAuthError("auth-oauth/bad-json",
355
+ url + " response not JSON: " + ((e && e.message) || String(e)));
356
+ }
357
+ }
358
+
359
+ async function _discover() {
360
+ if (!isOidc || !issuer) return null;
361
+ return _discoveryCache.wrap("config", async function () {
362
+ var url = issuer.replace(/\/$/, "") + "/.well-known/openid-configuration";
363
+ _validateUrl(url, allowHttp, "discovery url");
364
+ var config = await _fetchJson(url);
365
+ if (!config || typeof config !== "object") {
366
+ throw new OAuthError("auth-oauth/bad-discovery", "discovery document missing");
367
+ }
368
+ if (config.issuer && config.issuer !== issuer) {
369
+ throw new OAuthError("auth-oauth/issuer-mismatch",
370
+ "discovery issuer '" + config.issuer + "' does not match configured issuer '" + issuer + "'");
371
+ }
372
+ return config;
373
+ });
374
+ }
375
+
376
+ async function _resolveEndpoint(name) {
377
+ if (staticEndpoints[name]) return staticEndpoints[name];
378
+ var config = await _discover();
379
+ if (!config) {
380
+ throw new OAuthError("auth-oauth/no-endpoint",
381
+ name + " endpoint not configured and no OIDC discovery available");
382
+ }
383
+ // OIDC discovery uses snake_case key names.
384
+ var snake = ({
385
+ authorizationEndpoint: "authorization_endpoint",
386
+ tokenEndpoint: "token_endpoint",
387
+ userinfoEndpoint: "userinfo_endpoint",
388
+ revocationEndpoint: "revocation_endpoint",
389
+ jwksUri: "jwks_uri",
390
+ })[name];
391
+ var endpoint = config[snake];
392
+ if (!endpoint) {
393
+ throw new OAuthError("auth-oauth/no-endpoint",
394
+ name + " not present in discovery document");
395
+ }
396
+ return endpoint;
397
+ }
398
+
399
+ async function authorizationUrl(uopts) {
400
+ uopts = uopts || {};
401
+ var endpoint = await _resolveEndpoint("authorizationEndpoint");
402
+ var state = uopts.state || _generateRandomToken(16);
403
+ var nonce = uopts.nonce || (isOidc ? _generateRandomToken(16) : null);
404
+ var pkceVals = pkce ? _generatePkce() : null;
405
+ var params = new URLSearchParams();
406
+ params.set("response_type", "code");
407
+ params.set("client_id", clientId);
408
+ params.set("redirect_uri", redirectUri);
409
+ params.set("scope", scope.join(" "));
410
+ params.set("state", state);
411
+ if (nonce) params.set("nonce", nonce);
412
+ if (pkceVals) {
413
+ params.set("code_challenge", pkceVals.challenge);
414
+ params.set("code_challenge_method", "S256");
415
+ }
416
+ if (responseMode) params.set("response_mode", responseMode);
417
+ if (uopts.prompt) params.set("prompt", uopts.prompt);
418
+ if (uopts.loginHint) params.set("login_hint", uopts.loginHint);
419
+ if (uopts.maxAge != null) params.set("max_age", String(uopts.maxAge));
420
+ // Operator-supplied additional params (audience, resource, etc.).
421
+ if (uopts.extraParams && typeof uopts.extraParams === "object") {
422
+ var ek = Object.keys(uopts.extraParams);
423
+ for (var i = 0; i < ek.length; i++) params.set(ek[i], String(uopts.extraParams[ek[i]]));
424
+ }
425
+ var sep = endpoint.indexOf("?") === -1 ? "?" : "&";
426
+ return {
427
+ url: endpoint + sep + params.toString(),
428
+ state: state,
429
+ nonce: nonce,
430
+ verifier: pkceVals ? pkceVals.verifier : null,
431
+ challenge: pkceVals ? pkceVals.challenge : null,
432
+ };
433
+ }
434
+
435
+ async function exchangeCode(eopts) {
436
+ eopts = eopts || {};
437
+ if (!eopts.code) {
438
+ throw new OAuthError("auth-oauth/no-code", "exchangeCode: opts.code is required");
439
+ }
440
+ if (pkce && !eopts.verifier) {
441
+ throw new OAuthError("auth-oauth/no-verifier",
442
+ "exchangeCode: opts.verifier is required when PKCE is on (default)");
443
+ }
444
+ var endpoint = await _resolveEndpoint("tokenEndpoint");
445
+ var body = new URLSearchParams();
446
+ body.set("grant_type", "authorization_code");
447
+ body.set("code", eopts.code);
448
+ body.set("redirect_uri", redirectUri);
449
+ body.set("client_id", clientId);
450
+ if (clientSecret) body.set("client_secret", clientSecret);
451
+ if (eopts.verifier) body.set("code_verifier", eopts.verifier);
452
+
453
+ var tokens = await _postForm(endpoint, body);
454
+ return await _normalizeTokens(tokens, { nonce: eopts.nonce });
455
+ }
456
+
457
+ async function refreshAccessToken(refreshToken) {
458
+ if (!refreshToken) {
459
+ throw new OAuthError("auth-oauth/no-refresh-token",
460
+ "refreshAccessToken: refresh token is required");
461
+ }
462
+ var endpoint = await _resolveEndpoint("tokenEndpoint");
463
+ var body = new URLSearchParams();
464
+ body.set("grant_type", "refresh_token");
465
+ body.set("refresh_token", refreshToken);
466
+ body.set("client_id", clientId);
467
+ if (clientSecret) body.set("client_secret", clientSecret);
468
+ var tokens = await _postForm(endpoint, body);
469
+ // Refreshed tokens may not include a new id_token; verification
470
+ // is conditional.
471
+ return await _normalizeTokens(tokens, { skipNonceCheck: true });
472
+ }
473
+
474
+ async function fetchUserInfo(accessToken) {
475
+ if (!accessToken) {
476
+ throw new OAuthError("auth-oauth/no-access-token",
477
+ "fetchUserInfo: access token is required");
478
+ }
479
+ var endpoint = await _resolveEndpoint("userinfoEndpoint");
480
+ return await _fetchJson(endpoint, {
481
+ headers: {
482
+ "Authorization": "Bearer " + accessToken,
483
+ "Accept": "application/json",
484
+ "User-Agent": "blamejs",
485
+ },
486
+ });
487
+ }
488
+
489
+ async function revokeToken(token, ropts) {
490
+ if (!token) {
491
+ throw new OAuthError("auth-oauth/no-token", "revokeToken: token is required");
492
+ }
493
+ ropts = ropts || {};
494
+ var endpoint = await _resolveEndpoint("revocationEndpoint");
495
+ var body = new URLSearchParams();
496
+ body.set("token", token);
497
+ if (ropts.type) body.set("token_type_hint", ropts.type);
498
+ body.set("client_id", clientId);
499
+ if (clientSecret) body.set("client_secret", clientSecret);
500
+ var hc = _httpClient();
501
+ var req = {
502
+ url: endpoint,
503
+ method: "POST",
504
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
505
+ body: Buffer.from(body.toString(), "utf8"),
506
+ };
507
+ if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
508
+ Object.assign(req, httpClientOpts);
509
+ var res = await hc.request(req);
510
+ // RFC 7009: 200 even if the token was already revoked / unknown.
511
+ if (res.statusCode < 200 || res.statusCode >= 300) {
512
+ throw new OAuthError("auth-oauth/revoke-failed",
513
+ "revocation returned " + res.statusCode);
514
+ }
515
+ }
516
+
517
+ async function _postForm(endpoint, body) {
518
+ var hc = _httpClient();
519
+ var req = {
520
+ url: endpoint,
521
+ method: "POST",
522
+ headers: {
523
+ "Content-Type": "application/x-www-form-urlencoded",
524
+ "Accept": "application/json",
525
+ },
526
+ body: Buffer.from(body.toString(), "utf8"),
527
+ };
528
+ if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
529
+ Object.assign(req, httpClientOpts);
530
+ var res = await hc.request(req);
531
+ var text = res.body ? res.body.toString("utf8") : "";
532
+ if (res.statusCode < 200 || res.statusCode >= 300) {
533
+ throw new OAuthError("auth-oauth/token-error-" + res.statusCode,
534
+ endpoint + " returned " + res.statusCode + ": " + text.slice(0, 500));
535
+ }
536
+ var parsed;
537
+ try { parsed = JSON.parse(text); }
538
+ catch (e) {
539
+ throw new OAuthError("auth-oauth/bad-token-json",
540
+ "token endpoint response not JSON: " + ((e && e.message) || String(e)));
541
+ }
542
+ return parsed;
543
+ }
544
+
545
+ async function _normalizeTokens(raw, vopts) {
546
+ vopts = vopts || {};
547
+ var tokens = {
548
+ accessToken: raw.access_token,
549
+ tokenType: raw.token_type || "Bearer",
550
+ expiresIn: raw.expires_in || null,
551
+ refreshToken: raw.refresh_token || null,
552
+ idToken: raw.id_token || null,
553
+ scope: raw.scope ? raw.scope.split(/\s+/) : scope.slice(),
554
+ raw: raw,
555
+ };
556
+ if (tokens.idToken && isOidc) {
557
+ var v = await verifyIdToken(tokens.idToken, {
558
+ nonce: vopts.nonce,
559
+ skipNonceCheck: vopts.skipNonceCheck,
560
+ });
561
+ tokens.claims = v.claims;
562
+ tokens.profile = {
563
+ sub: v.claims.sub,
564
+ email: v.claims.email,
565
+ name: v.claims.name,
566
+ picture: v.claims.picture,
567
+ };
568
+ }
569
+ return tokens;
570
+ }
571
+
572
+ async function _getJwks() {
573
+ return _jwksCache.wrap("keys", async function () {
574
+ var jwksUri = await _resolveEndpoint("jwksUri");
575
+ var jwks = await _fetchJson(jwksUri);
576
+ if (!jwks || !Array.isArray(jwks.keys)) {
577
+ throw new OAuthError("auth-oauth/bad-jwks", "JWKS response missing 'keys' array");
578
+ }
579
+ return jwks.keys;
580
+ });
581
+ }
582
+
583
+ async function verifyIdToken(idToken, vopts) {
584
+ vopts = vopts || {};
585
+ if (typeof idToken !== "string") {
586
+ throw new OAuthError("auth-oauth/no-id-token", "verifyIdToken: idToken must be a string");
587
+ }
588
+ var parts = idToken.split(".");
589
+ if (parts.length !== 3) {
590
+ throw new OAuthError("auth-oauth/malformed-jwt", "ID token does not have 3 parts");
591
+ }
592
+ var header, payload;
593
+ try {
594
+ header = JSON.parse(_b64urlDecode(parts[0]).toString("utf8"));
595
+ payload = JSON.parse(_b64urlDecode(parts[1]).toString("utf8"));
596
+ } catch (e) {
597
+ throw new OAuthError("auth-oauth/malformed-jwt",
598
+ "ID token header/payload base64 decode failed: " + ((e && e.message) || String(e)));
599
+ }
600
+ if (!header || typeof header.alg !== "string") {
601
+ throw new OAuthError("auth-oauth/malformed-jwt", "ID token header missing 'alg'");
602
+ }
603
+ if (acceptedAlgorithms.indexOf(header.alg) === -1) {
604
+ throw new OAuthError("auth-oauth/alg-not-accepted",
605
+ "ID token signed with '" + header.alg + "' which is not in the accepted-algorithm list");
606
+ }
607
+ var keys = await _getJwks();
608
+ var match = null;
609
+ if (header.kid) {
610
+ for (var i = 0; i < keys.length; i++) {
611
+ if (keys[i].kid === header.kid) { match = keys[i]; break; }
612
+ }
613
+ } else if (keys.length === 1) {
614
+ match = keys[0];
615
+ }
616
+ if (!match) {
617
+ throw new OAuthError("auth-oauth/no-matching-key",
618
+ "no JWKS key matches header.kid='" + header.kid + "'");
619
+ }
620
+ var keyObject = _jwkToKey(match);
621
+ var params = _verifyParamsForAlg(header.alg);
622
+ var signingInput = parts[0] + "." + parts[1];
623
+ var sig = _b64urlDecode(parts[2]);
624
+ var verifyOpts = { key: keyObject };
625
+ if (params.padding !== undefined) verifyOpts.padding = params.padding;
626
+ if (params.saltLength !== undefined) verifyOpts.saltLength = params.saltLength;
627
+ if (params.dsaEncoding !== undefined) verifyOpts.dsaEncoding = params.dsaEncoding;
628
+ var verified = nodeCrypto.verify(params.hash, Buffer.from(signingInput, "ascii"), verifyOpts, sig);
629
+ if (!verified) {
630
+ throw new OAuthError("auth-oauth/bad-signature", "ID token signature verification failed");
631
+ }
632
+
633
+ // Claim validation.
634
+ var now = Math.floor(Date.now() / 1000);
635
+ var skewSec = Math.floor(clockSkewMs / 1000);
636
+ if (typeof payload.exp !== "number" || payload.exp + skewSec < now) {
637
+ throw new OAuthError("auth-oauth/expired", "ID token expired (exp=" + payload.exp + ", now=" + now + ")");
638
+ }
639
+ if (typeof payload.iat === "number" && payload.iat - skewSec > now) {
640
+ throw new OAuthError("auth-oauth/iat-future", "ID token iat is in the future");
641
+ }
642
+ if (typeof payload.nbf === "number" && payload.nbf - skewSec > now) {
643
+ throw new OAuthError("auth-oauth/nbf-future", "ID token nbf is in the future");
644
+ }
645
+ if (issuer && payload.iss !== issuer) {
646
+ throw new OAuthError("auth-oauth/iss-mismatch",
647
+ "ID token iss '" + payload.iss + "' does not match expected '" + issuer + "'");
648
+ }
649
+ var aud = Array.isArray(payload.aud) ? payload.aud : (payload.aud ? [payload.aud] : []);
650
+ if (aud.indexOf(clientId) === -1) {
651
+ throw new OAuthError("auth-oauth/aud-mismatch",
652
+ "ID token aud does not contain clientId '" + clientId + "'");
653
+ }
654
+ if (vopts.nonce && !vopts.skipNonceCheck) {
655
+ if (payload.nonce !== vopts.nonce) {
656
+ throw new OAuthError("auth-oauth/nonce-mismatch",
657
+ "ID token nonce mismatch (replay protection)");
658
+ }
659
+ }
660
+ return { header: header, claims: payload };
661
+ }
662
+
663
+ return {
664
+ authorizationUrl: authorizationUrl,
665
+ exchangeCode: exchangeCode,
666
+ refreshAccessToken: refreshAccessToken,
667
+ fetchUserInfo: fetchUserInfo,
668
+ revokeToken: revokeToken,
669
+ verifyIdToken: verifyIdToken,
670
+ discover: _discover,
671
+ // Diagnostic / power-user surface
672
+ issuer: issuer,
673
+ clientId: clientId,
674
+ redirectUri: redirectUri,
675
+ scope: scope,
676
+ isOidc: isOidc,
677
+ };
678
+ }
679
+
680
+ module.exports = {
681
+ create: create,
682
+ PRESETS: PRESETS,
683
+ OAuthError: OAuthError,
684
+ DEFAULT_ACCEPTED_ALGS: DEFAULT_ACCEPTED_ALGS,
685
+ // Internal helpers exposed for tests
686
+ _generatePkce: _generatePkce,
687
+ _generateRandomToken: _generateRandomToken,
688
+ _b64urlEncode: _b64urlEncode,
689
+ _b64urlDecode: _b64urlDecode,
690
+ _verifyParamsForAlg: _verifyParamsForAlg,
691
+ };