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