@blamejs/core 0.7.1 → 0.7.18
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/CHANGELOG.md +423 -389
- package/README.md +150 -149
- package/bin/blamejs.js +0 -0
- package/index.js +308 -282
- package/lib/api-key.js +660 -672
- package/lib/api-snapshot.js +338 -338
- package/lib/app-shutdown.js +385 -385
- package/lib/app.js +365 -365
- package/lib/archive.js +250 -250
- package/lib/atomic-file.js +544 -544
- package/lib/audit-chain.js +177 -177
- package/lib/audit-sign.js +344 -344
- package/lib/audit-tools.js +677 -677
- package/lib/audit.js +766 -766
- package/lib/auth/jwt.js +311 -311
- package/lib/auth/lockout.js +436 -436
- package/lib/auth/oauth.js +721 -721
- package/lib/auth/passkey.js +181 -181
- package/lib/auth/password.js +594 -594
- package/lib/backup/bundle.js +217 -217
- package/lib/backup/crypto.js +176 -176
- package/lib/backup/index.js +515 -515
- package/lib/backup/manifest.js +282 -282
- package/lib/break-glass.js +1338 -1338
- package/lib/bundler.js +441 -441
- package/lib/cache-redis.js +256 -266
- package/lib/cache.js +1206 -1211
- package/lib/canonical-json.js +115 -115
- package/lib/chain-writer.js +234 -234
- package/lib/cli-helpers.js +206 -206
- package/lib/cli.js +2334 -2334
- package/lib/cluster-provider-db.js +317 -317
- package/lib/cluster-storage.js +226 -226
- package/lib/cluster.js +703 -703
- package/lib/codepoint-class.js +196 -0
- package/lib/config-drift.js +301 -301
- package/lib/consent.js +222 -222
- package/lib/constants.js +191 -191
- package/lib/cookies.js +315 -315
- package/lib/credential-hash.js +322 -322
- package/lib/crypto.js +266 -266
- package/lib/csv.js +275 -286
- package/lib/db-declare-row-policy.js +267 -267
- package/lib/db-declare-view.js +420 -421
- package/lib/db-query.js +406 -406
- package/lib/db-schema.js +319 -319
- package/lib/db.js +1288 -1288
- package/lib/deprecate.js +222 -222
- package/lib/dev.js +335 -335
- package/lib/dual-control.js +473 -473
- package/lib/error-page.js +420 -420
- package/lib/external-db-migrate.js +441 -441
- package/lib/external-db.js +1061 -1061
- package/lib/file-type.js +273 -273
- package/lib/file-upload.js +1136 -0
- package/lib/forms.js +422 -422
- package/lib/framework-error.js +293 -202
- package/lib/framework-schema.js +717 -717
- package/lib/gate-contract.js +971 -0
- package/lib/guard-all.js +405 -0
- package/lib/guard-archive.js +739 -0
- package/lib/guard-csv.js +816 -0
- package/lib/guard-email.js +744 -0
- package/lib/guard-filename.js +724 -0
- package/lib/guard-html.js +976 -0
- package/lib/guard-json.js +729 -0
- package/lib/guard-markdown.js +586 -0
- package/lib/guard-svg.js +976 -0
- package/lib/guard-xml.js +405 -0
- package/lib/guard-yaml.js +529 -0
- package/lib/handlers.js +350 -350
- package/lib/http-client-cookie-jar.js +508 -508
- package/lib/http-client.js +1195 -1195
- package/lib/i18n.js +878 -878
- package/lib/jobs.js +185 -185
- package/lib/log-stream-cloudwatch.js +369 -369
- package/lib/log-stream-local.js +146 -146
- package/lib/log-stream-otlp-grpc.js +410 -410
- package/lib/log-stream-otlp.js +286 -286
- package/lib/log-stream-syslog.js +302 -302
- package/lib/log-stream-webhook.js +199 -199
- package/lib/log-stream.js +330 -330
- package/lib/log.js +500 -500
- package/lib/mail-bounce.js +528 -528
- package/lib/mail-dkim.js +369 -362
- package/lib/mail.js +981 -962
- package/lib/metrics.js +683 -683
- package/lib/middleware/api-encrypt.js +936 -573
- package/lib/middleware/attach-user.js +157 -157
- package/lib/middleware/body-parser.js +1170 -1091
- package/lib/middleware/bot-guard.js +178 -178
- package/lib/middleware/compression.js +452 -452
- package/lib/middleware/cors.js +314 -314
- package/lib/middleware/csp-nonce.js +348 -348
- package/lib/middleware/csrf-protect.js +316 -316
- package/lib/middleware/db-role-for.js +264 -269
- package/lib/middleware/health.js +392 -392
- package/lib/middleware/index.js +79 -79
- package/lib/middleware/rate-limit.js +358 -358
- package/lib/middleware/request-id.js +61 -61
- package/lib/middleware/request-log.js +168 -168
- package/lib/middleware/require-auth.js +104 -104
- package/lib/middleware/security-headers.js +116 -116
- package/lib/middleware/sse.js +166 -166
- package/lib/migrations.js +383 -383
- package/lib/mtls-ca.js +518 -518
- package/lib/mtls-engine-default.js +481 -481
- package/lib/network-dns.js +632 -632
- package/lib/network-heartbeat.js +290 -290
- package/lib/network-nts.js +574 -574
- package/lib/network-proxy.js +265 -265
- package/lib/network-tls.js +328 -328
- package/lib/network.js +233 -233
- package/lib/notify.js +612 -614
- package/lib/ntp-check.js +229 -229
- package/lib/numeric-bounds.js +111 -91
- package/lib/object-store/azure-blob-bucket-ops.js +349 -349
- package/lib/object-store/azure-blob.js +488 -451
- package/lib/object-store/gcs-bucket-ops.js +351 -351
- package/lib/object-store/gcs.js +519 -479
- package/lib/object-store/http-put.js +153 -153
- package/lib/object-store/index.js +197 -197
- package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
- package/lib/object-store/sigv4.js +903 -855
- package/lib/observability.js +151 -151
- package/lib/otel-export.js +269 -269
- package/lib/pagination.js +464 -464
- package/lib/parsers/index.js +80 -80
- package/lib/parsers/safe-env.js +642 -642
- package/lib/parsers/safe-ini.js +292 -292
- package/lib/parsers/safe-toml.js +784 -784
- package/lib/parsers/safe-xml.js +390 -390
- package/lib/parsers/safe-yaml.js +1015 -1015
- package/lib/permissions.js +708 -708
- package/lib/pqc-agent.js +87 -87
- package/lib/pqc-gate.js +279 -279
- package/lib/protobuf-encoder.js +190 -190
- package/lib/protocol-dispatcher.js +161 -161
- package/lib/pubsub-redis.js +167 -177
- package/lib/pubsub.js +429 -429
- package/lib/queue-local.js +476 -476
- package/lib/queue-redis.js +745 -752
- package/lib/queue-sqs.js +319 -319
- package/lib/queue.js +695 -695
- package/lib/redis-client.js +519 -489
- package/lib/request-helpers.js +340 -336
- package/lib/restore-bundle.js +237 -237
- package/lib/restore-rollback.js +259 -259
- package/lib/restore.js +409 -409
- package/lib/retry.js +376 -376
- package/lib/router.js +748 -748
- package/lib/safe-async.js +735 -735
- package/lib/safe-buffer.js +237 -237
- package/lib/safe-json.js +541 -541
- package/lib/safe-schema.js +1266 -1266
- package/lib/safe-url.js +159 -159
- package/lib/scheduler.js +706 -706
- package/lib/security-assert.js +373 -373
- package/lib/seeders.js +618 -630
- package/lib/session.js +478 -478
- package/lib/slug.js +269 -269
- package/lib/ssrf-guard.js +401 -401
- package/lib/static.js +879 -114
- package/lib/storage.js +471 -471
- package/lib/subject.js +281 -281
- package/lib/template.js +791 -791
- package/lib/testing.js +798 -798
- package/lib/time.js +310 -310
- package/lib/totp.js +302 -302
- package/lib/tracing.js +494 -494
- package/lib/uuid.js +132 -132
- package/lib/validate-opts.js +340 -270
- package/lib/vault/index.js +308 -308
- package/lib/vault/rotate.js +784 -784
- package/lib/vault/wrap.js +296 -296
- package/lib/vendor/noble-ciphers.cjs +9 -9
- package/lib/webhook.js +595 -598
- package/lib/websocket.js +1048 -1048
- package/package.json +77 -77
- package/sbom.cyclonedx.json +7 -7
package/lib/auth/oauth.js
CHANGED
|
@@ -1,721 +1,721 @@
|
|
|
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 C = require("../constants");
|
|
110
|
-
var { generateBytes } = require("../crypto");
|
|
111
|
-
var httpClient = require("../http-client");
|
|
112
|
-
var safeJson = require("../safe-json");
|
|
113
|
-
var safeUrl = require("../safe-url");
|
|
114
|
-
var { defineClass } = require("../framework-error");
|
|
115
|
-
var { boot } = require("../log");
|
|
116
|
-
|
|
117
|
-
// Cap on responses parsed from upstream OAuth providers. Token /
|
|
118
|
-
// userinfo / discovery responses are tiny in spec; 256 KiB leaves
|
|
119
|
-
// huge headroom and prevents a hostile (or compromised) upstream
|
|
120
|
-
// from staging a parse-bomb against the framework.
|
|
121
|
-
var OAUTH_MAX_RESPONSE_BYTES = C.BYTES.kib(256);
|
|
122
|
-
|
|
123
|
-
var OAuthError = defineClass("OAuthError", { alwaysPermanent: true });
|
|
124
|
-
var log = boot("auth.oauth");
|
|
125
|
-
|
|
126
|
-
// Vendor presets. Each entry has either { issuer } (OIDC) or explicit
|
|
127
|
-
// endpoints { authorizationEndpoint, tokenEndpoint, userinfoEndpoint }.
|
|
128
|
-
var PRESETS = Object.freeze({
|
|
129
|
-
google: {
|
|
130
|
-
issuer: "https://accounts.google.com",
|
|
131
|
-
defaultScope: ["openid", "email", "profile"],
|
|
132
|
-
isOidc: true,
|
|
133
|
-
},
|
|
134
|
-
microsoft: {
|
|
135
|
-
issuer: "https://login.microsoftonline.com/common/v2.0",
|
|
136
|
-
defaultScope: ["openid", "email", "profile"],
|
|
137
|
-
isOidc: true,
|
|
138
|
-
},
|
|
139
|
-
apple: {
|
|
140
|
-
issuer: "https://appleid.apple.com",
|
|
141
|
-
defaultScope: ["openid", "email", "name"],
|
|
142
|
-
isOidc: true,
|
|
143
|
-
// Apple wants form_post response_mode (browser POSTs back to redirect).
|
|
144
|
-
responseMode: "form_post",
|
|
145
|
-
},
|
|
146
|
-
auth0: {
|
|
147
|
-
// Operator passes auth0Domain: "tenant.auth0.com" via opts; we
|
|
148
|
-
// expand it into the issuer URL.
|
|
149
|
-
issuerTemplate: function (opts) {
|
|
150
|
-
if (!opts.auth0Domain) {
|
|
151
|
-
throw new OAuthError("auth-oauth/auth0-domain",
|
|
152
|
-
"auth0 preset requires opts.auth0Domain ('your-tenant.auth0.com')");
|
|
153
|
-
}
|
|
154
|
-
return "https://" + opts.auth0Domain;
|
|
155
|
-
},
|
|
156
|
-
defaultScope: ["openid", "email", "profile"],
|
|
157
|
-
isOidc: true,
|
|
158
|
-
},
|
|
159
|
-
keycloak: {
|
|
160
|
-
// Keycloak realms: opts.keycloakUrl + opts.keycloakRealm
|
|
161
|
-
issuerTemplate: function (opts) {
|
|
162
|
-
if (!opts.keycloakUrl || !opts.keycloakRealm) {
|
|
163
|
-
throw new OAuthError("auth-oauth/keycloak-config",
|
|
164
|
-
"keycloak preset requires opts.keycloakUrl and opts.keycloakRealm");
|
|
165
|
-
}
|
|
166
|
-
return opts.keycloakUrl.replace(/\/$/, "") + "/realms/" + opts.keycloakRealm;
|
|
167
|
-
},
|
|
168
|
-
defaultScope: ["openid", "email", "profile"],
|
|
169
|
-
isOidc: true,
|
|
170
|
-
},
|
|
171
|
-
github: {
|
|
172
|
-
// GitHub is OAuth 2 only — no OIDC, no ID tokens, no JWKS.
|
|
173
|
-
authorizationEndpoint: "https://github.com/login/oauth/authorize",
|
|
174
|
-
tokenEndpoint: "https://github.com/login/oauth/access_token",
|
|
175
|
-
userinfoEndpoint: "https://api.github.com/user",
|
|
176
|
-
defaultScope: ["read:user", "user:email"],
|
|
177
|
-
isOidc: false,
|
|
178
|
-
},
|
|
179
|
-
generic: {
|
|
180
|
-
// Operator-defined endpoints (or issuer-driven discovery). The
|
|
181
|
-
// preset itself adds nothing — its presence makes provider:'generic'
|
|
182
|
-
// a valid explicit selector instead of falling through to "unknown
|
|
183
|
-
// provider preset". Operators pass authorizationEndpoint /
|
|
184
|
-
// tokenEndpoint / userinfoEndpoint (or issuer + isOidc:true to
|
|
185
|
-
// discover) on opts.
|
|
186
|
-
},
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
var DEFAULT_ACCEPTED_ALGS = Object.freeze([
|
|
190
|
-
"RS256", "RS384", "RS512",
|
|
191
|
-
"ES256", "ES384", "ES512",
|
|
192
|
-
"PS256", "PS384", "PS512",
|
|
193
|
-
]);
|
|
194
|
-
|
|
195
|
-
var DEFAULT_DISCOVERY_CACHE_MS = C.TIME.hours(1);
|
|
196
|
-
var DEFAULT_CLOCK_SKEW_MS = C.TIME.minutes(1);
|
|
197
|
-
|
|
198
|
-
// Random material lengths. PKCE verifier per RFC 7636 §4.1 needs >= 256
|
|
199
|
-
// bits of entropy; 32 bytes hits that exactly. State + nonce are 16
|
|
200
|
-
// bytes (128-bit unguessability) which is the minimum recommended by
|
|
201
|
-
// OAuth 2.0 Threat Model §4.4.1.8 / §4.4.1.13.
|
|
202
|
-
var PKCE_VERIFIER_BYTES = C.BYTES.bytes(32);
|
|
203
|
-
var STATE_NONCE_BYTES = C.BYTES.bytes(16);
|
|
204
|
-
// JOSE PSS salt lengths (RFC 7518 §3.5) match the hash-output size:
|
|
205
|
-
// PS256/SHA-256 → 32, PS384/SHA-384 → 48, PS512/SHA-512 → 64.
|
|
206
|
-
var PSS_SALT_BYTES_SHA256 = C.BYTES.bytes(32);
|
|
207
|
-
var PSS_SALT_BYTES_SHA384 = C.BYTES.bytes(48);
|
|
208
|
-
var PSS_SALT_BYTES_SHA512 = C.BYTES.bytes(64);
|
|
209
|
-
|
|
210
|
-
// ---- helpers ----
|
|
211
|
-
|
|
212
|
-
function _b64urlEncode(buf) {
|
|
213
|
-
if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
|
|
214
|
-
return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function _b64urlDecode(s) {
|
|
218
|
-
if (typeof s !== "string") throw new OAuthError("auth-oauth/bad-base64", "expected base64url string");
|
|
219
|
-
var padded = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
220
|
-
while (padded.length % 4) padded += "=";
|
|
221
|
-
return Buffer.from(padded, "base64");
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function _generateRandomToken(bytes) {
|
|
225
|
-
return _b64urlEncode(generateBytes(bytes));
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
function _generatePkce() {
|
|
229
|
-
// RFC 7636: code_verifier is 43–128 chars [A-Za-z0-9-._~].
|
|
230
|
-
// base64url of 32 random bytes = 43 chars, all valid.
|
|
231
|
-
var verifier = _b64urlEncode(generateBytes(PKCE_VERIFIER_BYTES));
|
|
232
|
-
var challenge = _b64urlEncode(nodeCrypto.createHash("sha256").update(verifier).digest());
|
|
233
|
-
return { verifier: verifier, challenge: challenge };
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function _validateUrl(url, allowHttp, label) {
|
|
237
|
-
if (typeof url !== "string" || url.length === 0) {
|
|
238
|
-
throw new OAuthError("auth-oauth/bad-url", label + ": URL is required");
|
|
239
|
-
}
|
|
240
|
-
// Operator-supplied OAuth issuer / endpoint URL — route through
|
|
241
|
-
// safeUrl so the scheme allowlist is consistent with the rest of the
|
|
242
|
-
// framework's outbound gates. Map safe-url's error codes to the
|
|
243
|
-
// domain-specific oauth codes operators already key alerts on.
|
|
244
|
-
try {
|
|
245
|
-
safeUrl.parse(url, {
|
|
246
|
-
allowedProtocols: allowHttp ? safeUrl.ALLOW_HTTP_ALL : safeUrl.ALLOW_HTTP_TLS,
|
|
247
|
-
});
|
|
248
|
-
} catch (e) {
|
|
249
|
-
if (e && e.code === "safe-url/protocol-disallowed") {
|
|
250
|
-
throw new OAuthError("auth-oauth/insecure-url",
|
|
251
|
-
label + ": must be https" + (allowHttp ? " or http" : "") +
|
|
252
|
-
" (got '" + url + "')");
|
|
253
|
-
}
|
|
254
|
-
throw new OAuthError("auth-oauth/bad-url",
|
|
255
|
-
label + ": invalid URL '" + url + "'");
|
|
256
|
-
}
|
|
257
|
-
return url;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// ---- JOSE alg → node:crypto verify parameters ----
|
|
261
|
-
|
|
262
|
-
function _verifyParamsForAlg(alg) {
|
|
263
|
-
// Returns { hash, padding, dsaEncoding } for node:crypto.verify.
|
|
264
|
-
if (alg === "RS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
265
|
-
if (alg === "RS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
266
|
-
if (alg === "RS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
267
|
-
if (alg === "PS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA256 };
|
|
268
|
-
if (alg === "PS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA384 };
|
|
269
|
-
if (alg === "PS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA512 };
|
|
270
|
-
if (alg === "ES256") return { hash: "sha256", dsaEncoding: "ieee-p1363" };
|
|
271
|
-
if (alg === "ES384") return { hash: "sha384", dsaEncoding: "ieee-p1363" };
|
|
272
|
-
if (alg === "ES512") return { hash: "sha512", dsaEncoding: "ieee-p1363" };
|
|
273
|
-
throw new OAuthError("auth-oauth/unsupported-alg",
|
|
274
|
-
"alg '" + alg + "' is not supported for ID-token verification");
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// ---- JWKS → KeyObject ----
|
|
278
|
-
|
|
279
|
-
function _jwkToKey(jwk) {
|
|
280
|
-
// node's createPublicKey accepts JWK directly since Node 16.
|
|
281
|
-
try { return nodeCrypto.createPublicKey({ key: jwk, format: "jwk" }); }
|
|
282
|
-
catch (e) {
|
|
283
|
-
throw new OAuthError("auth-oauth/bad-jwk",
|
|
284
|
-
"could not import JWK (kid=" + (jwk && jwk.kid) + "): " + ((e && e.message) || String(e)));
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// ---- core ----
|
|
289
|
-
|
|
290
|
-
function create(opts) {
|
|
291
|
-
opts = opts || {};
|
|
292
|
-
var clientId = opts.clientId;
|
|
293
|
-
var clientSecret = opts.clientSecret || null; // public clients can omit
|
|
294
|
-
var redirectUri = opts.redirectUri;
|
|
295
|
-
var pkce = opts.pkce !== false;
|
|
296
|
-
var clockSkewMs = typeof opts.clockSkewMs === "number" ? opts.clockSkewMs : DEFAULT_CLOCK_SKEW_MS;
|
|
297
|
-
var discoveryCacheMs = typeof opts.discoveryCacheMs === "number"
|
|
298
|
-
? opts.discoveryCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
|
|
299
|
-
var acceptedAlgorithms = Array.isArray(opts.acceptedAlgorithms) && opts.acceptedAlgorithms.length > 0
|
|
300
|
-
? opts.acceptedAlgorithms.slice() : DEFAULT_ACCEPTED_ALGS.slice();
|
|
301
|
-
var allowHttp = !!opts.allowHttp; // localhost dev opt-in (scheme)
|
|
302
|
-
var allowInternal = opts.allowInternal != null ? opts.allowInternal : null; // localhost dev opt-in (SSRF gate)
|
|
303
|
-
var httpClientOpts = opts.httpClient || {};
|
|
304
|
-
var responseMode = opts.responseMode || null;
|
|
305
|
-
|
|
306
|
-
if (!clientId) {
|
|
307
|
-
throw new OAuthError("auth-oauth/no-client-id", "create: opts.clientId is required");
|
|
308
|
-
}
|
|
309
|
-
if (!redirectUri) {
|
|
310
|
-
throw new OAuthError("auth-oauth/no-redirect-uri", "create: opts.redirectUri is required");
|
|
311
|
-
}
|
|
312
|
-
_validateUrl(redirectUri, allowHttp, "redirectUri");
|
|
313
|
-
if (!pkce) {
|
|
314
|
-
log("WARNING: PKCE disabled — modern IdPs require it; this should only be used for legacy providers");
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// Resolve preset → effective config.
|
|
318
|
-
var preset = null;
|
|
319
|
-
if (opts.provider) {
|
|
320
|
-
if (!Object.prototype.hasOwnProperty.call(PRESETS, opts.provider)) {
|
|
321
|
-
throw new OAuthError("auth-oauth/unknown-provider",
|
|
322
|
-
"unknown provider preset '" + opts.provider + "' (known: " +
|
|
323
|
-
Object.keys(PRESETS).join(", ") + ")");
|
|
324
|
-
}
|
|
325
|
-
preset = PRESETS[opts.provider];
|
|
326
|
-
}
|
|
327
|
-
var isOidc = (preset && typeof preset.isOidc === "boolean") ? preset.isOidc
|
|
328
|
-
: (opts.isOidc !== undefined ? !!opts.isOidc : true);
|
|
329
|
-
var issuer = opts.issuer
|
|
330
|
-
|| (preset && typeof preset.issuerTemplate === "function" && preset.issuerTemplate(opts))
|
|
331
|
-
|| (preset && preset.issuer)
|
|
332
|
-
|| null;
|
|
333
|
-
var scope = Array.isArray(opts.scope) && opts.scope.length > 0
|
|
334
|
-
? opts.scope.slice()
|
|
335
|
-
: (preset && preset.defaultScope ? preset.defaultScope.slice() : ["openid"]);
|
|
336
|
-
if (!responseMode && preset && preset.responseMode) responseMode = preset.responseMode;
|
|
337
|
-
|
|
338
|
-
// Endpoints — either from preset (explicit), discovery, or operator opts.
|
|
339
|
-
var staticEndpoints = {
|
|
340
|
-
authorizationEndpoint: opts.authorizationEndpoint || (preset && preset.authorizationEndpoint) || null,
|
|
341
|
-
tokenEndpoint: opts.tokenEndpoint || (preset && preset.tokenEndpoint) || null,
|
|
342
|
-
userinfoEndpoint: opts.userinfoEndpoint || (preset && preset.userinfoEndpoint) || null,
|
|
343
|
-
revocationEndpoint: opts.revocationEndpoint || (preset && preset.revocationEndpoint) || null,
|
|
344
|
-
jwksUri: opts.jwksUri || (preset && preset.jwksUri) || null,
|
|
345
|
-
};
|
|
346
|
-
|
|
347
|
-
// Discovery + JWKS caches use b.cache.create + .wrap so concurrent
|
|
348
|
-
// boot races for the same IdP collapse to one fetch (single-flight)
|
|
349
|
-
// and operators can wire b.audit / observability without us
|
|
350
|
-
// re-implementing those hooks here. Per-cache namespaces are unique
|
|
351
|
-
// per oauth-client instance (clientId-scoped) so two clients pointed
|
|
352
|
-
// at different IdPs don't collide in a future cluster-cache backend.
|
|
353
|
-
var jwksCacheMs = typeof opts.jwksCacheMs === "number" ? opts.jwksCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
|
|
354
|
-
var _discoveryCache = cache.create({
|
|
355
|
-
namespace: "oauth.discovery." + clientId,
|
|
356
|
-
ttlMs: discoveryCacheMs,
|
|
357
|
-
});
|
|
358
|
-
var _jwksCache = cache.create({
|
|
359
|
-
namespace: "oauth.jwks." + clientId,
|
|
360
|
-
ttlMs: jwksCacheMs,
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
async function _fetchJson(url, fetchOpts) {
|
|
364
|
-
fetchOpts = fetchOpts || {};
|
|
365
|
-
var hc = httpClient;
|
|
366
|
-
var req = Object.assign({
|
|
367
|
-
url: url,
|
|
368
|
-
method: "GET",
|
|
369
|
-
}, fetchOpts);
|
|
370
|
-
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
371
|
-
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
372
|
-
Object.assign(req, httpClientOpts);
|
|
373
|
-
var res = await hc.request(req);
|
|
374
|
-
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
375
|
-
var bodyText = res.body ? res.body.toString("utf8") : "";
|
|
376
|
-
throw new OAuthError("auth-oauth/http-" + res.statusCode,
|
|
377
|
-
url + " returned " + res.statusCode + ": " + bodyText.slice(0, 500));
|
|
378
|
-
}
|
|
379
|
-
if (!res.body) return null;
|
|
380
|
-
try { return safeJson.parse(res.body.toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES }); }
|
|
381
|
-
catch (e) {
|
|
382
|
-
throw new OAuthError("auth-oauth/bad-json",
|
|
383
|
-
url + " response not JSON: " + ((e && e.message) || String(e)));
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
async function _discover() {
|
|
388
|
-
if (!isOidc || !issuer) return null;
|
|
389
|
-
return _discoveryCache.wrap("config", async function () {
|
|
390
|
-
var url = issuer.replace(/\/$/, "") + "/.well-known/openid-configuration";
|
|
391
|
-
_validateUrl(url, allowHttp, "discovery url");
|
|
392
|
-
var config = await _fetchJson(url);
|
|
393
|
-
if (!config || typeof config !== "object") {
|
|
394
|
-
throw new OAuthError("auth-oauth/bad-discovery", "discovery document missing");
|
|
395
|
-
}
|
|
396
|
-
if (config.issuer && config.issuer !== issuer) {
|
|
397
|
-
throw new OAuthError("auth-oauth/issuer-mismatch",
|
|
398
|
-
"discovery issuer '" + config.issuer + "' does not match configured issuer '" + issuer + "'");
|
|
399
|
-
}
|
|
400
|
-
return config;
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
async function _resolveEndpoint(name) {
|
|
405
|
-
if (staticEndpoints[name]) return staticEndpoints[name];
|
|
406
|
-
var config = await _discover();
|
|
407
|
-
if (!config) {
|
|
408
|
-
throw new OAuthError("auth-oauth/no-endpoint",
|
|
409
|
-
name + " endpoint not configured and no OIDC discovery available");
|
|
410
|
-
}
|
|
411
|
-
// OIDC discovery uses snake_case key names.
|
|
412
|
-
var snake = ({
|
|
413
|
-
authorizationEndpoint: "authorization_endpoint",
|
|
414
|
-
tokenEndpoint: "token_endpoint",
|
|
415
|
-
userinfoEndpoint: "userinfo_endpoint",
|
|
416
|
-
revocationEndpoint: "revocation_endpoint",
|
|
417
|
-
jwksUri: "jwks_uri",
|
|
418
|
-
})[name];
|
|
419
|
-
var endpoint = config[snake];
|
|
420
|
-
if (!endpoint) {
|
|
421
|
-
throw new OAuthError("auth-oauth/no-endpoint",
|
|
422
|
-
name + " not present in discovery document");
|
|
423
|
-
}
|
|
424
|
-
return endpoint;
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
async function authorizationUrl(uopts) {
|
|
428
|
-
uopts = uopts || {};
|
|
429
|
-
var endpoint = await _resolveEndpoint("authorizationEndpoint");
|
|
430
|
-
var state = uopts.state || _generateRandomToken(STATE_NONCE_BYTES);
|
|
431
|
-
var nonce = uopts.nonce || (isOidc ? _generateRandomToken(STATE_NONCE_BYTES) : null);
|
|
432
|
-
var pkceVals = pkce ? _generatePkce() : null;
|
|
433
|
-
var params = new URLSearchParams();
|
|
434
|
-
params.set("response_type", "code");
|
|
435
|
-
params.set("client_id", clientId);
|
|
436
|
-
params.set("redirect_uri", redirectUri);
|
|
437
|
-
params.set("scope", scope.join(" "));
|
|
438
|
-
params.set("state", state);
|
|
439
|
-
if (nonce) params.set("nonce", nonce);
|
|
440
|
-
if (pkceVals) {
|
|
441
|
-
params.set("code_challenge", pkceVals.challenge);
|
|
442
|
-
params.set("code_challenge_method", "S256");
|
|
443
|
-
}
|
|
444
|
-
if (responseMode) params.set("response_mode", responseMode);
|
|
445
|
-
if (uopts.prompt) params.set("prompt", uopts.prompt);
|
|
446
|
-
if (uopts.loginHint) params.set("login_hint", uopts.loginHint);
|
|
447
|
-
if (uopts.maxAge != null) params.set("max_age", String(uopts.maxAge));
|
|
448
|
-
// Operator-supplied additional params (audience, resource, etc.).
|
|
449
|
-
if (uopts.extraParams && typeof uopts.extraParams === "object") {
|
|
450
|
-
var ek = Object.keys(uopts.extraParams);
|
|
451
|
-
for (var i = 0; i < ek.length; i++) params.set(ek[i], String(uopts.extraParams[ek[i]]));
|
|
452
|
-
}
|
|
453
|
-
var sep = endpoint.indexOf("?") === -1 ? "?" : "&";
|
|
454
|
-
return {
|
|
455
|
-
url: endpoint + sep + params.toString(),
|
|
456
|
-
state: state,
|
|
457
|
-
nonce: nonce,
|
|
458
|
-
verifier: pkceVals ? pkceVals.verifier : null,
|
|
459
|
-
challenge: pkceVals ? pkceVals.challenge : null,
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
async function exchangeCode(eopts) {
|
|
464
|
-
eopts = eopts || {};
|
|
465
|
-
if (!eopts.code) {
|
|
466
|
-
throw new OAuthError("auth-oauth/no-code", "exchangeCode: opts.code is required");
|
|
467
|
-
}
|
|
468
|
-
if (pkce && !eopts.verifier) {
|
|
469
|
-
throw new OAuthError("auth-oauth/no-verifier",
|
|
470
|
-
"exchangeCode: opts.verifier is required when PKCE is on (default)");
|
|
471
|
-
}
|
|
472
|
-
var endpoint = await _resolveEndpoint("tokenEndpoint");
|
|
473
|
-
var body = new URLSearchParams();
|
|
474
|
-
body.set("grant_type", "authorization_code");
|
|
475
|
-
body.set("code", eopts.code);
|
|
476
|
-
body.set("redirect_uri", redirectUri);
|
|
477
|
-
body.set("client_id", clientId);
|
|
478
|
-
if (clientSecret) body.set("client_secret", clientSecret);
|
|
479
|
-
if (eopts.verifier) body.set("code_verifier", eopts.verifier);
|
|
480
|
-
|
|
481
|
-
var tokens = await _postForm(endpoint, body);
|
|
482
|
-
return await _normalizeTokens(tokens, { nonce: eopts.nonce });
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
async function refreshAccessToken(refreshToken) {
|
|
486
|
-
if (!refreshToken) {
|
|
487
|
-
throw new OAuthError("auth-oauth/no-refresh-token",
|
|
488
|
-
"refreshAccessToken: refresh token is required");
|
|
489
|
-
}
|
|
490
|
-
var endpoint = await _resolveEndpoint("tokenEndpoint");
|
|
491
|
-
var body = new URLSearchParams();
|
|
492
|
-
body.set("grant_type", "refresh_token");
|
|
493
|
-
body.set("refresh_token", refreshToken);
|
|
494
|
-
body.set("client_id", clientId);
|
|
495
|
-
if (clientSecret) body.set("client_secret", clientSecret);
|
|
496
|
-
var tokens = await _postForm(endpoint, body);
|
|
497
|
-
// Refreshed tokens may not include a new id_token; verification
|
|
498
|
-
// is conditional.
|
|
499
|
-
return await _normalizeTokens(tokens, { skipNonceCheck: true });
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
async function fetchUserInfo(accessToken) {
|
|
503
|
-
if (!accessToken) {
|
|
504
|
-
throw new OAuthError("auth-oauth/no-access-token",
|
|
505
|
-
"fetchUserInfo: access token is required");
|
|
506
|
-
}
|
|
507
|
-
var endpoint = await _resolveEndpoint("userinfoEndpoint");
|
|
508
|
-
return await _fetchJson(endpoint, {
|
|
509
|
-
headers: {
|
|
510
|
-
"Authorization": "Bearer " + accessToken,
|
|
511
|
-
"Accept": "application/json",
|
|
512
|
-
"User-Agent": "blamejs",
|
|
513
|
-
},
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
async function revokeToken(token, ropts) {
|
|
518
|
-
if (!token) {
|
|
519
|
-
throw new OAuthError("auth-oauth/no-token", "revokeToken: token is required");
|
|
520
|
-
}
|
|
521
|
-
ropts = ropts || {};
|
|
522
|
-
var endpoint = await _resolveEndpoint("revocationEndpoint");
|
|
523
|
-
var body = new URLSearchParams();
|
|
524
|
-
body.set("token", token);
|
|
525
|
-
if (ropts.type) body.set("token_type_hint", ropts.type);
|
|
526
|
-
body.set("client_id", clientId);
|
|
527
|
-
if (clientSecret) body.set("client_secret", clientSecret);
|
|
528
|
-
var hc = httpClient;
|
|
529
|
-
var req = {
|
|
530
|
-
url: endpoint,
|
|
531
|
-
method: "POST",
|
|
532
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
533
|
-
body: Buffer.from(body.toString(), "utf8"),
|
|
534
|
-
};
|
|
535
|
-
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
536
|
-
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
537
|
-
Object.assign(req, httpClientOpts);
|
|
538
|
-
var res = await hc.request(req);
|
|
539
|
-
// RFC 7009: 200 even if the token was already revoked / unknown.
|
|
540
|
-
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
541
|
-
throw new OAuthError("auth-oauth/revoke-failed",
|
|
542
|
-
"revocation returned " + res.statusCode);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
async function _postForm(endpoint, body) {
|
|
547
|
-
var hc = httpClient;
|
|
548
|
-
var req = {
|
|
549
|
-
url: endpoint,
|
|
550
|
-
method: "POST",
|
|
551
|
-
headers: {
|
|
552
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
553
|
-
"Accept": "application/json",
|
|
554
|
-
},
|
|
555
|
-
body: Buffer.from(body.toString(), "utf8"),
|
|
556
|
-
};
|
|
557
|
-
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
558
|
-
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
559
|
-
Object.assign(req, httpClientOpts);
|
|
560
|
-
var res = await hc.request(req);
|
|
561
|
-
var text = res.body ? res.body.toString("utf8") : "";
|
|
562
|
-
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
563
|
-
throw new OAuthError("auth-oauth/token-error-" + res.statusCode,
|
|
564
|
-
endpoint + " returned " + res.statusCode + ": " + text.slice(0, 500));
|
|
565
|
-
}
|
|
566
|
-
var parsed;
|
|
567
|
-
try { parsed = safeJson.parse(text, { maxBytes: OAUTH_MAX_RESPONSE_BYTES }); }
|
|
568
|
-
catch (e) {
|
|
569
|
-
throw new OAuthError("auth-oauth/bad-token-json",
|
|
570
|
-
"token endpoint response not JSON: " + ((e && e.message) || String(e)));
|
|
571
|
-
}
|
|
572
|
-
return parsed;
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
async function _normalizeTokens(raw, vopts) {
|
|
576
|
-
vopts = vopts || {};
|
|
577
|
-
var tokens = {
|
|
578
|
-
accessToken: raw.access_token,
|
|
579
|
-
tokenType: raw.token_type || "Bearer",
|
|
580
|
-
expiresIn: raw.expires_in || null,
|
|
581
|
-
refreshToken: raw.refresh_token || null,
|
|
582
|
-
idToken: raw.id_token || null,
|
|
583
|
-
scope: raw.scope ? raw.scope.split(/\s+/) : scope.slice(),
|
|
584
|
-
raw: raw,
|
|
585
|
-
};
|
|
586
|
-
if (tokens.idToken && isOidc) {
|
|
587
|
-
var v = await verifyIdToken(tokens.idToken, {
|
|
588
|
-
nonce: vopts.nonce,
|
|
589
|
-
skipNonceCheck: vopts.skipNonceCheck,
|
|
590
|
-
});
|
|
591
|
-
tokens.claims = v.claims;
|
|
592
|
-
tokens.profile = {
|
|
593
|
-
sub: v.claims.sub,
|
|
594
|
-
email: v.claims.email,
|
|
595
|
-
name: v.claims.name,
|
|
596
|
-
picture: v.claims.picture,
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
return tokens;
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
async function _getJwks() {
|
|
603
|
-
return _jwksCache.wrap("keys", async function () {
|
|
604
|
-
var jwksUri = await _resolveEndpoint("jwksUri");
|
|
605
|
-
var jwks = await _fetchJson(jwksUri);
|
|
606
|
-
if (!jwks || !Array.isArray(jwks.keys)) {
|
|
607
|
-
throw new OAuthError("auth-oauth/bad-jwks", "JWKS response missing 'keys' array");
|
|
608
|
-
}
|
|
609
|
-
return jwks.keys;
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
async function verifyIdToken(idToken, vopts) {
|
|
614
|
-
vopts = vopts || {};
|
|
615
|
-
if (typeof idToken !== "string") {
|
|
616
|
-
throw new OAuthError("auth-oauth/no-id-token", "verifyIdToken: idToken must be a string");
|
|
617
|
-
}
|
|
618
|
-
var parts = idToken.split(".");
|
|
619
|
-
if (parts.length !== 3) {
|
|
620
|
-
throw new OAuthError("auth-oauth/malformed-jwt", "ID token does not have 3 parts");
|
|
621
|
-
}
|
|
622
|
-
var header, payload;
|
|
623
|
-
try {
|
|
624
|
-
header = safeJson.parse(_b64urlDecode(parts[0]).toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES });
|
|
625
|
-
payload = safeJson.parse(_b64urlDecode(parts[1]).toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES });
|
|
626
|
-
} catch (e) {
|
|
627
|
-
throw new OAuthError("auth-oauth/malformed-jwt",
|
|
628
|
-
"ID token header/payload base64 decode failed: " + ((e && e.message) || String(e)));
|
|
629
|
-
}
|
|
630
|
-
if (!header || typeof header.alg !== "string") {
|
|
631
|
-
throw new OAuthError("auth-oauth/malformed-jwt", "ID token header missing 'alg'");
|
|
632
|
-
}
|
|
633
|
-
if (acceptedAlgorithms.indexOf(header.alg) === -1) {
|
|
634
|
-
throw new OAuthError("auth-oauth/alg-not-accepted",
|
|
635
|
-
"ID token signed with '" + header.alg + "' which is not in the accepted-algorithm list");
|
|
636
|
-
}
|
|
637
|
-
var keys = await _getJwks();
|
|
638
|
-
var match = null;
|
|
639
|
-
if (header.kid) {
|
|
640
|
-
for (var i = 0; i < keys.length; i++) {
|
|
641
|
-
if (keys[i].kid === header.kid) { match = keys[i]; break; }
|
|
642
|
-
}
|
|
643
|
-
} else if (keys.length === 1) {
|
|
644
|
-
match = keys[0];
|
|
645
|
-
}
|
|
646
|
-
if (!match) {
|
|
647
|
-
throw new OAuthError("auth-oauth/no-matching-key",
|
|
648
|
-
"no JWKS key matches header.kid='" + header.kid + "'");
|
|
649
|
-
}
|
|
650
|
-
var keyObject = _jwkToKey(match);
|
|
651
|
-
var params = _verifyParamsForAlg(header.alg);
|
|
652
|
-
var signingInput = parts[0] + "." + parts[1];
|
|
653
|
-
var sig = _b64urlDecode(parts[2]);
|
|
654
|
-
var verifyOpts = { key: keyObject };
|
|
655
|
-
if (params.padding !== undefined) verifyOpts.padding = params.padding;
|
|
656
|
-
if (params.saltLength !== undefined) verifyOpts.saltLength = params.saltLength;
|
|
657
|
-
if (params.dsaEncoding !== undefined) verifyOpts.dsaEncoding = params.dsaEncoding;
|
|
658
|
-
var verified = nodeCrypto.verify(params.hash, Buffer.from(signingInput, "ascii"), verifyOpts, sig);
|
|
659
|
-
if (!verified) {
|
|
660
|
-
throw new OAuthError("auth-oauth/bad-signature", "ID token signature verification failed");
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
// Claim validation.
|
|
664
|
-
var now = Math.floor(Date.now() / C.TIME.seconds(1));
|
|
665
|
-
var skewSec = Math.floor(clockSkewMs / C.TIME.seconds(1));
|
|
666
|
-
if (typeof payload.exp !== "number" || payload.exp + skewSec < now) {
|
|
667
|
-
throw new OAuthError("auth-oauth/expired", "ID token expired (exp=" + payload.exp + ", now=" + now + ")");
|
|
668
|
-
}
|
|
669
|
-
if (typeof payload.iat === "number" && payload.iat - skewSec > now) {
|
|
670
|
-
throw new OAuthError("auth-oauth/iat-future", "ID token iat is in the future");
|
|
671
|
-
}
|
|
672
|
-
if (typeof payload.nbf === "number" && payload.nbf - skewSec > now) {
|
|
673
|
-
throw new OAuthError("auth-oauth/nbf-future", "ID token nbf is in the future");
|
|
674
|
-
}
|
|
675
|
-
if (issuer && payload.iss !== issuer) {
|
|
676
|
-
throw new OAuthError("auth-oauth/iss-mismatch",
|
|
677
|
-
"ID token iss '" + payload.iss + "' does not match expected '" + issuer + "'");
|
|
678
|
-
}
|
|
679
|
-
var aud = Array.isArray(payload.aud) ? payload.aud : (payload.aud ? [payload.aud] : []);
|
|
680
|
-
if (aud.indexOf(clientId) === -1) {
|
|
681
|
-
throw new OAuthError("auth-oauth/aud-mismatch",
|
|
682
|
-
"ID token aud does not contain clientId '" + clientId + "'");
|
|
683
|
-
}
|
|
684
|
-
if (vopts.nonce && !vopts.skipNonceCheck) {
|
|
685
|
-
if (payload.nonce !== vopts.nonce) {
|
|
686
|
-
throw new OAuthError("auth-oauth/nonce-mismatch",
|
|
687
|
-
"ID token nonce mismatch (replay protection)");
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
return { header: header, claims: payload };
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
return {
|
|
694
|
-
authorizationUrl: authorizationUrl,
|
|
695
|
-
exchangeCode: exchangeCode,
|
|
696
|
-
refreshAccessToken: refreshAccessToken,
|
|
697
|
-
fetchUserInfo: fetchUserInfo,
|
|
698
|
-
revokeToken: revokeToken,
|
|
699
|
-
verifyIdToken: verifyIdToken,
|
|
700
|
-
discover: _discover,
|
|
701
|
-
// Diagnostic / power-user surface
|
|
702
|
-
issuer: issuer,
|
|
703
|
-
clientId: clientId,
|
|
704
|
-
redirectUri: redirectUri,
|
|
705
|
-
scope: scope,
|
|
706
|
-
isOidc: isOidc,
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
module.exports = {
|
|
711
|
-
create: create,
|
|
712
|
-
PRESETS: PRESETS,
|
|
713
|
-
OAuthError: OAuthError,
|
|
714
|
-
DEFAULT_ACCEPTED_ALGS: DEFAULT_ACCEPTED_ALGS,
|
|
715
|
-
// Internal helpers exposed for tests
|
|
716
|
-
_generatePkce: _generatePkce,
|
|
717
|
-
_generateRandomToken: _generateRandomToken,
|
|
718
|
-
_b64urlEncode: _b64urlEncode,
|
|
719
|
-
_b64urlDecode: _b64urlDecode,
|
|
720
|
-
_verifyParamsForAlg: _verifyParamsForAlg,
|
|
721
|
-
};
|
|
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 C = require("../constants");
|
|
110
|
+
var { generateBytes } = require("../crypto");
|
|
111
|
+
var httpClient = require("../http-client");
|
|
112
|
+
var safeJson = require("../safe-json");
|
|
113
|
+
var safeUrl = require("../safe-url");
|
|
114
|
+
var { defineClass } = require("../framework-error");
|
|
115
|
+
var { boot } = require("../log");
|
|
116
|
+
|
|
117
|
+
// Cap on responses parsed from upstream OAuth providers. Token /
|
|
118
|
+
// userinfo / discovery responses are tiny in spec; 256 KiB leaves
|
|
119
|
+
// huge headroom and prevents a hostile (or compromised) upstream
|
|
120
|
+
// from staging a parse-bomb against the framework.
|
|
121
|
+
var OAUTH_MAX_RESPONSE_BYTES = C.BYTES.kib(256);
|
|
122
|
+
|
|
123
|
+
var OAuthError = defineClass("OAuthError", { alwaysPermanent: true });
|
|
124
|
+
var log = boot("auth.oauth");
|
|
125
|
+
|
|
126
|
+
// Vendor presets. Each entry has either { issuer } (OIDC) or explicit
|
|
127
|
+
// endpoints { authorizationEndpoint, tokenEndpoint, userinfoEndpoint }.
|
|
128
|
+
var PRESETS = Object.freeze({
|
|
129
|
+
google: {
|
|
130
|
+
issuer: "https://accounts.google.com",
|
|
131
|
+
defaultScope: ["openid", "email", "profile"],
|
|
132
|
+
isOidc: true,
|
|
133
|
+
},
|
|
134
|
+
microsoft: {
|
|
135
|
+
issuer: "https://login.microsoftonline.com/common/v2.0",
|
|
136
|
+
defaultScope: ["openid", "email", "profile"],
|
|
137
|
+
isOidc: true,
|
|
138
|
+
},
|
|
139
|
+
apple: {
|
|
140
|
+
issuer: "https://appleid.apple.com",
|
|
141
|
+
defaultScope: ["openid", "email", "name"],
|
|
142
|
+
isOidc: true,
|
|
143
|
+
// Apple wants form_post response_mode (browser POSTs back to redirect).
|
|
144
|
+
responseMode: "form_post",
|
|
145
|
+
},
|
|
146
|
+
auth0: {
|
|
147
|
+
// Operator passes auth0Domain: "tenant.auth0.com" via opts; we
|
|
148
|
+
// expand it into the issuer URL.
|
|
149
|
+
issuerTemplate: function (opts) {
|
|
150
|
+
if (!opts.auth0Domain) {
|
|
151
|
+
throw new OAuthError("auth-oauth/auth0-domain",
|
|
152
|
+
"auth0 preset requires opts.auth0Domain ('your-tenant.auth0.com')");
|
|
153
|
+
}
|
|
154
|
+
return "https://" + opts.auth0Domain;
|
|
155
|
+
},
|
|
156
|
+
defaultScope: ["openid", "email", "profile"],
|
|
157
|
+
isOidc: true,
|
|
158
|
+
},
|
|
159
|
+
keycloak: {
|
|
160
|
+
// Keycloak realms: opts.keycloakUrl + opts.keycloakRealm
|
|
161
|
+
issuerTemplate: function (opts) {
|
|
162
|
+
if (!opts.keycloakUrl || !opts.keycloakRealm) {
|
|
163
|
+
throw new OAuthError("auth-oauth/keycloak-config",
|
|
164
|
+
"keycloak preset requires opts.keycloakUrl and opts.keycloakRealm");
|
|
165
|
+
}
|
|
166
|
+
return opts.keycloakUrl.replace(/\/$/, "") + "/realms/" + opts.keycloakRealm;
|
|
167
|
+
},
|
|
168
|
+
defaultScope: ["openid", "email", "profile"],
|
|
169
|
+
isOidc: true,
|
|
170
|
+
},
|
|
171
|
+
github: {
|
|
172
|
+
// GitHub is OAuth 2 only — no OIDC, no ID tokens, no JWKS.
|
|
173
|
+
authorizationEndpoint: "https://github.com/login/oauth/authorize",
|
|
174
|
+
tokenEndpoint: "https://github.com/login/oauth/access_token",
|
|
175
|
+
userinfoEndpoint: "https://api.github.com/user",
|
|
176
|
+
defaultScope: ["read:user", "user:email"],
|
|
177
|
+
isOidc: false,
|
|
178
|
+
},
|
|
179
|
+
generic: {
|
|
180
|
+
// Operator-defined endpoints (or issuer-driven discovery). The
|
|
181
|
+
// preset itself adds nothing — its presence makes provider:'generic'
|
|
182
|
+
// a valid explicit selector instead of falling through to "unknown
|
|
183
|
+
// provider preset". Operators pass authorizationEndpoint /
|
|
184
|
+
// tokenEndpoint / userinfoEndpoint (or issuer + isOidc:true to
|
|
185
|
+
// discover) on opts.
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
var DEFAULT_ACCEPTED_ALGS = Object.freeze([
|
|
190
|
+
"RS256", "RS384", "RS512",
|
|
191
|
+
"ES256", "ES384", "ES512",
|
|
192
|
+
"PS256", "PS384", "PS512",
|
|
193
|
+
]);
|
|
194
|
+
|
|
195
|
+
var DEFAULT_DISCOVERY_CACHE_MS = C.TIME.hours(1);
|
|
196
|
+
var DEFAULT_CLOCK_SKEW_MS = C.TIME.minutes(1);
|
|
197
|
+
|
|
198
|
+
// Random material lengths. PKCE verifier per RFC 7636 §4.1 needs >= 256
|
|
199
|
+
// bits of entropy; 32 bytes hits that exactly. State + nonce are 16
|
|
200
|
+
// bytes (128-bit unguessability) which is the minimum recommended by
|
|
201
|
+
// OAuth 2.0 Threat Model §4.4.1.8 / §4.4.1.13.
|
|
202
|
+
var PKCE_VERIFIER_BYTES = C.BYTES.bytes(32);
|
|
203
|
+
var STATE_NONCE_BYTES = C.BYTES.bytes(16);
|
|
204
|
+
// JOSE PSS salt lengths (RFC 7518 §3.5) match the hash-output size:
|
|
205
|
+
// PS256/SHA-256 → 32, PS384/SHA-384 → 48, PS512/SHA-512 → 64.
|
|
206
|
+
var PSS_SALT_BYTES_SHA256 = C.BYTES.bytes(32);
|
|
207
|
+
var PSS_SALT_BYTES_SHA384 = C.BYTES.bytes(48);
|
|
208
|
+
var PSS_SALT_BYTES_SHA512 = C.BYTES.bytes(64);
|
|
209
|
+
|
|
210
|
+
// ---- helpers ----
|
|
211
|
+
|
|
212
|
+
function _b64urlEncode(buf) {
|
|
213
|
+
if (typeof buf === "string") buf = Buffer.from(buf, "utf8");
|
|
214
|
+
return buf.toString("base64").replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function _b64urlDecode(s) {
|
|
218
|
+
if (typeof s !== "string") throw new OAuthError("auth-oauth/bad-base64", "expected base64url string");
|
|
219
|
+
var padded = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
220
|
+
while (padded.length % 4) padded += "=";
|
|
221
|
+
return Buffer.from(padded, "base64");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function _generateRandomToken(bytes) {
|
|
225
|
+
return _b64urlEncode(generateBytes(bytes));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function _generatePkce() {
|
|
229
|
+
// RFC 7636: code_verifier is 43–128 chars [A-Za-z0-9-._~].
|
|
230
|
+
// base64url of 32 random bytes = 43 chars, all valid.
|
|
231
|
+
var verifier = _b64urlEncode(generateBytes(PKCE_VERIFIER_BYTES));
|
|
232
|
+
var challenge = _b64urlEncode(nodeCrypto.createHash("sha256").update(verifier).digest());
|
|
233
|
+
return { verifier: verifier, challenge: challenge };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function _validateUrl(url, allowHttp, label) {
|
|
237
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
238
|
+
throw new OAuthError("auth-oauth/bad-url", label + ": URL is required");
|
|
239
|
+
}
|
|
240
|
+
// Operator-supplied OAuth issuer / endpoint URL — route through
|
|
241
|
+
// safeUrl so the scheme allowlist is consistent with the rest of the
|
|
242
|
+
// framework's outbound gates. Map safe-url's error codes to the
|
|
243
|
+
// domain-specific oauth codes operators already key alerts on.
|
|
244
|
+
try {
|
|
245
|
+
safeUrl.parse(url, {
|
|
246
|
+
allowedProtocols: allowHttp ? safeUrl.ALLOW_HTTP_ALL : safeUrl.ALLOW_HTTP_TLS,
|
|
247
|
+
});
|
|
248
|
+
} catch (e) {
|
|
249
|
+
if (e && e.code === "safe-url/protocol-disallowed") {
|
|
250
|
+
throw new OAuthError("auth-oauth/insecure-url",
|
|
251
|
+
label + ": must be https" + (allowHttp ? " or http" : "") +
|
|
252
|
+
" (got '" + url + "')");
|
|
253
|
+
}
|
|
254
|
+
throw new OAuthError("auth-oauth/bad-url",
|
|
255
|
+
label + ": invalid URL '" + url + "'");
|
|
256
|
+
}
|
|
257
|
+
return url;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---- JOSE alg → node:crypto verify parameters ----
|
|
261
|
+
|
|
262
|
+
function _verifyParamsForAlg(alg) {
|
|
263
|
+
// Returns { hash, padding, dsaEncoding } for node:crypto.verify.
|
|
264
|
+
if (alg === "RS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
265
|
+
if (alg === "RS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
266
|
+
if (alg === "RS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
|
|
267
|
+
if (alg === "PS256") return { hash: "sha256", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA256 };
|
|
268
|
+
if (alg === "PS384") return { hash: "sha384", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA384 };
|
|
269
|
+
if (alg === "PS512") return { hash: "sha512", padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT_BYTES_SHA512 };
|
|
270
|
+
if (alg === "ES256") return { hash: "sha256", dsaEncoding: "ieee-p1363" };
|
|
271
|
+
if (alg === "ES384") return { hash: "sha384", dsaEncoding: "ieee-p1363" };
|
|
272
|
+
if (alg === "ES512") return { hash: "sha512", dsaEncoding: "ieee-p1363" };
|
|
273
|
+
throw new OAuthError("auth-oauth/unsupported-alg",
|
|
274
|
+
"alg '" + alg + "' is not supported for ID-token verification");
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ---- JWKS → KeyObject ----
|
|
278
|
+
|
|
279
|
+
function _jwkToKey(jwk) {
|
|
280
|
+
// node's createPublicKey accepts JWK directly since Node 16.
|
|
281
|
+
try { return nodeCrypto.createPublicKey({ key: jwk, format: "jwk" }); }
|
|
282
|
+
catch (e) {
|
|
283
|
+
throw new OAuthError("auth-oauth/bad-jwk",
|
|
284
|
+
"could not import JWK (kid=" + (jwk && jwk.kid) + "): " + ((e && e.message) || String(e)));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ---- core ----
|
|
289
|
+
|
|
290
|
+
function create(opts) {
|
|
291
|
+
opts = opts || {};
|
|
292
|
+
var clientId = opts.clientId;
|
|
293
|
+
var clientSecret = opts.clientSecret || null; // public clients can omit
|
|
294
|
+
var redirectUri = opts.redirectUri;
|
|
295
|
+
var pkce = opts.pkce !== false;
|
|
296
|
+
var clockSkewMs = typeof opts.clockSkewMs === "number" ? opts.clockSkewMs : DEFAULT_CLOCK_SKEW_MS;
|
|
297
|
+
var discoveryCacheMs = typeof opts.discoveryCacheMs === "number"
|
|
298
|
+
? opts.discoveryCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
|
|
299
|
+
var acceptedAlgorithms = Array.isArray(opts.acceptedAlgorithms) && opts.acceptedAlgorithms.length > 0
|
|
300
|
+
? opts.acceptedAlgorithms.slice() : DEFAULT_ACCEPTED_ALGS.slice();
|
|
301
|
+
var allowHttp = !!opts.allowHttp; // localhost dev opt-in (scheme)
|
|
302
|
+
var allowInternal = opts.allowInternal != null ? opts.allowInternal : null; // localhost dev opt-in (SSRF gate)
|
|
303
|
+
var httpClientOpts = opts.httpClient || {};
|
|
304
|
+
var responseMode = opts.responseMode || null;
|
|
305
|
+
|
|
306
|
+
if (!clientId) {
|
|
307
|
+
throw new OAuthError("auth-oauth/no-client-id", "create: opts.clientId is required");
|
|
308
|
+
}
|
|
309
|
+
if (!redirectUri) {
|
|
310
|
+
throw new OAuthError("auth-oauth/no-redirect-uri", "create: opts.redirectUri is required");
|
|
311
|
+
}
|
|
312
|
+
_validateUrl(redirectUri, allowHttp, "redirectUri");
|
|
313
|
+
if (!pkce) {
|
|
314
|
+
log("WARNING: PKCE disabled — modern IdPs require it; this should only be used for legacy providers");
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Resolve preset → effective config.
|
|
318
|
+
var preset = null;
|
|
319
|
+
if (opts.provider) {
|
|
320
|
+
if (!Object.prototype.hasOwnProperty.call(PRESETS, opts.provider)) {
|
|
321
|
+
throw new OAuthError("auth-oauth/unknown-provider",
|
|
322
|
+
"unknown provider preset '" + opts.provider + "' (known: " +
|
|
323
|
+
Object.keys(PRESETS).join(", ") + ")");
|
|
324
|
+
}
|
|
325
|
+
preset = PRESETS[opts.provider];
|
|
326
|
+
}
|
|
327
|
+
var isOidc = (preset && typeof preset.isOidc === "boolean") ? preset.isOidc
|
|
328
|
+
: (opts.isOidc !== undefined ? !!opts.isOidc : true);
|
|
329
|
+
var issuer = opts.issuer
|
|
330
|
+
|| (preset && typeof preset.issuerTemplate === "function" && preset.issuerTemplate(opts))
|
|
331
|
+
|| (preset && preset.issuer)
|
|
332
|
+
|| null;
|
|
333
|
+
var scope = Array.isArray(opts.scope) && opts.scope.length > 0
|
|
334
|
+
? opts.scope.slice()
|
|
335
|
+
: (preset && preset.defaultScope ? preset.defaultScope.slice() : ["openid"]);
|
|
336
|
+
if (!responseMode && preset && preset.responseMode) responseMode = preset.responseMode;
|
|
337
|
+
|
|
338
|
+
// Endpoints — either from preset (explicit), discovery, or operator opts.
|
|
339
|
+
var staticEndpoints = {
|
|
340
|
+
authorizationEndpoint: opts.authorizationEndpoint || (preset && preset.authorizationEndpoint) || null,
|
|
341
|
+
tokenEndpoint: opts.tokenEndpoint || (preset && preset.tokenEndpoint) || null,
|
|
342
|
+
userinfoEndpoint: opts.userinfoEndpoint || (preset && preset.userinfoEndpoint) || null,
|
|
343
|
+
revocationEndpoint: opts.revocationEndpoint || (preset && preset.revocationEndpoint) || null,
|
|
344
|
+
jwksUri: opts.jwksUri || (preset && preset.jwksUri) || null,
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
// Discovery + JWKS caches use b.cache.create + .wrap so concurrent
|
|
348
|
+
// boot races for the same IdP collapse to one fetch (single-flight)
|
|
349
|
+
// and operators can wire b.audit / observability without us
|
|
350
|
+
// re-implementing those hooks here. Per-cache namespaces are unique
|
|
351
|
+
// per oauth-client instance (clientId-scoped) so two clients pointed
|
|
352
|
+
// at different IdPs don't collide in a future cluster-cache backend.
|
|
353
|
+
var jwksCacheMs = typeof opts.jwksCacheMs === "number" ? opts.jwksCacheMs : DEFAULT_DISCOVERY_CACHE_MS;
|
|
354
|
+
var _discoveryCache = cache.create({
|
|
355
|
+
namespace: "oauth.discovery." + clientId,
|
|
356
|
+
ttlMs: discoveryCacheMs,
|
|
357
|
+
});
|
|
358
|
+
var _jwksCache = cache.create({
|
|
359
|
+
namespace: "oauth.jwks." + clientId,
|
|
360
|
+
ttlMs: jwksCacheMs,
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
async function _fetchJson(url, fetchOpts) {
|
|
364
|
+
fetchOpts = fetchOpts || {};
|
|
365
|
+
var hc = httpClient;
|
|
366
|
+
var req = Object.assign({
|
|
367
|
+
url: url,
|
|
368
|
+
method: "GET",
|
|
369
|
+
}, fetchOpts);
|
|
370
|
+
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
371
|
+
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
372
|
+
Object.assign(req, httpClientOpts);
|
|
373
|
+
var res = await hc.request(req);
|
|
374
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
375
|
+
var bodyText = res.body ? res.body.toString("utf8") : "";
|
|
376
|
+
throw new OAuthError("auth-oauth/http-" + res.statusCode,
|
|
377
|
+
url + " returned " + res.statusCode + ": " + bodyText.slice(0, 500));
|
|
378
|
+
}
|
|
379
|
+
if (!res.body) return null;
|
|
380
|
+
try { return safeJson.parse(res.body.toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES }); }
|
|
381
|
+
catch (e) {
|
|
382
|
+
throw new OAuthError("auth-oauth/bad-json",
|
|
383
|
+
url + " response not JSON: " + ((e && e.message) || String(e)));
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function _discover() {
|
|
388
|
+
if (!isOidc || !issuer) return null;
|
|
389
|
+
return _discoveryCache.wrap("config", async function () {
|
|
390
|
+
var url = issuer.replace(/\/$/, "") + "/.well-known/openid-configuration";
|
|
391
|
+
_validateUrl(url, allowHttp, "discovery url");
|
|
392
|
+
var config = await _fetchJson(url);
|
|
393
|
+
if (!config || typeof config !== "object") {
|
|
394
|
+
throw new OAuthError("auth-oauth/bad-discovery", "discovery document missing");
|
|
395
|
+
}
|
|
396
|
+
if (config.issuer && config.issuer !== issuer) {
|
|
397
|
+
throw new OAuthError("auth-oauth/issuer-mismatch",
|
|
398
|
+
"discovery issuer '" + config.issuer + "' does not match configured issuer '" + issuer + "'");
|
|
399
|
+
}
|
|
400
|
+
return config;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async function _resolveEndpoint(name) {
|
|
405
|
+
if (staticEndpoints[name]) return staticEndpoints[name];
|
|
406
|
+
var config = await _discover();
|
|
407
|
+
if (!config) {
|
|
408
|
+
throw new OAuthError("auth-oauth/no-endpoint",
|
|
409
|
+
name + " endpoint not configured and no OIDC discovery available");
|
|
410
|
+
}
|
|
411
|
+
// OIDC discovery uses snake_case key names.
|
|
412
|
+
var snake = ({
|
|
413
|
+
authorizationEndpoint: "authorization_endpoint",
|
|
414
|
+
tokenEndpoint: "token_endpoint",
|
|
415
|
+
userinfoEndpoint: "userinfo_endpoint",
|
|
416
|
+
revocationEndpoint: "revocation_endpoint",
|
|
417
|
+
jwksUri: "jwks_uri",
|
|
418
|
+
})[name];
|
|
419
|
+
var endpoint = config[snake];
|
|
420
|
+
if (!endpoint) {
|
|
421
|
+
throw new OAuthError("auth-oauth/no-endpoint",
|
|
422
|
+
name + " not present in discovery document");
|
|
423
|
+
}
|
|
424
|
+
return endpoint;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async function authorizationUrl(uopts) {
|
|
428
|
+
uopts = uopts || {};
|
|
429
|
+
var endpoint = await _resolveEndpoint("authorizationEndpoint");
|
|
430
|
+
var state = uopts.state || _generateRandomToken(STATE_NONCE_BYTES);
|
|
431
|
+
var nonce = uopts.nonce || (isOidc ? _generateRandomToken(STATE_NONCE_BYTES) : null);
|
|
432
|
+
var pkceVals = pkce ? _generatePkce() : null;
|
|
433
|
+
var params = new URLSearchParams();
|
|
434
|
+
params.set("response_type", "code");
|
|
435
|
+
params.set("client_id", clientId);
|
|
436
|
+
params.set("redirect_uri", redirectUri);
|
|
437
|
+
params.set("scope", scope.join(" "));
|
|
438
|
+
params.set("state", state);
|
|
439
|
+
if (nonce) params.set("nonce", nonce);
|
|
440
|
+
if (pkceVals) {
|
|
441
|
+
params.set("code_challenge", pkceVals.challenge);
|
|
442
|
+
params.set("code_challenge_method", "S256");
|
|
443
|
+
}
|
|
444
|
+
if (responseMode) params.set("response_mode", responseMode);
|
|
445
|
+
if (uopts.prompt) params.set("prompt", uopts.prompt);
|
|
446
|
+
if (uopts.loginHint) params.set("login_hint", uopts.loginHint);
|
|
447
|
+
if (uopts.maxAge != null) params.set("max_age", String(uopts.maxAge));
|
|
448
|
+
// Operator-supplied additional params (audience, resource, etc.).
|
|
449
|
+
if (uopts.extraParams && typeof uopts.extraParams === "object") {
|
|
450
|
+
var ek = Object.keys(uopts.extraParams);
|
|
451
|
+
for (var i = 0; i < ek.length; i++) params.set(ek[i], String(uopts.extraParams[ek[i]]));
|
|
452
|
+
}
|
|
453
|
+
var sep = endpoint.indexOf("?") === -1 ? "?" : "&";
|
|
454
|
+
return {
|
|
455
|
+
url: endpoint + sep + params.toString(),
|
|
456
|
+
state: state,
|
|
457
|
+
nonce: nonce,
|
|
458
|
+
verifier: pkceVals ? pkceVals.verifier : null,
|
|
459
|
+
challenge: pkceVals ? pkceVals.challenge : null,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function exchangeCode(eopts) {
|
|
464
|
+
eopts = eopts || {};
|
|
465
|
+
if (!eopts.code) {
|
|
466
|
+
throw new OAuthError("auth-oauth/no-code", "exchangeCode: opts.code is required");
|
|
467
|
+
}
|
|
468
|
+
if (pkce && !eopts.verifier) {
|
|
469
|
+
throw new OAuthError("auth-oauth/no-verifier",
|
|
470
|
+
"exchangeCode: opts.verifier is required when PKCE is on (default)");
|
|
471
|
+
}
|
|
472
|
+
var endpoint = await _resolveEndpoint("tokenEndpoint");
|
|
473
|
+
var body = new URLSearchParams();
|
|
474
|
+
body.set("grant_type", "authorization_code");
|
|
475
|
+
body.set("code", eopts.code);
|
|
476
|
+
body.set("redirect_uri", redirectUri);
|
|
477
|
+
body.set("client_id", clientId);
|
|
478
|
+
if (clientSecret) body.set("client_secret", clientSecret);
|
|
479
|
+
if (eopts.verifier) body.set("code_verifier", eopts.verifier);
|
|
480
|
+
|
|
481
|
+
var tokens = await _postForm(endpoint, body);
|
|
482
|
+
return await _normalizeTokens(tokens, { nonce: eopts.nonce });
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async function refreshAccessToken(refreshToken) {
|
|
486
|
+
if (!refreshToken) {
|
|
487
|
+
throw new OAuthError("auth-oauth/no-refresh-token",
|
|
488
|
+
"refreshAccessToken: refresh token is required");
|
|
489
|
+
}
|
|
490
|
+
var endpoint = await _resolveEndpoint("tokenEndpoint");
|
|
491
|
+
var body = new URLSearchParams();
|
|
492
|
+
body.set("grant_type", "refresh_token");
|
|
493
|
+
body.set("refresh_token", refreshToken);
|
|
494
|
+
body.set("client_id", clientId);
|
|
495
|
+
if (clientSecret) body.set("client_secret", clientSecret);
|
|
496
|
+
var tokens = await _postForm(endpoint, body);
|
|
497
|
+
// Refreshed tokens may not include a new id_token; verification
|
|
498
|
+
// is conditional.
|
|
499
|
+
return await _normalizeTokens(tokens, { skipNonceCheck: true });
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function fetchUserInfo(accessToken) {
|
|
503
|
+
if (!accessToken) {
|
|
504
|
+
throw new OAuthError("auth-oauth/no-access-token",
|
|
505
|
+
"fetchUserInfo: access token is required");
|
|
506
|
+
}
|
|
507
|
+
var endpoint = await _resolveEndpoint("userinfoEndpoint");
|
|
508
|
+
return await _fetchJson(endpoint, {
|
|
509
|
+
headers: {
|
|
510
|
+
"Authorization": "Bearer " + accessToken,
|
|
511
|
+
"Accept": "application/json",
|
|
512
|
+
"User-Agent": "blamejs",
|
|
513
|
+
},
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function revokeToken(token, ropts) {
|
|
518
|
+
if (!token) {
|
|
519
|
+
throw new OAuthError("auth-oauth/no-token", "revokeToken: token is required");
|
|
520
|
+
}
|
|
521
|
+
ropts = ropts || {};
|
|
522
|
+
var endpoint = await _resolveEndpoint("revocationEndpoint");
|
|
523
|
+
var body = new URLSearchParams();
|
|
524
|
+
body.set("token", token);
|
|
525
|
+
if (ropts.type) body.set("token_type_hint", ropts.type);
|
|
526
|
+
body.set("client_id", clientId);
|
|
527
|
+
if (clientSecret) body.set("client_secret", clientSecret);
|
|
528
|
+
var hc = httpClient;
|
|
529
|
+
var req = {
|
|
530
|
+
url: endpoint,
|
|
531
|
+
method: "POST",
|
|
532
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
533
|
+
body: Buffer.from(body.toString(), "utf8"),
|
|
534
|
+
};
|
|
535
|
+
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
536
|
+
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
537
|
+
Object.assign(req, httpClientOpts);
|
|
538
|
+
var res = await hc.request(req);
|
|
539
|
+
// RFC 7009: 200 even if the token was already revoked / unknown.
|
|
540
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
541
|
+
throw new OAuthError("auth-oauth/revoke-failed",
|
|
542
|
+
"revocation returned " + res.statusCode);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async function _postForm(endpoint, body) {
|
|
547
|
+
var hc = httpClient;
|
|
548
|
+
var req = {
|
|
549
|
+
url: endpoint,
|
|
550
|
+
method: "POST",
|
|
551
|
+
headers: {
|
|
552
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
553
|
+
"Accept": "application/json",
|
|
554
|
+
},
|
|
555
|
+
body: Buffer.from(body.toString(), "utf8"),
|
|
556
|
+
};
|
|
557
|
+
if (allowHttp) req.allowedProtocols = safeUrl.ALLOW_HTTP_ALL;
|
|
558
|
+
if (allowInternal !== null) req.allowInternal = allowInternal;
|
|
559
|
+
Object.assign(req, httpClientOpts);
|
|
560
|
+
var res = await hc.request(req);
|
|
561
|
+
var text = res.body ? res.body.toString("utf8") : "";
|
|
562
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
563
|
+
throw new OAuthError("auth-oauth/token-error-" + res.statusCode,
|
|
564
|
+
endpoint + " returned " + res.statusCode + ": " + text.slice(0, 500));
|
|
565
|
+
}
|
|
566
|
+
var parsed;
|
|
567
|
+
try { parsed = safeJson.parse(text, { maxBytes: OAUTH_MAX_RESPONSE_BYTES }); }
|
|
568
|
+
catch (e) {
|
|
569
|
+
throw new OAuthError("auth-oauth/bad-token-json",
|
|
570
|
+
"token endpoint response not JSON: " + ((e && e.message) || String(e)));
|
|
571
|
+
}
|
|
572
|
+
return parsed;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
async function _normalizeTokens(raw, vopts) {
|
|
576
|
+
vopts = vopts || {};
|
|
577
|
+
var tokens = {
|
|
578
|
+
accessToken: raw.access_token,
|
|
579
|
+
tokenType: raw.token_type || "Bearer",
|
|
580
|
+
expiresIn: raw.expires_in || null,
|
|
581
|
+
refreshToken: raw.refresh_token || null,
|
|
582
|
+
idToken: raw.id_token || null,
|
|
583
|
+
scope: raw.scope ? raw.scope.split(/\s+/) : scope.slice(),
|
|
584
|
+
raw: raw,
|
|
585
|
+
};
|
|
586
|
+
if (tokens.idToken && isOidc) {
|
|
587
|
+
var v = await verifyIdToken(tokens.idToken, {
|
|
588
|
+
nonce: vopts.nonce,
|
|
589
|
+
skipNonceCheck: vopts.skipNonceCheck,
|
|
590
|
+
});
|
|
591
|
+
tokens.claims = v.claims;
|
|
592
|
+
tokens.profile = {
|
|
593
|
+
sub: v.claims.sub,
|
|
594
|
+
email: v.claims.email,
|
|
595
|
+
name: v.claims.name,
|
|
596
|
+
picture: v.claims.picture,
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
return tokens;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async function _getJwks() {
|
|
603
|
+
return _jwksCache.wrap("keys", async function () {
|
|
604
|
+
var jwksUri = await _resolveEndpoint("jwksUri");
|
|
605
|
+
var jwks = await _fetchJson(jwksUri);
|
|
606
|
+
if (!jwks || !Array.isArray(jwks.keys)) {
|
|
607
|
+
throw new OAuthError("auth-oauth/bad-jwks", "JWKS response missing 'keys' array");
|
|
608
|
+
}
|
|
609
|
+
return jwks.keys;
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async function verifyIdToken(idToken, vopts) {
|
|
614
|
+
vopts = vopts || {};
|
|
615
|
+
if (typeof idToken !== "string") {
|
|
616
|
+
throw new OAuthError("auth-oauth/no-id-token", "verifyIdToken: idToken must be a string");
|
|
617
|
+
}
|
|
618
|
+
var parts = idToken.split(".");
|
|
619
|
+
if (parts.length !== 3) {
|
|
620
|
+
throw new OAuthError("auth-oauth/malformed-jwt", "ID token does not have 3 parts");
|
|
621
|
+
}
|
|
622
|
+
var header, payload;
|
|
623
|
+
try {
|
|
624
|
+
header = safeJson.parse(_b64urlDecode(parts[0]).toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES });
|
|
625
|
+
payload = safeJson.parse(_b64urlDecode(parts[1]).toString("utf8"), { maxBytes: OAUTH_MAX_RESPONSE_BYTES });
|
|
626
|
+
} catch (e) {
|
|
627
|
+
throw new OAuthError("auth-oauth/malformed-jwt",
|
|
628
|
+
"ID token header/payload base64 decode failed: " + ((e && e.message) || String(e)));
|
|
629
|
+
}
|
|
630
|
+
if (!header || typeof header.alg !== "string") {
|
|
631
|
+
throw new OAuthError("auth-oauth/malformed-jwt", "ID token header missing 'alg'");
|
|
632
|
+
}
|
|
633
|
+
if (acceptedAlgorithms.indexOf(header.alg) === -1) {
|
|
634
|
+
throw new OAuthError("auth-oauth/alg-not-accepted",
|
|
635
|
+
"ID token signed with '" + header.alg + "' which is not in the accepted-algorithm list");
|
|
636
|
+
}
|
|
637
|
+
var keys = await _getJwks();
|
|
638
|
+
var match = null;
|
|
639
|
+
if (header.kid) {
|
|
640
|
+
for (var i = 0; i < keys.length; i++) {
|
|
641
|
+
if (keys[i].kid === header.kid) { match = keys[i]; break; }
|
|
642
|
+
}
|
|
643
|
+
} else if (keys.length === 1) {
|
|
644
|
+
match = keys[0];
|
|
645
|
+
}
|
|
646
|
+
if (!match) {
|
|
647
|
+
throw new OAuthError("auth-oauth/no-matching-key",
|
|
648
|
+
"no JWKS key matches header.kid='" + header.kid + "'");
|
|
649
|
+
}
|
|
650
|
+
var keyObject = _jwkToKey(match);
|
|
651
|
+
var params = _verifyParamsForAlg(header.alg);
|
|
652
|
+
var signingInput = parts[0] + "." + parts[1];
|
|
653
|
+
var sig = _b64urlDecode(parts[2]);
|
|
654
|
+
var verifyOpts = { key: keyObject };
|
|
655
|
+
if (params.padding !== undefined) verifyOpts.padding = params.padding;
|
|
656
|
+
if (params.saltLength !== undefined) verifyOpts.saltLength = params.saltLength;
|
|
657
|
+
if (params.dsaEncoding !== undefined) verifyOpts.dsaEncoding = params.dsaEncoding;
|
|
658
|
+
var verified = nodeCrypto.verify(params.hash, Buffer.from(signingInput, "ascii"), verifyOpts, sig);
|
|
659
|
+
if (!verified) {
|
|
660
|
+
throw new OAuthError("auth-oauth/bad-signature", "ID token signature verification failed");
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Claim validation.
|
|
664
|
+
var now = Math.floor(Date.now() / C.TIME.seconds(1));
|
|
665
|
+
var skewSec = Math.floor(clockSkewMs / C.TIME.seconds(1));
|
|
666
|
+
if (typeof payload.exp !== "number" || payload.exp + skewSec < now) {
|
|
667
|
+
throw new OAuthError("auth-oauth/expired", "ID token expired (exp=" + payload.exp + ", now=" + now + ")");
|
|
668
|
+
}
|
|
669
|
+
if (typeof payload.iat === "number" && payload.iat - skewSec > now) {
|
|
670
|
+
throw new OAuthError("auth-oauth/iat-future", "ID token iat is in the future");
|
|
671
|
+
}
|
|
672
|
+
if (typeof payload.nbf === "number" && payload.nbf - skewSec > now) {
|
|
673
|
+
throw new OAuthError("auth-oauth/nbf-future", "ID token nbf is in the future");
|
|
674
|
+
}
|
|
675
|
+
if (issuer && payload.iss !== issuer) {
|
|
676
|
+
throw new OAuthError("auth-oauth/iss-mismatch",
|
|
677
|
+
"ID token iss '" + payload.iss + "' does not match expected '" + issuer + "'");
|
|
678
|
+
}
|
|
679
|
+
var aud = Array.isArray(payload.aud) ? payload.aud : (payload.aud ? [payload.aud] : []);
|
|
680
|
+
if (aud.indexOf(clientId) === -1) {
|
|
681
|
+
throw new OAuthError("auth-oauth/aud-mismatch",
|
|
682
|
+
"ID token aud does not contain clientId '" + clientId + "'");
|
|
683
|
+
}
|
|
684
|
+
if (vopts.nonce && !vopts.skipNonceCheck) {
|
|
685
|
+
if (payload.nonce !== vopts.nonce) {
|
|
686
|
+
throw new OAuthError("auth-oauth/nonce-mismatch",
|
|
687
|
+
"ID token nonce mismatch (replay protection)");
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return { header: header, claims: payload };
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
return {
|
|
694
|
+
authorizationUrl: authorizationUrl,
|
|
695
|
+
exchangeCode: exchangeCode,
|
|
696
|
+
refreshAccessToken: refreshAccessToken,
|
|
697
|
+
fetchUserInfo: fetchUserInfo,
|
|
698
|
+
revokeToken: revokeToken,
|
|
699
|
+
verifyIdToken: verifyIdToken,
|
|
700
|
+
discover: _discover,
|
|
701
|
+
// Diagnostic / power-user surface
|
|
702
|
+
issuer: issuer,
|
|
703
|
+
clientId: clientId,
|
|
704
|
+
redirectUri: redirectUri,
|
|
705
|
+
scope: scope,
|
|
706
|
+
isOidc: isOidc,
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
module.exports = {
|
|
711
|
+
create: create,
|
|
712
|
+
PRESETS: PRESETS,
|
|
713
|
+
OAuthError: OAuthError,
|
|
714
|
+
DEFAULT_ACCEPTED_ALGS: DEFAULT_ACCEPTED_ALGS,
|
|
715
|
+
// Internal helpers exposed for tests
|
|
716
|
+
_generatePkce: _generatePkce,
|
|
717
|
+
_generateRandomToken: _generateRandomToken,
|
|
718
|
+
_b64urlEncode: _b64urlEncode,
|
|
719
|
+
_b64urlDecode: _b64urlDecode,
|
|
720
|
+
_verifyParamsForAlg: _verifyParamsForAlg,
|
|
721
|
+
};
|