axiam-sdk 1.0.0-alpha2 → 1.0.0-alpha21
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/README.md +219 -8
- package/dist/amqp/index.d.cts +1 -1
- package/dist/amqp/index.d.ts +1 -1
- package/dist/amqp/index.js +4 -0
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +4 -0
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-xwmCivHH.d.ts → authzCore-DtSN59if.d.ts} +19 -2
- package/dist/{authzCore-CV-Td-V1.d.cts → authzCore-DuRI1aJf.d.cts} +19 -2
- package/dist/client-B_FqmZ0i.d.cts +72 -0
- package/dist/client-Dn1fs5MH.d.ts +72 -0
- package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
- package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
- package/dist/grpc/index.d.cts +113 -6
- package/dist/grpc/index.d.ts +113 -6
- package/dist/grpc/index.js +435 -18
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +434 -19
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +209 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +204 -14
- package/dist/index.mjs.map +1 -1
- package/dist/jwks-BgojMGC5.d.cts +152 -0
- package/dist/jwks-BgojMGC5.d.ts +152 -0
- package/dist/middleware/index.d.cts +208 -8
- package/dist/middleware/index.d.ts +208 -8
- package/dist/middleware/index.js +1107 -1
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +1100 -3
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +2 -2
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +3 -0
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +3 -0
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +50 -94
- package/dist/node/index.d.ts +50 -94
- package/dist/node/index.js +1039 -15
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +1023 -16
- package/dist/node/index.mjs.map +1 -1
- package/dist/oidcState-BGxqWUun.d.cts +598 -0
- package/dist/oidcState-CkFuCjpM.d.ts +598 -0
- package/dist/rest/index.d.cts +107 -5
- package/dist/rest/index.d.ts +107 -5
- package/dist/rest/index.js +209 -13
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +204 -14
- package/dist/rest/index.mjs.map +1 -1
- package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
- package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
- package/dist/session-BWUWhhyB.d.cts +154 -0
- package/dist/session-BWUWhhyB.d.ts +154 -0
- package/package.json +2 -2
- package/dist/client-BPg9kfKV.d.ts +0 -150
- package/dist/client-CAeQw1a-.d.cts +0 -150
- package/dist/jwks-CX-nhD6A.d.cts +0 -29
- package/dist/jwks-CX-nhD6A.d.ts +0 -29
- package/dist/sensitive-CWBH_tHr.d.cts +0 -12
- package/dist/sensitive-CWBH_tHr.d.ts +0 -12
package/dist/node/index.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
var axios = require('axios');
|
|
4
4
|
var toughCookie = require('tough-cookie');
|
|
5
5
|
var axiosCookiejarSupport = require('axios-cookiejar-support');
|
|
6
|
+
var crypto = require('crypto');
|
|
6
7
|
|
|
7
8
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
9
|
|
|
@@ -23,14 +24,40 @@ var AxiamError = class extends Error {
|
|
|
23
24
|
}
|
|
24
25
|
};
|
|
25
26
|
var AuthError = class _AuthError extends AxiamError {
|
|
26
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Optional stable, machine-readable reason code for the failure.
|
|
29
|
+
*
|
|
30
|
+
* Populated by the CONTRACT.md §12.4 ID-token validation checklist with
|
|
31
|
+
* one of the seven codes §12.3 rule 3 enumerates (see
|
|
32
|
+
* {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.
|
|
33
|
+
* It is a *code*, never free text, so callers can branch on it without
|
|
34
|
+
* parsing `message`.
|
|
35
|
+
*/
|
|
36
|
+
reason;
|
|
37
|
+
constructor(message, reason) {
|
|
27
38
|
super(message);
|
|
28
39
|
this.name = "AuthError";
|
|
40
|
+
this.reason = reason;
|
|
29
41
|
Object.setPrototypeOf(this, _AuthError.prototype);
|
|
30
42
|
}
|
|
31
43
|
};
|
|
44
|
+
var OAuthProtocolError = class _OAuthProtocolError extends AuthError {
|
|
45
|
+
/** The RFC 6749 `error` code (e.g. `"invalid_grant"`, `"invalid_client"`, `"unsupported_grant_type"`). */
|
|
46
|
+
error;
|
|
47
|
+
/** The server's human-readable `error_description`. Never contains token material. */
|
|
48
|
+
errorDescription;
|
|
49
|
+
constructor(error, errorDescription) {
|
|
50
|
+
super(`${error}: ${errorDescription}`);
|
|
51
|
+
this.name = "OAuthProtocolError";
|
|
52
|
+
this.error = error;
|
|
53
|
+
this.errorDescription = errorDescription;
|
|
54
|
+
Object.setPrototypeOf(this, _OAuthProtocolError.prototype);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
32
57
|
var AuthzError = class _AuthzError extends AxiamError {
|
|
58
|
+
/** The denied action, when the server reported it. */
|
|
33
59
|
action;
|
|
60
|
+
/** The resource the denied action targeted, when the server reported it. */
|
|
34
61
|
resourceId;
|
|
35
62
|
constructor(message, action, resourceId) {
|
|
36
63
|
super(message);
|
|
@@ -41,6 +68,7 @@ var AuthzError = class _AuthzError extends AxiamError {
|
|
|
41
68
|
}
|
|
42
69
|
};
|
|
43
70
|
var NetworkError = class _NetworkError extends AxiamError {
|
|
71
|
+
/** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */
|
|
44
72
|
cause;
|
|
45
73
|
constructor(message, cause) {
|
|
46
74
|
super(message);
|
|
@@ -60,6 +88,24 @@ function extractAuthzFieldsFromBody(body) {
|
|
|
60
88
|
const resourceId = typeof record.resource_id === "string" ? record.resource_id : void 0;
|
|
61
89
|
return { action, resourceId };
|
|
62
90
|
}
|
|
91
|
+
var OAUTH2_PATH_PREFIX = "/oauth2/";
|
|
92
|
+
function isOAuth2EndpointUrl(url) {
|
|
93
|
+
if (!url) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);
|
|
98
|
+
} catch {
|
|
99
|
+
return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function isOAuth2ErrorBody(body) {
|
|
103
|
+
if (body === null || typeof body !== "object") {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
const record = body;
|
|
107
|
+
return typeof record.error === "string" && typeof record.error_description === "string";
|
|
108
|
+
}
|
|
63
109
|
var SAFE_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
|
|
64
110
|
"content-type",
|
|
65
111
|
"content-length",
|
|
@@ -97,6 +143,9 @@ function sanitizeAxiosError(err) {
|
|
|
97
143
|
};
|
|
98
144
|
}
|
|
99
145
|
function mapHttpStatusToError(status, message, ctx) {
|
|
146
|
+
if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {
|
|
147
|
+
return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);
|
|
148
|
+
}
|
|
100
149
|
if (status === 401) {
|
|
101
150
|
return new AuthError(message);
|
|
102
151
|
}
|
|
@@ -112,6 +161,7 @@ var REDACTED = "[SENSITIVE]";
|
|
|
112
161
|
var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
113
162
|
var Sensitive = class {
|
|
114
163
|
#value;
|
|
164
|
+
/** Wrap `value` so it can never be logged or serialized by accident. */
|
|
115
165
|
constructor(value) {
|
|
116
166
|
this.#value = value;
|
|
117
167
|
}
|
|
@@ -119,12 +169,15 @@ var Sensitive = class {
|
|
|
119
169
|
expose() {
|
|
120
170
|
return this.#value;
|
|
121
171
|
}
|
|
172
|
+
/** Returns the `"[SENSITIVE]"` placeholder — never the wrapped value. */
|
|
122
173
|
toString() {
|
|
123
174
|
return REDACTED;
|
|
124
175
|
}
|
|
176
|
+
/** Makes `JSON.stringify()` emit the `"[SENSITIVE]"` placeholder. */
|
|
125
177
|
toJSON() {
|
|
126
178
|
return REDACTED;
|
|
127
179
|
}
|
|
180
|
+
/** Makes `console.log`/`util.inspect` print the `"[SENSITIVE]"` placeholder. */
|
|
128
181
|
[NODE_INSPECT_CUSTOM]() {
|
|
129
182
|
return REDACTED;
|
|
130
183
|
}
|
|
@@ -168,9 +221,34 @@ createRefreshGuard();
|
|
|
168
221
|
|
|
169
222
|
// src/core/config.ts
|
|
170
223
|
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
224
|
+
var CERT_PEM_MARKER = "-----BEGIN CERTIFICATE-----";
|
|
225
|
+
var PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;
|
|
226
|
+
function resolveClientIdentity(options) {
|
|
227
|
+
const hasCert = options.clientCert !== void 0;
|
|
228
|
+
const hasKey = options.clientKey !== void 0;
|
|
229
|
+
if (hasCert !== hasKey) {
|
|
230
|
+
throw new Error(
|
|
231
|
+
"clientCert and clientKey must be provided together for mutual TLS (one was given without the other) (CONTRACT.md \xA76.1)."
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
if (!hasCert || !hasKey) {
|
|
235
|
+
return void 0;
|
|
236
|
+
}
|
|
237
|
+
if (!options.clientCert.includes(CERT_PEM_MARKER)) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
'clientCert must be a PEM-encoded certificate chain (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76.1).'
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (!PRIVATE_KEY_PEM_RE.test(options.clientKey)) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
'clientKey must be a PEM-encoded private key (expected to contain "-----BEGIN PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----") (CONTRACT.md \xA76.1).'
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
return { cert: options.clientCert, key: new Sensitive(options.clientKey) };
|
|
248
|
+
}
|
|
171
249
|
|
|
172
250
|
// src/rest/session.ts
|
|
173
|
-
var PEM_MARKER =
|
|
251
|
+
var PEM_MARKER = CERT_PEM_MARKER;
|
|
174
252
|
var SharedSession = class {
|
|
175
253
|
/** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */
|
|
176
254
|
axios;
|
|
@@ -178,6 +256,28 @@ var SharedSession = class {
|
|
|
178
256
|
baseUrl;
|
|
179
257
|
/** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
|
|
180
258
|
tenantHeaderValue;
|
|
259
|
+
/** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */
|
|
260
|
+
tenantId;
|
|
261
|
+
/** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */
|
|
262
|
+
tenantSlug;
|
|
263
|
+
/** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */
|
|
264
|
+
orgId;
|
|
265
|
+
/** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */
|
|
266
|
+
orgSlug;
|
|
267
|
+
/**
|
|
268
|
+
* Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`
|
|
269
|
+
* requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config
|
|
270
|
+
* when the UUID was supplied, then updated from the access-token `tenant_id`
|
|
271
|
+
* claim after each successful login/refresh (Node persona only — the browser
|
|
272
|
+
* cannot read the httpOnly access-token cookie).
|
|
273
|
+
*/
|
|
274
|
+
resolvedTenantId;
|
|
275
|
+
/**
|
|
276
|
+
* Resolved organization UUID used to build the `refresh` body. Seeded from
|
|
277
|
+
* `orgId` config, then updated from the access-token `org_id` claim after a
|
|
278
|
+
* successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.
|
|
279
|
+
*/
|
|
280
|
+
resolvedOrgId;
|
|
181
281
|
/** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
|
|
182
282
|
csrfToken;
|
|
183
283
|
/** Set true once a successful login/verifyMfa has completed. */
|
|
@@ -197,8 +297,55 @@ var SharedSession = class {
|
|
|
197
297
|
this.axios = axiosInstance;
|
|
198
298
|
this.baseUrl = options.baseUrl;
|
|
199
299
|
this.tenantHeaderValue = tenantHeaderValue;
|
|
300
|
+
this.tenantId = options.tenantId;
|
|
301
|
+
this.tenantSlug = options.tenantSlug;
|
|
302
|
+
this.orgId = options.orgId;
|
|
303
|
+
this.orgSlug = options.orgSlug;
|
|
304
|
+
this.resolvedTenantId = options.tenantId;
|
|
305
|
+
this.resolvedOrgId = options.orgId;
|
|
200
306
|
this.refreshGuard = createRefreshGuard();
|
|
201
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* Build the `POST /api/v1/auth/refresh` request body (§1). The server's
|
|
310
|
+
* `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this
|
|
311
|
+
* emits the resolved UUIDs — from the access-token claims after login, or
|
|
312
|
+
* from UUID-form construction options as a fallback. Fields that could not
|
|
313
|
+
* be resolved are omitted (the server then answers with a clear 400), rather
|
|
314
|
+
* than sending a slug where a UUID is required.
|
|
315
|
+
*/
|
|
316
|
+
buildRefreshBody() {
|
|
317
|
+
const body = {};
|
|
318
|
+
if (this.resolvedTenantId) {
|
|
319
|
+
body.tenant_id = this.resolvedTenantId;
|
|
320
|
+
}
|
|
321
|
+
if (this.resolvedOrgId) {
|
|
322
|
+
body.org_id = this.resolvedOrgId;
|
|
323
|
+
}
|
|
324
|
+
return body;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the
|
|
328
|
+
* configured tenant and organization identifiers (UUID or slug form) in
|
|
329
|
+
* addition to the credentials — the server resolves the workspace from the
|
|
330
|
+
* body, not the `X-Tenant-ID` header, and rejects a login that omits org
|
|
331
|
+
* context. Undefined identifiers are omitted.
|
|
332
|
+
*/
|
|
333
|
+
buildLoginBody(email, password) {
|
|
334
|
+
const body = { username_or_email: email, password };
|
|
335
|
+
if (this.tenantId) {
|
|
336
|
+
body.tenant_id = this.tenantId;
|
|
337
|
+
}
|
|
338
|
+
if (this.tenantSlug) {
|
|
339
|
+
body.tenant_slug = this.tenantSlug;
|
|
340
|
+
}
|
|
341
|
+
if (this.orgId) {
|
|
342
|
+
body.org_id = this.orgId;
|
|
343
|
+
}
|
|
344
|
+
if (this.orgSlug) {
|
|
345
|
+
body.org_slug = this.orgSlug;
|
|
346
|
+
}
|
|
347
|
+
return body;
|
|
348
|
+
}
|
|
202
349
|
/**
|
|
203
350
|
* Host-isolation guard (3A, defense in depth): returns `true` when `url`
|
|
204
351
|
* targets a host other than this session's base origin — an absolute
|
|
@@ -232,11 +379,12 @@ function resolveTenantHeaderValue(options) {
|
|
|
232
379
|
"AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
|
|
233
380
|
);
|
|
234
381
|
}
|
|
235
|
-
function maybeBuildHttpsAgent(customCa) {
|
|
382
|
+
function maybeBuildHttpsAgent(customCa, identity) {
|
|
236
383
|
if (!customCa) {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
384
|
+
if (!identity) {
|
|
385
|
+
return void 0;
|
|
386
|
+
}
|
|
387
|
+
} else if (!customCa.includes(PEM_MARKER)) {
|
|
240
388
|
throw new Error(
|
|
241
389
|
'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
|
|
242
390
|
);
|
|
@@ -245,7 +393,11 @@ function maybeBuildHttpsAgent(customCa) {
|
|
|
245
393
|
return void 0;
|
|
246
394
|
}
|
|
247
395
|
const https = __require("https");
|
|
248
|
-
return new https.Agent({
|
|
396
|
+
return new https.Agent({
|
|
397
|
+
...customCa ? { ca: customCa } : {},
|
|
398
|
+
// rejectUnauthorized is intentionally left at its secure default (true).
|
|
399
|
+
...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
|
|
400
|
+
});
|
|
249
401
|
}
|
|
250
402
|
function createSession(options) {
|
|
251
403
|
const tenantHeaderValue = resolveTenantHeaderValue(options);
|
|
@@ -254,7 +406,8 @@ function createSession(options) {
|
|
|
254
406
|
'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
|
|
255
407
|
);
|
|
256
408
|
}
|
|
257
|
-
const
|
|
409
|
+
const clientIdentity = resolveClientIdentity(options);
|
|
410
|
+
const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);
|
|
258
411
|
const axiosInstance = axios__default.default.create({
|
|
259
412
|
baseURL: options.baseUrl,
|
|
260
413
|
withCredentials: true,
|
|
@@ -274,7 +427,14 @@ function createSession(options) {
|
|
|
274
427
|
}
|
|
275
428
|
|
|
276
429
|
// src/rest/interceptors.ts
|
|
277
|
-
var SKIP_REFRESH = [
|
|
430
|
+
var SKIP_REFRESH = [
|
|
431
|
+
"/api/v1/auth/refresh",
|
|
432
|
+
"/api/v1/auth/login",
|
|
433
|
+
"/api/v1/auth/logout",
|
|
434
|
+
"/oauth2/token",
|
|
435
|
+
"/oauth2/introspect",
|
|
436
|
+
"/oauth2/revoke"
|
|
437
|
+
];
|
|
278
438
|
function installCsrfInterceptor(axiosInstance, session) {
|
|
279
439
|
axiosInstance.interceptors.request.use((config) => {
|
|
280
440
|
if (session.isForeignHost(config.url)) {
|
|
@@ -305,7 +465,8 @@ function installRefreshInterceptor(axiosInstance, session) {
|
|
|
305
465
|
originalRequest._retry = true;
|
|
306
466
|
try {
|
|
307
467
|
await session.refreshGuard(async () => {
|
|
308
|
-
await session.axios.post("/api/v1/auth/refresh",
|
|
468
|
+
await session.axios.post("/api/v1/auth/refresh", session.buildRefreshBody());
|
|
469
|
+
await session.onAuthenticated?.();
|
|
309
470
|
});
|
|
310
471
|
return axiosInstance(originalRequest);
|
|
311
472
|
} catch (refreshError) {
|
|
@@ -319,7 +480,13 @@ function installRefreshInterceptor(axiosInstance, session) {
|
|
|
319
480
|
}
|
|
320
481
|
}
|
|
321
482
|
if (status === 401 && isSkipRefresh) {
|
|
322
|
-
return Promise.reject(
|
|
483
|
+
return Promise.reject(
|
|
484
|
+
mapHttpStatusToError(401, "authentication failed", {
|
|
485
|
+
url,
|
|
486
|
+
body: error.response.data,
|
|
487
|
+
cause: error
|
|
488
|
+
})
|
|
489
|
+
);
|
|
323
490
|
}
|
|
324
491
|
return Promise.reject(error);
|
|
325
492
|
}
|
|
@@ -357,7 +524,7 @@ function extractErrorMessage(err) {
|
|
|
357
524
|
return "request failed";
|
|
358
525
|
}
|
|
359
526
|
async function login(client, email, password) {
|
|
360
|
-
const body =
|
|
527
|
+
const body = client.session.buildLoginBody(email, password);
|
|
361
528
|
try {
|
|
362
529
|
const response = await client.session.axios.post(
|
|
363
530
|
LOGIN_PATH,
|
|
@@ -398,7 +565,8 @@ async function verifyMfa(client, mfaToken, code) {
|
|
|
398
565
|
}
|
|
399
566
|
async function refresh(client) {
|
|
400
567
|
try {
|
|
401
|
-
await client.session.axios.post(REFRESH_PATH,
|
|
568
|
+
await client.session.axios.post(REFRESH_PATH, client.session.buildRefreshBody());
|
|
569
|
+
await client.session.onAuthenticated?.();
|
|
402
570
|
} catch (err) {
|
|
403
571
|
const status = extractAxiosStatus(err);
|
|
404
572
|
if (status !== void 0) {
|
|
@@ -616,22 +784,124 @@ var TokenManager = class {
|
|
|
616
784
|
setTenantId(tenantId) {
|
|
617
785
|
this.#tenantId = tenantId;
|
|
618
786
|
}
|
|
787
|
+
/**
|
|
788
|
+
* Best-effort decode of the `tenant_id`/`org_id` claims out of the cached
|
|
789
|
+
* access token, WITHOUT signature verification. Used only to populate the
|
|
790
|
+
* `refresh` request body (`RefreshRequest` requires both UUIDs) — never as a
|
|
791
|
+
* trust decision: the actual credential is the httpOnly `axiam_access` cookie
|
|
792
|
+
* the server verifies, and the server re-derives the authoritative `org_id`
|
|
793
|
+
* from the tenant on refresh (see crates/axiam-api-rest handlers/auth.rs),
|
|
794
|
+
* so echoing these values back carries no security weight. A malformed or
|
|
795
|
+
* absent token yields an empty result (the caller then keeps whatever UUIDs
|
|
796
|
+
* were resolved from construction options).
|
|
797
|
+
*/
|
|
798
|
+
claimsFromCachedToken() {
|
|
799
|
+
const token = this.#cachedAccess?.expose();
|
|
800
|
+
if (!token) {
|
|
801
|
+
return {};
|
|
802
|
+
}
|
|
803
|
+
const claims = decodeJwtPayload(token);
|
|
804
|
+
return {
|
|
805
|
+
tenantId: typeof claims.tenant_id === "string" ? claims.tenant_id : void 0,
|
|
806
|
+
orgId: typeof claims.org_id === "string" ? claims.org_id : void 0
|
|
807
|
+
};
|
|
808
|
+
}
|
|
619
809
|
/** Clear all cached token state (used by logout()). */
|
|
620
810
|
clear() {
|
|
621
811
|
this.#cachedAccess = null;
|
|
622
812
|
}
|
|
623
813
|
};
|
|
814
|
+
function decodeJwtPayload(token) {
|
|
815
|
+
try {
|
|
816
|
+
const segments = token.split(".");
|
|
817
|
+
if (segments.length !== 3) {
|
|
818
|
+
return {};
|
|
819
|
+
}
|
|
820
|
+
const json = Buffer.from(segments[1], "base64url").toString("utf8");
|
|
821
|
+
const parsed = JSON.parse(json);
|
|
822
|
+
return typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
823
|
+
} catch {
|
|
824
|
+
return {};
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
var MAX_CLOCK_SKEW_SEC = 60;
|
|
828
|
+
function idTokenAuthError(reason, message) {
|
|
829
|
+
return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);
|
|
830
|
+
}
|
|
831
|
+
function resolveClockSkewSec(clockSkewSec) {
|
|
832
|
+
if (clockSkewSec === void 0) {
|
|
833
|
+
return MAX_CLOCK_SKEW_SEC;
|
|
834
|
+
}
|
|
835
|
+
return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
|
|
836
|
+
}
|
|
837
|
+
function constantTimeEquals(a, b) {
|
|
838
|
+
const left = Buffer.from(a, "utf8");
|
|
839
|
+
const right = Buffer.from(b, "utf8");
|
|
840
|
+
if (left.length !== right.length) {
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
return crypto.timingSafeEqual(left, right);
|
|
844
|
+
}
|
|
845
|
+
var ID_TOKEN_ALG = "EdDSA";
|
|
846
|
+
function assertIdTokenAlg(alg) {
|
|
847
|
+
if (alg !== ID_TOKEN_ALG) {
|
|
848
|
+
throw idTokenAuthError(
|
|
849
|
+
"invalid_alg",
|
|
850
|
+
`expected alg "${ID_TOKEN_ALG}", got ${typeof alg === "string" ? `"${alg}"` : "no alg header"}`
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
function checkIdTokenClaims(claims, expectations, nowSec = Math.floor(Date.now() / 1e3)) {
|
|
855
|
+
const skew = resolveClockSkewSec(expectations.clockSkewSec);
|
|
856
|
+
if (claims.iss !== expectations.issuer) {
|
|
857
|
+
throw idTokenAuthError("invalid_issuer", "iss does not equal the discovery document issuer");
|
|
858
|
+
}
|
|
859
|
+
const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
860
|
+
if (!audiences.includes(expectations.clientId)) {
|
|
861
|
+
throw idTokenAuthError("invalid_audience", "aud does not contain this client_id");
|
|
862
|
+
}
|
|
863
|
+
if (audiences.length > 1 && claims.azp !== expectations.clientId) {
|
|
864
|
+
throw idTokenAuthError(
|
|
865
|
+
"invalid_audience",
|
|
866
|
+
"aud holds multiple audiences and azp is absent or does not equal this client_id"
|
|
867
|
+
);
|
|
868
|
+
}
|
|
869
|
+
if (typeof claims.exp !== "number") {
|
|
870
|
+
throw idTokenAuthError("token_expired", "exp claim is missing or not a number");
|
|
871
|
+
}
|
|
872
|
+
if (claims.exp + skew <= nowSec) {
|
|
873
|
+
throw idTokenAuthError("token_expired", "exp is in the past");
|
|
874
|
+
}
|
|
875
|
+
if (typeof claims.iat !== "number") {
|
|
876
|
+
throw idTokenAuthError("token_expired", "iat claim is missing or not a number");
|
|
877
|
+
}
|
|
878
|
+
if (claims.iat - skew > nowSec) {
|
|
879
|
+
throw idTokenAuthError("token_expired", "iat is in the future");
|
|
880
|
+
}
|
|
881
|
+
if (typeof claims.nbf === "number" && claims.nbf - skew > nowSec) {
|
|
882
|
+
throw idTokenAuthError("token_expired", "nbf is in the future");
|
|
883
|
+
}
|
|
884
|
+
if (expectations.nonce !== void 0) {
|
|
885
|
+
if (typeof claims.nonce !== "string" || !constantTimeEquals(claims.nonce, expectations.nonce)) {
|
|
886
|
+
throw idTokenAuthError("nonce_mismatch", "nonce claim is absent or does not match the request nonce");
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
return claims;
|
|
890
|
+
}
|
|
624
891
|
|
|
625
892
|
// src/node/jwks.ts
|
|
626
893
|
var JWKS_PATH = "/oauth2/jwks";
|
|
627
894
|
var COOLDOWN_DURATION_MS = 6e4;
|
|
628
895
|
var TIMEOUT_DURATION_MS = 5e3;
|
|
629
896
|
function createVerifier(baseUrl) {
|
|
897
|
+
return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
|
|
898
|
+
}
|
|
899
|
+
function createJwksVerifier(jwksUri) {
|
|
630
900
|
let jwksPromise = null;
|
|
631
901
|
async function getJwks() {
|
|
632
902
|
if (!jwksPromise) {
|
|
633
903
|
jwksPromise = import('jose').then(
|
|
634
|
-
({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(
|
|
904
|
+
({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
|
|
635
905
|
cooldownDuration: COOLDOWN_DURATION_MS,
|
|
636
906
|
timeoutDuration: TIMEOUT_DURATION_MS
|
|
637
907
|
})
|
|
@@ -645,13 +915,54 @@ function createVerifier(baseUrl) {
|
|
|
645
915
|
const jwks = await getJwks();
|
|
646
916
|
const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
|
|
647
917
|
return payload;
|
|
918
|
+
},
|
|
919
|
+
async verifyIdToken(token, expectations) {
|
|
920
|
+
const { decodeProtectedHeader, jwtVerify } = await import('jose');
|
|
921
|
+
let header;
|
|
922
|
+
try {
|
|
923
|
+
header = decodeProtectedHeader(token);
|
|
924
|
+
} catch {
|
|
925
|
+
throw idTokenAuthError("invalid_alg", "token is not a well-formed JWS");
|
|
926
|
+
}
|
|
927
|
+
assertIdTokenAlg(header.alg);
|
|
928
|
+
if (!header.kid) {
|
|
929
|
+
throw idTokenAuthError("unknown_kid", "token carries no kid header");
|
|
930
|
+
}
|
|
931
|
+
const jwks = await getJwks();
|
|
932
|
+
const skew = resolveClockSkewSec(expectations.clockSkewSec);
|
|
933
|
+
let claims;
|
|
934
|
+
try {
|
|
935
|
+
const { payload } = await jwtVerify(token, jwks, {
|
|
936
|
+
algorithms: [ID_TOKEN_ALG],
|
|
937
|
+
clockTolerance: skew
|
|
938
|
+
});
|
|
939
|
+
claims = payload;
|
|
940
|
+
} catch (err) {
|
|
941
|
+
throw mapJoseVerifyError(err);
|
|
942
|
+
}
|
|
943
|
+
return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });
|
|
648
944
|
}
|
|
649
945
|
};
|
|
650
946
|
}
|
|
947
|
+
function mapJoseVerifyError(err) {
|
|
948
|
+
const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
|
|
949
|
+
switch (code) {
|
|
950
|
+
case "ERR_JWKS_NO_MATCHING_KEY":
|
|
951
|
+
return idTokenAuthError("unknown_kid", "no JWKS key matches the token kid");
|
|
952
|
+
case "ERR_JWT_EXPIRED":
|
|
953
|
+
return idTokenAuthError("token_expired", "exp is in the past");
|
|
954
|
+
case "ERR_JWT_CLAIM_VALIDATION_FAILED":
|
|
955
|
+
return idTokenAuthError("token_expired", "a time-based claim (nbf/iat) is not yet valid");
|
|
956
|
+
default:
|
|
957
|
+
return idTokenAuthError("invalid_signature", "signature verification failed");
|
|
958
|
+
}
|
|
959
|
+
}
|
|
651
960
|
|
|
652
961
|
// src/node/session.ts
|
|
653
962
|
var NodeSession = class extends SharedSession {
|
|
963
|
+
/** Manages the access/refresh token pair backing this session. */
|
|
654
964
|
tokenManager;
|
|
965
|
+
/** Local JWKS verifier for validating access tokens without a server round-trip. */
|
|
655
966
|
jwksVerifier;
|
|
656
967
|
#jar;
|
|
657
968
|
constructor(options, base, tokenManager, jwksVerifier, jar) {
|
|
@@ -670,8 +981,9 @@ var NodeSession = class extends SharedSession {
|
|
|
670
981
|
* remaining fully independent from any other session's guard.
|
|
671
982
|
*/
|
|
672
983
|
doRefresh = async () => {
|
|
673
|
-
await this.axios.post("/api/v1/auth/refresh",
|
|
984
|
+
await this.axios.post("/api/v1/auth/refresh", this.buildRefreshBody());
|
|
674
985
|
await this.tokenManager.syncFromJar();
|
|
986
|
+
this.#resolveIdentifiersFromToken();
|
|
675
987
|
await this.#syncCsrfFromJar();
|
|
676
988
|
};
|
|
677
989
|
/**
|
|
@@ -683,8 +995,25 @@ var NodeSession = class extends SharedSession {
|
|
|
683
995
|
*/
|
|
684
996
|
onAuthenticated = async () => {
|
|
685
997
|
await this.tokenManager.syncFromJar();
|
|
998
|
+
this.#resolveIdentifiersFromToken();
|
|
686
999
|
await this.#syncCsrfFromJar();
|
|
687
1000
|
};
|
|
1001
|
+
/**
|
|
1002
|
+
* Populate `resolvedTenantId`/`resolvedOrgId` from the cached access token's
|
|
1003
|
+
* claims when present, leaving any UUID resolved from construction options in
|
|
1004
|
+
* place otherwise. Best-effort and unverified (see
|
|
1005
|
+
* TokenManager.claimsFromCachedToken) — used purely to build the refresh body.
|
|
1006
|
+
*/
|
|
1007
|
+
#resolveIdentifiersFromToken() {
|
|
1008
|
+
const { tenantId, orgId } = this.tokenManager.claimsFromCachedToken();
|
|
1009
|
+
if (tenantId) {
|
|
1010
|
+
this.resolvedTenantId = tenantId;
|
|
1011
|
+
this.tokenManager.setTenantId(tenantId);
|
|
1012
|
+
}
|
|
1013
|
+
if (orgId) {
|
|
1014
|
+
this.resolvedOrgId = orgId;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
688
1017
|
async #syncCsrfFromJar() {
|
|
689
1018
|
this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);
|
|
690
1019
|
}
|
|
@@ -700,18 +1029,713 @@ function createNodeSession(options) {
|
|
|
700
1029
|
function createNodeClient(options) {
|
|
701
1030
|
return new AxiamClient(options, createNodeSession(options));
|
|
702
1031
|
}
|
|
1032
|
+
var CODE_CHALLENGE_METHOD_S256 = "S256";
|
|
1033
|
+
var CSPRNG_BYTES = 32;
|
|
1034
|
+
function randomUrlSafeToken(bytes = CSPRNG_BYTES) {
|
|
1035
|
+
return crypto.randomBytes(bytes).toString("base64url");
|
|
1036
|
+
}
|
|
1037
|
+
function generateCodeVerifier() {
|
|
1038
|
+
return new Sensitive(randomUrlSafeToken(CSPRNG_BYTES));
|
|
1039
|
+
}
|
|
1040
|
+
function computeCodeChallenge(codeVerifier) {
|
|
1041
|
+
return crypto.createHash("sha256").update(codeVerifier, "ascii").digest("base64url");
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// src/node/oidc.ts
|
|
1045
|
+
var DISCOVERY_PATH = "/.well-known/openid-configuration";
|
|
1046
|
+
var SSO_START_PATH = "/api/v1/auth/federation/oidc/start";
|
|
1047
|
+
var SSO_CALLBACK_PATH = "/api/v1/auth/federation/oidc/callback";
|
|
1048
|
+
var MIN_DISCOVERY_TTL_MS = 3e5;
|
|
1049
|
+
var OPENID_SCOPE = "openid";
|
|
1050
|
+
var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
|
|
1051
|
+
"response_type",
|
|
1052
|
+
"client_id",
|
|
1053
|
+
"redirect_uri",
|
|
1054
|
+
"scope",
|
|
1055
|
+
"state",
|
|
1056
|
+
"nonce",
|
|
1057
|
+
"code_challenge",
|
|
1058
|
+
"code_challenge_method"
|
|
1059
|
+
]);
|
|
1060
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1061
|
+
var DiscoveryCache = class {
|
|
1062
|
+
#documents = /* @__PURE__ */ new Map();
|
|
1063
|
+
#inFlight = /* @__PURE__ */ new Map();
|
|
1064
|
+
#ttlMs;
|
|
1065
|
+
constructor(ttlMs) {
|
|
1066
|
+
this.#ttlMs = Math.max(ttlMs, MIN_DISCOVERY_TTL_MS);
|
|
1067
|
+
}
|
|
1068
|
+
async get(originKey, fetcher) {
|
|
1069
|
+
const cached = this.#documents.get(originKey);
|
|
1070
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
1071
|
+
return cached.document;
|
|
1072
|
+
}
|
|
1073
|
+
const pending = this.#inFlight.get(originKey);
|
|
1074
|
+
if (pending) {
|
|
1075
|
+
return pending;
|
|
1076
|
+
}
|
|
1077
|
+
const fetch = fetcher().then((document2) => {
|
|
1078
|
+
this.#documents.set(originKey, { document: document2, expiresAt: Date.now() + this.#ttlMs });
|
|
1079
|
+
return document2;
|
|
1080
|
+
}).finally(() => {
|
|
1081
|
+
this.#inFlight.delete(originKey);
|
|
1082
|
+
});
|
|
1083
|
+
this.#inFlight.set(originKey, fetch);
|
|
1084
|
+
return fetch;
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
function normalizeOrigin(url) {
|
|
1088
|
+
const parsed = new URL(url);
|
|
1089
|
+
const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
|
|
1090
|
+
const host = parsed.hostname.toLowerCase();
|
|
1091
|
+
const defaultPort = scheme === "https" ? "443" : scheme === "http" ? "80" : "";
|
|
1092
|
+
const port = parsed.port || defaultPort;
|
|
1093
|
+
return `${scheme}://${host}:${port}`;
|
|
1094
|
+
}
|
|
1095
|
+
function exposeSecret(value) {
|
|
1096
|
+
return typeof value === "string" ? value : value.expose();
|
|
1097
|
+
}
|
|
1098
|
+
function axiosStatus(err) {
|
|
1099
|
+
if (err && typeof err === "object" && "response" in err) {
|
|
1100
|
+
return err.response?.status;
|
|
1101
|
+
}
|
|
1102
|
+
return void 0;
|
|
1103
|
+
}
|
|
1104
|
+
function axiosBody(err) {
|
|
1105
|
+
if (err && typeof err === "object" && "response" in err) {
|
|
1106
|
+
return err.response?.data;
|
|
1107
|
+
}
|
|
1108
|
+
return void 0;
|
|
1109
|
+
}
|
|
1110
|
+
function bodyMessage(body, fallback) {
|
|
1111
|
+
if (body && typeof body === "object") {
|
|
1112
|
+
const record = body;
|
|
1113
|
+
if (typeof record.error_description === "string") {
|
|
1114
|
+
return record.error_description;
|
|
1115
|
+
}
|
|
1116
|
+
if (typeof record.message === "string") {
|
|
1117
|
+
return record.message;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
return fallback;
|
|
1121
|
+
}
|
|
1122
|
+
function mapOidcError(err, url, fallbackMessage) {
|
|
1123
|
+
if (err instanceof AxiamError) {
|
|
1124
|
+
return err;
|
|
1125
|
+
}
|
|
1126
|
+
const status = axiosStatus(err);
|
|
1127
|
+
if (status !== void 0) {
|
|
1128
|
+
const body = axiosBody(err);
|
|
1129
|
+
return mapHttpStatusToError(status, bodyMessage(body, fallbackMessage), { url, body, cause: err });
|
|
1130
|
+
}
|
|
1131
|
+
return new NetworkError(fallbackMessage, sanitizeAxiosError(err));
|
|
1132
|
+
}
|
|
1133
|
+
var OidcClient = class {
|
|
1134
|
+
#session;
|
|
1135
|
+
#options;
|
|
1136
|
+
#discoveryCache;
|
|
1137
|
+
/** One verifier per `jwks_uri` — the same node/jwks.ts implementation the §10 middleware uses. */
|
|
1138
|
+
#verifiers = /* @__PURE__ */ new Map();
|
|
1139
|
+
/** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */
|
|
1140
|
+
#adoptedCredential = null;
|
|
1141
|
+
#adoptionInterceptorInstalled = false;
|
|
1142
|
+
/** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */
|
|
1143
|
+
#pendingRefresh = null;
|
|
1144
|
+
constructor(session, options) {
|
|
1145
|
+
this.#session = session;
|
|
1146
|
+
this.#options = options;
|
|
1147
|
+
this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);
|
|
1148
|
+
}
|
|
1149
|
+
// -------------------------------------------------------------------------
|
|
1150
|
+
// 1. oidcDiscover
|
|
1151
|
+
// -------------------------------------------------------------------------
|
|
1152
|
+
/**
|
|
1153
|
+
* `GET /.well-known/openid-configuration` (§12.1) — fetch the OIDC discovery
|
|
1154
|
+
* document, cached per origin with a ≥5-minute TTL and single-flight
|
|
1155
|
+
* de-duplication of concurrent calls (§12.3 rule 6).
|
|
1156
|
+
*
|
|
1157
|
+
* The document's own `issuer` is authoritative for ID-token validation and
|
|
1158
|
+
* may legitimately differ from `baseUrl` behind a proxy, so a mismatch is
|
|
1159
|
+
* never treated as an error.
|
|
1160
|
+
*/
|
|
1161
|
+
async oidcDiscover() {
|
|
1162
|
+
const originKey = normalizeOrigin(this.#session.baseUrl);
|
|
1163
|
+
return this.#discoveryCache.get(originKey, async () => {
|
|
1164
|
+
const response = await this.#get(DISCOVERY_PATH, "oidc discovery request failed");
|
|
1165
|
+
return response.data;
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
// -------------------------------------------------------------------------
|
|
1169
|
+
// 2. oidcBegin
|
|
1170
|
+
// -------------------------------------------------------------------------
|
|
1171
|
+
/**
|
|
1172
|
+
* Build an authorization request (§12.1) — **pure local computation, no
|
|
1173
|
+
* network I/O**.
|
|
1174
|
+
*
|
|
1175
|
+
* Generates a 32-byte CSPRNG `state` and `nonce` (base64url, unpadded) and a
|
|
1176
|
+
* fresh PKCE verifier/challenge pair using **S256 only** — `plain` is not
|
|
1177
|
+
* implemented anywhere in this SDK. The URL is built from the discovery
|
|
1178
|
+
* document's `authorization_endpoint` with exactly the eight parameters
|
|
1179
|
+
* §12.1 rule 5 mandates, plus any `extraParams` the caller adds.
|
|
1180
|
+
*
|
|
1181
|
+
* Nothing is stored: persist the returned `state`, `nonce` and
|
|
1182
|
+
* `codeVerifier` yourself (§12.3 rule 1).
|
|
1183
|
+
*
|
|
1184
|
+
* @throws Error when `extraParams` tries to override one of the eight
|
|
1185
|
+
* SDK-owned parameters — a programming error, caught at call time.
|
|
1186
|
+
*/
|
|
1187
|
+
oidcBegin(params) {
|
|
1188
|
+
const state = randomUrlSafeToken();
|
|
1189
|
+
const nonce = randomUrlSafeToken();
|
|
1190
|
+
const codeVerifier = generateCodeVerifier();
|
|
1191
|
+
const codeChallenge = computeCodeChallenge(codeVerifier.expose());
|
|
1192
|
+
const scope = normalizeScope(params.scope);
|
|
1193
|
+
const target = new URL(params.configuration.authorization_endpoint);
|
|
1194
|
+
const query = new URLSearchParams(target.search);
|
|
1195
|
+
for (const [key, value] of Object.entries(params.extraParams ?? {})) {
|
|
1196
|
+
if (RESERVED_AUTHORIZE_PARAMS.has(key)) {
|
|
1197
|
+
throw new Error(
|
|
1198
|
+
`oidcBegin: extraParams may not override the SDK-owned authorization parameter "${key}" (CONTRACT.md \xA712.1 rule 5).`
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
query.set(key, value);
|
|
1202
|
+
}
|
|
1203
|
+
query.set("response_type", "code");
|
|
1204
|
+
query.set("client_id", this.#options.clientId);
|
|
1205
|
+
query.set("redirect_uri", params.redirectUri);
|
|
1206
|
+
query.set("scope", scope);
|
|
1207
|
+
query.set("state", state);
|
|
1208
|
+
query.set("nonce", nonce);
|
|
1209
|
+
query.set("code_challenge", codeChallenge);
|
|
1210
|
+
query.set("code_challenge_method", CODE_CHALLENGE_METHOD_S256);
|
|
1211
|
+
target.search = query.toString().replace(/\+/g, "%20");
|
|
1212
|
+
return { url: target.toString(), state, nonce, codeVerifier };
|
|
1213
|
+
}
|
|
1214
|
+
// -------------------------------------------------------------------------
|
|
1215
|
+
// 3. oidcExchange
|
|
1216
|
+
// -------------------------------------------------------------------------
|
|
1217
|
+
/**
|
|
1218
|
+
* `POST /oauth2/token` with `grant_type=authorization_code` (§12.1) —
|
|
1219
|
+
* exchange an authorization code for a token set, validating the returned
|
|
1220
|
+
* ID token in full before returning.
|
|
1221
|
+
*
|
|
1222
|
+
* The `nonce` argument is mandatory: this grant always requests the `openid`
|
|
1223
|
+
* scope, so §12.4 rule 6 always applies. If **any** §12.4 rule fails, the
|
|
1224
|
+
* whole token set is discarded and `AuthError` is raised with the matching
|
|
1225
|
+
* reason code — the access and refresh tokens from the same response are
|
|
1226
|
+
* never returned (§12.4 rule 7).
|
|
1227
|
+
*/
|
|
1228
|
+
async oidcExchange(params) {
|
|
1229
|
+
const configuration = params.configuration ?? await this.oidcDiscover();
|
|
1230
|
+
const form = new URLSearchParams();
|
|
1231
|
+
form.set("grant_type", "authorization_code");
|
|
1232
|
+
form.set("code", params.code);
|
|
1233
|
+
form.set("code_verifier", exposeSecret(params.codeVerifier));
|
|
1234
|
+
form.set("redirect_uri", params.redirectUri);
|
|
1235
|
+
form.set("client_id", this.#options.clientId);
|
|
1236
|
+
this.#appendClientSecret(form);
|
|
1237
|
+
const wire = await this.#postToken(configuration, form, params.tenantId);
|
|
1238
|
+
return this.#toTokenSet(wire, configuration, params.nonce);
|
|
1239
|
+
}
|
|
1240
|
+
// -------------------------------------------------------------------------
|
|
1241
|
+
// 4. oidcRefresh
|
|
1242
|
+
// -------------------------------------------------------------------------
|
|
1243
|
+
/**
|
|
1244
|
+
* `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an
|
|
1245
|
+
* {@link OidcTokenSet}, under the §9 single-flight refresh guard.
|
|
1246
|
+
*
|
|
1247
|
+
* @remarks
|
|
1248
|
+
* This is a **distinct operation** from `AxiamClient.refresh()`, which drives
|
|
1249
|
+
* the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The
|
|
1250
|
+
* two are never merged or aliased and neither falls back to the other
|
|
1251
|
+
* (§12.1). They do share the session's §9 guard, so at most one refresh of
|
|
1252
|
+
* either kind is ever in flight for a session.
|
|
1253
|
+
*
|
|
1254
|
+
* Concurrent `oidcRefresh` calls collapse into one HTTP request and all
|
|
1255
|
+
* receive the same token set — §9 rule 2's result sharing.
|
|
1256
|
+
*
|
|
1257
|
+
* An `id_token` in the response is validated against §12.4 rules 1–5 and 7;
|
|
1258
|
+
* rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce
|
|
1259
|
+
* in a refresh-issued ID token.
|
|
1260
|
+
*/
|
|
1261
|
+
oidcRefresh(params) {
|
|
1262
|
+
const existing = this.#pendingRefresh;
|
|
1263
|
+
if (existing) {
|
|
1264
|
+
return existing;
|
|
1265
|
+
}
|
|
1266
|
+
const pending = this.#refreshUnderGuard(params);
|
|
1267
|
+
this.#pendingRefresh = pending;
|
|
1268
|
+
const clear = () => {
|
|
1269
|
+
if (this.#pendingRefresh === pending) {
|
|
1270
|
+
this.#pendingRefresh = null;
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
pending.then(clear, clear);
|
|
1274
|
+
return pending;
|
|
1275
|
+
}
|
|
1276
|
+
// -------------------------------------------------------------------------
|
|
1277
|
+
// 5. loginClientCredentials
|
|
1278
|
+
// -------------------------------------------------------------------------
|
|
1279
|
+
/**
|
|
1280
|
+
* `POST /oauth2/token` with `grant_type=client_credentials` (§12.1) —
|
|
1281
|
+
* service-account machine-to-machine login.
|
|
1282
|
+
*
|
|
1283
|
+
* Requests no `openid` scope, so the response carries no `id_token`. Pass
|
|
1284
|
+
* `adoptAsCredential: true` to additionally use the returned access token as
|
|
1285
|
+
* this session's bearer credential for subsequent REST calls (§12.1, a MAY).
|
|
1286
|
+
*
|
|
1287
|
+
* @throws AuthError when no `clientSecret` is configured — this grant cannot
|
|
1288
|
+
* be performed by a public client.
|
|
1289
|
+
*/
|
|
1290
|
+
async loginClientCredentials(params = {}) {
|
|
1291
|
+
const configuration = params.configuration ?? await this.oidcDiscover();
|
|
1292
|
+
const form = new URLSearchParams();
|
|
1293
|
+
form.set("grant_type", "client_credentials");
|
|
1294
|
+
form.set("client_id", this.#options.clientId);
|
|
1295
|
+
form.set("client_secret", this.#requireClientSecret("loginClientCredentials"));
|
|
1296
|
+
if (params.scope !== void 0) {
|
|
1297
|
+
form.set("scope", params.scope);
|
|
1298
|
+
}
|
|
1299
|
+
const wire = await this.#postToken(configuration, form, params.tenantId);
|
|
1300
|
+
const tokenSet = await this.#toTokenSet(wire, configuration, void 0);
|
|
1301
|
+
if (params.adoptAsCredential) {
|
|
1302
|
+
this.#adoptCredential(tokenSet.accessToken);
|
|
1303
|
+
}
|
|
1304
|
+
return tokenSet;
|
|
1305
|
+
}
|
|
1306
|
+
// -------------------------------------------------------------------------
|
|
1307
|
+
// 6. introspect
|
|
1308
|
+
// -------------------------------------------------------------------------
|
|
1309
|
+
/**
|
|
1310
|
+
* `POST /oauth2/introspect` (RFC 7662, §12.1) — ask the server whether a
|
|
1311
|
+
* token is active and, if so, for its metadata.
|
|
1312
|
+
*
|
|
1313
|
+
* Requires confidential-client credentials (§12.1 note 4). A `401` here is a
|
|
1314
|
+
* *client-credential* failure surfaced as `OAuthProtocolError`; it never
|
|
1315
|
+
* enters the §9 refresh guard, because refreshing the user session cannot
|
|
1316
|
+
* fix a bad `client_secret` (§12.3 rule 3).
|
|
1317
|
+
*
|
|
1318
|
+
* @throws AuthError when no `clientSecret` is configured.
|
|
1319
|
+
*/
|
|
1320
|
+
async introspect(params) {
|
|
1321
|
+
const configuration = params.configuration ?? await this.oidcDiscover();
|
|
1322
|
+
const form = new URLSearchParams();
|
|
1323
|
+
form.set("token", exposeSecret(params.token));
|
|
1324
|
+
form.set("client_id", this.#options.clientId);
|
|
1325
|
+
form.set("client_secret", this.#requireClientSecret("introspect"));
|
|
1326
|
+
if (params.tokenTypeHint !== void 0) {
|
|
1327
|
+
form.set("token_type_hint", params.tokenTypeHint);
|
|
1328
|
+
}
|
|
1329
|
+
const url = this.#endpointUrl(configuration.introspection_endpoint, params.tenantId);
|
|
1330
|
+
const response = await this.#postForm(url, form, "introspect request failed");
|
|
1331
|
+
const wire = response.data;
|
|
1332
|
+
return {
|
|
1333
|
+
active: wire.active,
|
|
1334
|
+
...wire.sub != null ? { sub: wire.sub } : {},
|
|
1335
|
+
...wire.client_id != null ? { clientId: wire.client_id } : {},
|
|
1336
|
+
...wire.scope != null ? { scope: wire.scope } : {},
|
|
1337
|
+
...wire.token_type != null ? { tokenType: wire.token_type } : {},
|
|
1338
|
+
...wire.exp != null ? { exp: wire.exp } : {},
|
|
1339
|
+
...wire.iat != null ? { iat: wire.iat } : {}
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
// -------------------------------------------------------------------------
|
|
1343
|
+
// 7. revoke
|
|
1344
|
+
// -------------------------------------------------------------------------
|
|
1345
|
+
/**
|
|
1346
|
+
* `POST /oauth2/revoke` (RFC 7009, §12.1) — revoke an access or refresh
|
|
1347
|
+
* token. Returns nothing.
|
|
1348
|
+
*
|
|
1349
|
+
* Per RFC 7009 the server answers `200` for unknown, expired and
|
|
1350
|
+
* already-revoked tokens alike, so revocation is **idempotent**: any `200`
|
|
1351
|
+
* is success and no error is raised for a token the server has never seen.
|
|
1352
|
+
* Only a `401` (client authentication failed) is an error, surfaced as
|
|
1353
|
+
* `OAuthProtocolError` (§12.1 note 5, §12.3 rule 3).
|
|
1354
|
+
*
|
|
1355
|
+
* @throws AuthError when no `clientSecret` is configured.
|
|
1356
|
+
*/
|
|
1357
|
+
async revoke(params) {
|
|
1358
|
+
const configuration = params.configuration ?? await this.oidcDiscover();
|
|
1359
|
+
const form = new URLSearchParams();
|
|
1360
|
+
form.set("token", exposeSecret(params.token));
|
|
1361
|
+
form.set("client_id", this.#options.clientId);
|
|
1362
|
+
form.set("client_secret", this.#requireClientSecret("revoke"));
|
|
1363
|
+
if (params.tokenTypeHint !== void 0) {
|
|
1364
|
+
form.set("token_type_hint", params.tokenTypeHint);
|
|
1365
|
+
}
|
|
1366
|
+
const url = this.#endpointUrl(configuration.revocation_endpoint, params.tenantId);
|
|
1367
|
+
await this.#postForm(url, form, "revoke request failed");
|
|
1368
|
+
}
|
|
1369
|
+
// -------------------------------------------------------------------------
|
|
1370
|
+
// 8. ssoStart
|
|
1371
|
+
// -------------------------------------------------------------------------
|
|
1372
|
+
/**
|
|
1373
|
+
* `POST /api/v1/auth/federation/oidc/start` (§12.1) — step 1 of first-time
|
|
1374
|
+
* SSO against an **upstream** IdP. No JWT required.
|
|
1375
|
+
*
|
|
1376
|
+
* One tenant form (`tenantId` or `tenantSlug`) and one org form (`orgId` or
|
|
1377
|
+
* `orgSlug`) must be resolvable, from the arguments or from the session's
|
|
1378
|
+
* construction options (§5.1). Redirect the browser to the returned
|
|
1379
|
+
* `authorizeUrl` and round-trip `state` back into {@link ssoComplete}
|
|
1380
|
+
* unmodified — the server keeps the nonce to itself (§12.1 note 7).
|
|
1381
|
+
*
|
|
1382
|
+
* @throws AuthError client-side, without a wire call, when tenant or org
|
|
1383
|
+
* context cannot be resolved.
|
|
1384
|
+
*/
|
|
1385
|
+
async ssoStart(params) {
|
|
1386
|
+
const tenantId = params.tenantId ?? this.#session.tenantId;
|
|
1387
|
+
const tenantSlug = params.tenantSlug ?? this.#session.tenantSlug;
|
|
1388
|
+
const orgId = params.orgId ?? this.#session.orgId;
|
|
1389
|
+
const orgSlug = params.orgSlug ?? this.#session.orgSlug;
|
|
1390
|
+
if (!tenantId && !tenantSlug) {
|
|
1391
|
+
throw new AuthError(
|
|
1392
|
+
"ssoStart requires tenant context: pass tenantId or tenantSlug, or construct the client with one (CONTRACT.md \xA75.1)."
|
|
1393
|
+
);
|
|
1394
|
+
}
|
|
1395
|
+
if (!orgId && !orgSlug) {
|
|
1396
|
+
throw new AuthError(
|
|
1397
|
+
"ssoStart requires organization context: pass orgId or orgSlug, or construct the client with one (CONTRACT.md \xA75.1)."
|
|
1398
|
+
);
|
|
1399
|
+
}
|
|
1400
|
+
const body = {
|
|
1401
|
+
federation_config_id: params.federationConfigId,
|
|
1402
|
+
redirect_uri: params.redirectUri
|
|
1403
|
+
};
|
|
1404
|
+
if (tenantId) {
|
|
1405
|
+
body.tenant_id = tenantId;
|
|
1406
|
+
} else if (tenantSlug) {
|
|
1407
|
+
body.tenant_slug = tenantSlug;
|
|
1408
|
+
}
|
|
1409
|
+
if (orgId) {
|
|
1410
|
+
body.org_id = orgId;
|
|
1411
|
+
} else if (orgSlug) {
|
|
1412
|
+
body.org_slug = orgSlug;
|
|
1413
|
+
}
|
|
1414
|
+
const response = await this.#postJson(
|
|
1415
|
+
SSO_START_PATH,
|
|
1416
|
+
body,
|
|
1417
|
+
"ssoStart request failed"
|
|
1418
|
+
);
|
|
1419
|
+
return {
|
|
1420
|
+
authorizeUrl: response.data.authorize_url,
|
|
1421
|
+
state: response.data.state,
|
|
1422
|
+
expiresInSecs: response.data.expires_in_secs
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
// -------------------------------------------------------------------------
|
|
1426
|
+
// 9. ssoComplete
|
|
1427
|
+
// -------------------------------------------------------------------------
|
|
1428
|
+
/**
|
|
1429
|
+
* `POST /api/v1/auth/federation/oidc/callback` (§12.1) — step 2 of upstream
|
|
1430
|
+
* SSO: consumes the single-use `state`, provisions or links the user, and
|
|
1431
|
+
* establishes the session.
|
|
1432
|
+
*
|
|
1433
|
+
* @remarks
|
|
1434
|
+
* The session arrives as **`Set-Cookie`**, not in the response body
|
|
1435
|
+
* (§12.1 note 6), so this call must go through the §4 cookie jar: use a
|
|
1436
|
+
* `NodeSession` (`createNodeSession`/`createNodeClient`) or the session is
|
|
1437
|
+
* silently lost. On success the session is marked authenticated and its
|
|
1438
|
+
* post-authentication hook runs, syncing the CSRF token and cached access
|
|
1439
|
+
* token out of the jar exactly as `login()` does.
|
|
1440
|
+
*
|
|
1441
|
+
* §12.4 does not apply here — no ID token ever reaches the SDK on the
|
|
1442
|
+
* federation path.
|
|
1443
|
+
*/
|
|
1444
|
+
async ssoComplete(params) {
|
|
1445
|
+
const response = await this.#postJson(
|
|
1446
|
+
SSO_CALLBACK_PATH,
|
|
1447
|
+
{ state: params.state, code: params.code },
|
|
1448
|
+
"ssoComplete request failed"
|
|
1449
|
+
);
|
|
1450
|
+
this.#session.authenticated = true;
|
|
1451
|
+
await this.#session.onAuthenticated?.();
|
|
1452
|
+
return {
|
|
1453
|
+
userId: response.data.user_id,
|
|
1454
|
+
sessionId: response.data.session_id,
|
|
1455
|
+
expiresIn: response.data.expires_in,
|
|
1456
|
+
redirectUri: response.data.redirect_uri
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
// -------------------------------------------------------------------------
|
|
1460
|
+
// internals
|
|
1461
|
+
// -------------------------------------------------------------------------
|
|
1462
|
+
/**
|
|
1463
|
+
* Run one `refresh_token` grant under the session's §9 single-flight guard.
|
|
1464
|
+
*
|
|
1465
|
+
* The guard's callback signature returns `void`, so the token set is
|
|
1466
|
+
* published through a local variable. When the callback does NOT run, the
|
|
1467
|
+
* guard was already busy with a *different* refresh (the §1 cookie-session
|
|
1468
|
+
* path, which cannot produce an `OidcTokenSet`); rather than return a stale
|
|
1469
|
+
* or wrong result we simply try again now that the other refresh has
|
|
1470
|
+
* settled. Bounded, so a pathologically busy guard fails loudly instead of
|
|
1471
|
+
* spinning.
|
|
1472
|
+
*/
|
|
1473
|
+
async #refreshUnderGuard(params) {
|
|
1474
|
+
const configuration = params.configuration ?? await this.oidcDiscover();
|
|
1475
|
+
const form = new URLSearchParams();
|
|
1476
|
+
form.set("grant_type", "refresh_token");
|
|
1477
|
+
form.set("refresh_token", exposeSecret(params.refreshToken));
|
|
1478
|
+
form.set("client_id", this.#options.clientId);
|
|
1479
|
+
this.#appendClientSecret(form);
|
|
1480
|
+
if (params.scope !== void 0) {
|
|
1481
|
+
form.set("scope", params.scope);
|
|
1482
|
+
}
|
|
1483
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1484
|
+
let refreshed;
|
|
1485
|
+
await this.#session.refreshGuard(async () => {
|
|
1486
|
+
const wire = await this.#postToken(configuration, form, params.tenantId);
|
|
1487
|
+
refreshed = await this.#toTokenSet(wire, configuration, void 0);
|
|
1488
|
+
});
|
|
1489
|
+
if (refreshed) {
|
|
1490
|
+
return refreshed;
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
throw new AuthError(
|
|
1494
|
+
"oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md \xA79); another refresh kept it busy."
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
/** POST a form body to the token endpoint from the discovery document. */
|
|
1498
|
+
async #postToken(configuration, form, tenantId) {
|
|
1499
|
+
const url = this.#endpointUrl(configuration.token_endpoint, tenantId);
|
|
1500
|
+
const response = await this.#postForm(url, form, "token request failed");
|
|
1501
|
+
return response.data;
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* Convert a `TokenResponse` into an {@link OidcTokenSet}, validating any
|
|
1505
|
+
* `id_token` first (§12.4). Validation precedes construction, so a failure
|
|
1506
|
+
* discards the whole set — the caller never sees the access or refresh token
|
|
1507
|
+
* from a response whose ID token was rejected (§12.4 rule 7).
|
|
1508
|
+
*/
|
|
1509
|
+
async #toTokenSet(wire, configuration, nonce) {
|
|
1510
|
+
let idClaims;
|
|
1511
|
+
if (wire.id_token) {
|
|
1512
|
+
idClaims = await this.#verifierFor(configuration.jwks_uri).verifyIdToken(wire.id_token, {
|
|
1513
|
+
issuer: configuration.issuer,
|
|
1514
|
+
clientId: this.#options.clientId,
|
|
1515
|
+
...nonce !== void 0 ? { nonce } : {},
|
|
1516
|
+
...this.#options.clockSkewSec !== void 0 ? { clockSkewSec: this.#options.clockSkewSec } : {}
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
return {
|
|
1520
|
+
accessToken: new Sensitive(wire.access_token),
|
|
1521
|
+
tokenType: wire.token_type,
|
|
1522
|
+
expiresIn: wire.expires_in,
|
|
1523
|
+
...wire.scope != null ? { scope: wire.scope } : {},
|
|
1524
|
+
...wire.refresh_token != null ? { refreshToken: new Sensitive(wire.refresh_token) } : {},
|
|
1525
|
+
...wire.id_token != null ? { idToken: new Sensitive(wire.id_token) } : {},
|
|
1526
|
+
...idClaims !== void 0 ? { idClaims } : {}
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
/** Lazily build (and reuse) the JWKS verifier for a `jwks_uri` (§12.3 rule 6). */
|
|
1530
|
+
#verifierFor(jwksUri) {
|
|
1531
|
+
const existing = this.#verifiers.get(jwksUri);
|
|
1532
|
+
if (existing) {
|
|
1533
|
+
return existing;
|
|
1534
|
+
}
|
|
1535
|
+
const verifier = createJwksVerifier(jwksUri);
|
|
1536
|
+
this.#verifiers.set(jwksUri, verifier);
|
|
1537
|
+
return verifier;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Build the final endpoint URL: the discovery document's endpoint plus the
|
|
1541
|
+
* mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2). Existing
|
|
1542
|
+
* query parameters on the endpoint are preserved.
|
|
1543
|
+
*/
|
|
1544
|
+
#endpointUrl(endpoint, tenantId) {
|
|
1545
|
+
const url = new URL(endpoint);
|
|
1546
|
+
url.searchParams.set("tenant_id", this.#resolveTenantId(tenantId));
|
|
1547
|
+
return url.toString();
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Resolve the tenant UUID for the `tenant_id` query parameter (§12.3
|
|
1551
|
+
* rule 4): the explicit argument, else the client-level `tenantId`, else the
|
|
1552
|
+
* session's `tenantId` — and only ever a UUID. A slug-only client raises the
|
|
1553
|
+
* taxonomy error client-side, with no wire call, rather than sending a slug
|
|
1554
|
+
* where the server requires a UUID.
|
|
1555
|
+
*/
|
|
1556
|
+
#resolveTenantId(explicit) {
|
|
1557
|
+
const candidate = explicit ?? this.#options.tenantId ?? this.#session.tenantId;
|
|
1558
|
+
if (!candidate) {
|
|
1559
|
+
throw new AuthError(
|
|
1560
|
+
"this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenantId explicitly, or construct the client with the tenantId (UUID) form (CONTRACT.md \xA712.3 rule 4)."
|
|
1561
|
+
);
|
|
1562
|
+
}
|
|
1563
|
+
if (!UUID_RE.test(candidate)) {
|
|
1564
|
+
throw new AuthError(
|
|
1565
|
+
"tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted (CONTRACT.md \xA712.3 rule 4)."
|
|
1566
|
+
);
|
|
1567
|
+
}
|
|
1568
|
+
return candidate;
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Add `client_secret` to a form body for a confidential client, and omit it
|
|
1572
|
+
* entirely for a public client — §12.1 forbids sending an empty/null value
|
|
1573
|
+
* for an absent optional field.
|
|
1574
|
+
*/
|
|
1575
|
+
#appendClientSecret(form) {
|
|
1576
|
+
const secret = this.#options.clientSecret;
|
|
1577
|
+
if (secret !== void 0) {
|
|
1578
|
+
form.set("client_secret", exposeSecret(secret));
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
/** The `client_secret` for an operation that cannot be performed without one (§12.1 note 4). */
|
|
1582
|
+
#requireClientSecret(operation) {
|
|
1583
|
+
const secret = this.#options.clientSecret;
|
|
1584
|
+
if (secret === void 0) {
|
|
1585
|
+
throw new AuthError(
|
|
1586
|
+
`${operation} requires confidential-client credentials: construct the OidcClient with a clientSecret (CONTRACT.md \xA712.1 note 4).`
|
|
1587
|
+
);
|
|
1588
|
+
}
|
|
1589
|
+
return exposeSecret(secret);
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Adopt an access token as this session's bearer credential (§12.1, opt-in).
|
|
1593
|
+
*
|
|
1594
|
+
* The token lives only inside the interceptor closure, behind
|
|
1595
|
+
* {@link Sensitive} — never on `axios.defaults`, a public property or the
|
|
1596
|
+
* cookie jar — so it stays unreachable through any public getter (§12.3
|
|
1597
|
+
* rule 2). It is deliberately NOT sent to `/oauth2/*`: those endpoints
|
|
1598
|
+
* authenticate the client through the form body (§12.1 note 3).
|
|
1599
|
+
*/
|
|
1600
|
+
#adoptCredential(accessToken) {
|
|
1601
|
+
this.#adoptedCredential = accessToken;
|
|
1602
|
+
if (this.#adoptionInterceptorInstalled) {
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
this.#adoptionInterceptorInstalled = true;
|
|
1606
|
+
this.#session.axios.interceptors.request.use((config) => {
|
|
1607
|
+
const adopted = this.#adoptedCredential;
|
|
1608
|
+
const url = config.url ?? "";
|
|
1609
|
+
if (!adopted || this.#session.isForeignHost(url) || url.includes("/oauth2/")) {
|
|
1610
|
+
return config;
|
|
1611
|
+
}
|
|
1612
|
+
config.headers = config.headers ?? {};
|
|
1613
|
+
config.headers["Authorization"] = `Bearer ${adopted.expose()}`;
|
|
1614
|
+
return config;
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
/** GET through the session transport, mapping failures onto the §2 taxonomy. */
|
|
1618
|
+
async #get(url, fallbackMessage) {
|
|
1619
|
+
try {
|
|
1620
|
+
return await this.#session.axios.get(url);
|
|
1621
|
+
} catch (err) {
|
|
1622
|
+
throw mapOidcError(err, url, fallbackMessage);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
/** POST a form-encoded body (§12.1 note 1) through the session transport. */
|
|
1626
|
+
async #postForm(url, form, fallbackMessage) {
|
|
1627
|
+
const config = {
|
|
1628
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" }
|
|
1629
|
+
};
|
|
1630
|
+
try {
|
|
1631
|
+
return await this.#session.axios.post(url, form.toString(), config);
|
|
1632
|
+
} catch (err) {
|
|
1633
|
+
throw mapOidcError(err, url, fallbackMessage);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
/** POST a JSON body (the federation endpoints) through the session transport. */
|
|
1637
|
+
async #postJson(url, body, fallbackMessage) {
|
|
1638
|
+
try {
|
|
1639
|
+
return await this.#session.axios.post(url, body);
|
|
1640
|
+
} catch (err) {
|
|
1641
|
+
throw mapOidcError(err, url, fallbackMessage);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
};
|
|
1645
|
+
function normalizeScope(scope) {
|
|
1646
|
+
const requested = Array.isArray(scope) ? scope : (scope ?? "").split(" ");
|
|
1647
|
+
const values = requested.map((value) => value.trim()).filter(Boolean);
|
|
1648
|
+
if (!values.includes(OPENID_SCOPE)) {
|
|
1649
|
+
values.unshift(OPENID_SCOPE);
|
|
1650
|
+
}
|
|
1651
|
+
return [...new Set(values)].join(" ");
|
|
1652
|
+
}
|
|
1653
|
+
function createOidcClient(session, options) {
|
|
1654
|
+
return new OidcClient(session, options);
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
// src/node/oidcState.ts
|
|
1658
|
+
var OIDC_STATE_TTL_MS = 6e5;
|
|
1659
|
+
var MemoryOidcStateStore = class {
|
|
1660
|
+
#entries = /* @__PURE__ */ new Map();
|
|
1661
|
+
#ttlMs;
|
|
1662
|
+
/**
|
|
1663
|
+
* @param ttlMs entry lifetime in milliseconds. Defaults to
|
|
1664
|
+
* {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
|
|
1665
|
+
* shorter TTL is honoured (useful in tests), a longer one is reduced,
|
|
1666
|
+
* because §12.3 rule 1 fixes 10 minutes as the maximum.
|
|
1667
|
+
*/
|
|
1668
|
+
constructor(ttlMs = OIDC_STATE_TTL_MS) {
|
|
1669
|
+
this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
|
|
1670
|
+
}
|
|
1671
|
+
/** Number of unexpired entries currently held. Intended for tests and metrics. */
|
|
1672
|
+
get size() {
|
|
1673
|
+
this.#sweep();
|
|
1674
|
+
return this.#entries.size;
|
|
1675
|
+
}
|
|
1676
|
+
/** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
|
|
1677
|
+
async save(entry) {
|
|
1678
|
+
this.#sweep();
|
|
1679
|
+
this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
|
|
1680
|
+
}
|
|
1681
|
+
/**
|
|
1682
|
+
* Atomically return and delete the entry for `state`. Deletion happens
|
|
1683
|
+
* before the expiry check, so even an expired hit is removed rather than
|
|
1684
|
+
* left to accumulate — and a second call can never return the same entry
|
|
1685
|
+
* twice regardless of timing (JavaScript's single-threaded event loop makes
|
|
1686
|
+
* this get-then-delete pair genuinely atomic; a store backed by real
|
|
1687
|
+
* concurrency must use an atomic primitive such as Redis `GETDEL`).
|
|
1688
|
+
*/
|
|
1689
|
+
async consume(state) {
|
|
1690
|
+
const held = this.#entries.get(state);
|
|
1691
|
+
if (!held) {
|
|
1692
|
+
return void 0;
|
|
1693
|
+
}
|
|
1694
|
+
this.#entries.delete(state);
|
|
1695
|
+
if (held.expiresAt <= Date.now()) {
|
|
1696
|
+
return void 0;
|
|
1697
|
+
}
|
|
1698
|
+
return held.entry;
|
|
1699
|
+
}
|
|
1700
|
+
/** Drop every expired entry. Lazy housekeeping — no background timer. */
|
|
1701
|
+
#sweep() {
|
|
1702
|
+
const now = Date.now();
|
|
1703
|
+
for (const [state, held] of this.#entries) {
|
|
1704
|
+
if (held.expiresAt <= now) {
|
|
1705
|
+
this.#entries.delete(state);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
703
1710
|
|
|
704
1711
|
exports.ACCESS_COOKIE = ACCESS_COOKIE;
|
|
1712
|
+
exports.CODE_CHALLENGE_METHOD_S256 = CODE_CHALLENGE_METHOD_S256;
|
|
1713
|
+
exports.CSPRNG_BYTES = CSPRNG_BYTES;
|
|
705
1714
|
exports.CSRF_COOKIE = CSRF_COOKIE;
|
|
1715
|
+
exports.DISCOVERY_PATH = DISCOVERY_PATH;
|
|
1716
|
+
exports.ID_TOKEN_ALG = ID_TOKEN_ALG;
|
|
706
1717
|
exports.JWKS_PATH = JWKS_PATH;
|
|
1718
|
+
exports.MAX_CLOCK_SKEW_SEC = MAX_CLOCK_SKEW_SEC;
|
|
1719
|
+
exports.MIN_DISCOVERY_TTL_MS = MIN_DISCOVERY_TTL_MS;
|
|
1720
|
+
exports.MemoryOidcStateStore = MemoryOidcStateStore;
|
|
707
1721
|
exports.NodeSession = NodeSession;
|
|
1722
|
+
exports.OIDC_STATE_TTL_MS = OIDC_STATE_TTL_MS;
|
|
1723
|
+
exports.OidcClient = OidcClient;
|
|
708
1724
|
exports.REFRESH_COOKIE = REFRESH_COOKIE;
|
|
1725
|
+
exports.SSO_CALLBACK_PATH = SSO_CALLBACK_PATH;
|
|
1726
|
+
exports.SSO_START_PATH = SSO_START_PATH;
|
|
709
1727
|
exports.TokenManager = TokenManager;
|
|
1728
|
+
exports.computeCodeChallenge = computeCodeChallenge;
|
|
710
1729
|
exports.createJar = createJar;
|
|
1730
|
+
exports.createJwksVerifier = createJwksVerifier;
|
|
711
1731
|
exports.createNodeClient = createNodeClient;
|
|
712
1732
|
exports.createNodeSession = createNodeSession;
|
|
1733
|
+
exports.createOidcClient = createOidcClient;
|
|
713
1734
|
exports.createVerifier = createVerifier;
|
|
714
1735
|
exports.extractCookieValue = extractCookieValue;
|
|
1736
|
+
exports.generateCodeVerifier = generateCodeVerifier;
|
|
1737
|
+
exports.normalizeOrigin = normalizeOrigin;
|
|
1738
|
+
exports.randomUrlSafeToken = randomUrlSafeToken;
|
|
715
1739
|
exports.wrapAxios = wrapAxios;
|
|
716
1740
|
//# sourceMappingURL=index.js.map
|
|
717
1741
|
//# sourceMappingURL=index.js.map
|