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.
Files changed (64) hide show
  1. package/README.md +219 -8
  2. package/dist/amqp/index.d.cts +1 -1
  3. package/dist/amqp/index.d.ts +1 -1
  4. package/dist/amqp/index.js +4 -0
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +4 -0
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-xwmCivHH.d.ts → authzCore-DtSN59if.d.ts} +19 -2
  9. package/dist/{authzCore-CV-Td-V1.d.cts → authzCore-DuRI1aJf.d.cts} +19 -2
  10. package/dist/client-B_FqmZ0i.d.cts +72 -0
  11. package/dist/client-Dn1fs5MH.d.ts +72 -0
  12. package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
  13. package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
  14. package/dist/grpc/index.d.cts +113 -6
  15. package/dist/grpc/index.d.ts +113 -6
  16. package/dist/grpc/index.js +435 -18
  17. package/dist/grpc/index.js.map +1 -1
  18. package/dist/grpc/index.mjs +434 -19
  19. package/dist/grpc/index.mjs.map +1 -1
  20. package/dist/index.d.cts +4 -2
  21. package/dist/index.d.ts +4 -2
  22. package/dist/index.js +209 -13
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +204 -14
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/jwks-BgojMGC5.d.cts +152 -0
  27. package/dist/jwks-BgojMGC5.d.ts +152 -0
  28. package/dist/middleware/index.d.cts +208 -8
  29. package/dist/middleware/index.d.ts +208 -8
  30. package/dist/middleware/index.js +1107 -1
  31. package/dist/middleware/index.js.map +1 -1
  32. package/dist/middleware/index.mjs +1100 -3
  33. package/dist/middleware/index.mjs.map +1 -1
  34. package/dist/nestjs/index.d.cts +2 -2
  35. package/dist/nestjs/index.d.ts +2 -2
  36. package/dist/nestjs/index.js +3 -0
  37. package/dist/nestjs/index.js.map +1 -1
  38. package/dist/nestjs/index.mjs +3 -0
  39. package/dist/nestjs/index.mjs.map +1 -1
  40. package/dist/node/index.d.cts +50 -94
  41. package/dist/node/index.d.ts +50 -94
  42. package/dist/node/index.js +1039 -15
  43. package/dist/node/index.js.map +1 -1
  44. package/dist/node/index.mjs +1023 -16
  45. package/dist/node/index.mjs.map +1 -1
  46. package/dist/oidcState-BGxqWUun.d.cts +598 -0
  47. package/dist/oidcState-CkFuCjpM.d.ts +598 -0
  48. package/dist/rest/index.d.cts +107 -5
  49. package/dist/rest/index.d.ts +107 -5
  50. package/dist/rest/index.js +209 -13
  51. package/dist/rest/index.js.map +1 -1
  52. package/dist/rest/index.mjs +204 -14
  53. package/dist/rest/index.mjs.map +1 -1
  54. package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
  55. package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
  56. package/dist/session-BWUWhhyB.d.cts +154 -0
  57. package/dist/session-BWUWhhyB.d.ts +154 -0
  58. package/package.json +2 -2
  59. package/dist/client-BPg9kfKV.d.ts +0 -150
  60. package/dist/client-CAeQw1a-.d.cts +0 -150
  61. package/dist/jwks-CX-nhD6A.d.cts +0 -29
  62. package/dist/jwks-CX-nhD6A.d.ts +0 -29
  63. package/dist/sensitive-CWBH_tHr.d.cts +0 -12
  64. package/dist/sensitive-CWBH_tHr.d.ts +0 -12
@@ -1,4 +1,4 @@
1
- import { timingSafeEqual } from 'crypto';
1
+ import { timingSafeEqual, randomBytes, createHash } from 'crypto';
2
2
 
3
3
  // src/core/errors.ts
4
4
  var AxiamError = class extends Error {
@@ -8,14 +8,40 @@ var AxiamError = class extends Error {
8
8
  }
9
9
  };
10
10
  var AuthError = class _AuthError extends AxiamError {
11
- constructor(message) {
11
+ /**
12
+ * Optional stable, machine-readable reason code for the failure.
13
+ *
14
+ * Populated by the CONTRACT.md §12.4 ID-token validation checklist with
15
+ * one of the seven codes §12.3 rule 3 enumerates (see
16
+ * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.
17
+ * It is a *code*, never free text, so callers can branch on it without
18
+ * parsing `message`.
19
+ */
20
+ reason;
21
+ constructor(message, reason) {
12
22
  super(message);
13
23
  this.name = "AuthError";
24
+ this.reason = reason;
14
25
  Object.setPrototypeOf(this, _AuthError.prototype);
15
26
  }
16
27
  };
28
+ var OAuthProtocolError = class _OAuthProtocolError extends AuthError {
29
+ /** The RFC 6749 `error` code (e.g. `"invalid_grant"`, `"invalid_client"`, `"unsupported_grant_type"`). */
30
+ error;
31
+ /** The server's human-readable `error_description`. Never contains token material. */
32
+ errorDescription;
33
+ constructor(error, errorDescription) {
34
+ super(`${error}: ${errorDescription}`);
35
+ this.name = "OAuthProtocolError";
36
+ this.error = error;
37
+ this.errorDescription = errorDescription;
38
+ Object.setPrototypeOf(this, _OAuthProtocolError.prototype);
39
+ }
40
+ };
17
41
  var AuthzError = class _AuthzError extends AxiamError {
42
+ /** The denied action, when the server reported it. */
18
43
  action;
44
+ /** The resource the denied action targeted, when the server reported it. */
19
45
  resourceId;
20
46
  constructor(message, action, resourceId) {
21
47
  super(message);
@@ -26,6 +52,7 @@ var AuthzError = class _AuthzError extends AxiamError {
26
52
  }
27
53
  };
28
54
  var NetworkError = class _NetworkError extends AxiamError {
55
+ /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */
29
56
  cause;
30
57
  constructor(message, cause) {
31
58
  super(message);
@@ -35,6 +62,111 @@ var NetworkError = class _NetworkError extends AxiamError {
35
62
  }
36
63
  };
37
64
 
65
+ // src/core/errorMapper.ts
66
+ function extractAuthzFieldsFromBody(body) {
67
+ if (body === null || typeof body !== "object") {
68
+ return {};
69
+ }
70
+ const record = body;
71
+ const action = typeof record.action === "string" ? record.action : void 0;
72
+ const resourceId = typeof record.resource_id === "string" ? record.resource_id : void 0;
73
+ return { action, resourceId };
74
+ }
75
+ var OAUTH2_PATH_PREFIX = "/oauth2/";
76
+ function isOAuth2EndpointUrl(url) {
77
+ if (!url) {
78
+ return false;
79
+ }
80
+ try {
81
+ return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);
82
+ } catch {
83
+ return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);
84
+ }
85
+ }
86
+ function isOAuth2ErrorBody(body) {
87
+ if (body === null || typeof body !== "object") {
88
+ return false;
89
+ }
90
+ const record = body;
91
+ return typeof record.error === "string" && typeof record.error_description === "string";
92
+ }
93
+ var SAFE_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
94
+ "content-type",
95
+ "content-length",
96
+ "date",
97
+ "server",
98
+ "retry-after",
99
+ "x-request-id",
100
+ "x-tenant-id"
101
+ ]);
102
+ var REDACTED_HEADER = "[REDACTED]";
103
+ function sanitizeAxiosError(err) {
104
+ if (err === null || typeof err !== "object") {
105
+ return err;
106
+ }
107
+ const candidate = err;
108
+ if (candidate.response === null || typeof candidate.response !== "object") {
109
+ return err;
110
+ }
111
+ const response = candidate.response;
112
+ if (response.headers === null || typeof response.headers !== "object") {
113
+ return err;
114
+ }
115
+ const sanitizedHeaders = { ...response.headers };
116
+ for (const key of Object.keys(sanitizedHeaders)) {
117
+ if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {
118
+ sanitizedHeaders[key] = REDACTED_HEADER;
119
+ }
120
+ }
121
+ return {
122
+ ...err,
123
+ response: {
124
+ ...response,
125
+ headers: sanitizedHeaders
126
+ }
127
+ };
128
+ }
129
+ function mapHttpStatusToError(status, message, ctx) {
130
+ if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {
131
+ return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);
132
+ }
133
+ if (status === 401) {
134
+ return new AuthError(message);
135
+ }
136
+ if (status === 403 || status === 409) {
137
+ const fromBody = extractAuthzFieldsFromBody(ctx?.body);
138
+ return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);
139
+ }
140
+ return new NetworkError(message, sanitizeAxiosError(ctx?.cause));
141
+ }
142
+
143
+ // src/core/sensitive.ts
144
+ var REDACTED = "[SENSITIVE]";
145
+ var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
146
+ var Sensitive = class {
147
+ #value;
148
+ /** Wrap `value` so it can never be logged or serialized by accident. */
149
+ constructor(value) {
150
+ this.#value = value;
151
+ }
152
+ /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */
153
+ expose() {
154
+ return this.#value;
155
+ }
156
+ /** Returns the `"[SENSITIVE]"` placeholder — never the wrapped value. */
157
+ toString() {
158
+ return REDACTED;
159
+ }
160
+ /** Makes `JSON.stringify()` emit the `"[SENSITIVE]"` placeholder. */
161
+ toJSON() {
162
+ return REDACTED;
163
+ }
164
+ /** Makes `console.log`/`util.inspect` print the `"[SENSITIVE]"` placeholder. */
165
+ [NODE_INSPECT_CUSTOM]() {
166
+ return REDACTED;
167
+ }
168
+ };
169
+
38
170
  // src/middleware/authzCore.ts
39
171
  function fromParam(name) {
40
172
  return { kind: "param", name };
@@ -177,6 +309,98 @@ function isCsrfValid(cookieHeader, csrfHeaderValue) {
177
309
  return timingSafeEqual(received, expected);
178
310
  }
179
311
 
312
+ // src/middleware/oidcLoginCore.ts
313
+ function authenticationFailedBody(message) {
314
+ return { error: "authentication_failed", message };
315
+ }
316
+ function invalidRequestBody2(message) {
317
+ return { error: "invalid_request", message };
318
+ }
319
+ function unavailableBody(message) {
320
+ return { error: "oidc_unavailable", message };
321
+ }
322
+ async function beginOidcLogin(options, returnTo) {
323
+ try {
324
+ const configuration = await options.client.oidcDiscover();
325
+ const request = options.client.oidcBegin({
326
+ configuration,
327
+ redirectUri: options.redirectUri,
328
+ ...options.scope !== void 0 ? { scope: options.scope } : {}
329
+ });
330
+ await options.store.save({
331
+ state: request.state,
332
+ nonce: request.nonce,
333
+ codeVerifier: request.codeVerifier,
334
+ redirectUri: options.redirectUri,
335
+ ...returnTo !== void 0 ? { returnTo } : {}
336
+ });
337
+ return { kind: "redirect", url: request.url };
338
+ } catch (err) {
339
+ options.logger?.debug("axiam_sdk.oidc", "oidc login could not be started", {
340
+ reason: err instanceof Error ? err.message : "unknown"
341
+ });
342
+ return { kind: "error", status: 503, body: unavailableBody("could not start the OIDC login flow") };
343
+ }
344
+ }
345
+ async function completeOidcLogin(options, query) {
346
+ if (query.error) {
347
+ options.logger?.debug("axiam_sdk.oidc", "idp returned an authorization error", { error: query.error });
348
+ return {
349
+ kind: "error",
350
+ status: 401,
351
+ body: authenticationFailedBody(
352
+ query.error_description ? `${query.error}: ${query.error_description}` : query.error
353
+ )
354
+ };
355
+ }
356
+ if (!query.state || !query.code) {
357
+ return {
358
+ kind: "error",
359
+ status: 400,
360
+ body: invalidRequestBody2("callback is missing the state or code query parameter")
361
+ };
362
+ }
363
+ const entry = await options.store.consume(query.state);
364
+ if (!entry) {
365
+ options.logger?.debug("axiam_sdk.oidc", "no stored login state for the callback state");
366
+ return {
367
+ kind: "error",
368
+ status: 401,
369
+ body: authenticationFailedBody("unknown, expired, or already-used login state")
370
+ };
371
+ }
372
+ let tokens;
373
+ try {
374
+ tokens = await options.client.oidcExchange({
375
+ code: query.code,
376
+ codeVerifier: entry.codeVerifier,
377
+ nonce: entry.nonce,
378
+ redirectUri: entry.redirectUri
379
+ });
380
+ } catch (err) {
381
+ if (err instanceof NetworkError) {
382
+ options.logger?.debug("axiam_sdk.oidc", "token exchange transport failure");
383
+ return { kind: "error", status: 503, body: unavailableBody("the AXIAM token endpoint is unreachable") };
384
+ }
385
+ const reason = err instanceof AuthError ? err.message : "token exchange failed";
386
+ options.logger?.debug("axiam_sdk.oidc", "token exchange failed", { reason });
387
+ return { kind: "error", status: 401, body: authenticationFailedBody(reason) };
388
+ }
389
+ await options.onSuccess?.(tokens, entry);
390
+ const destination = options.successRedirect ?? entry.returnTo;
391
+ if (destination) {
392
+ return { kind: "redirect", url: destination };
393
+ }
394
+ return {
395
+ kind: "json",
396
+ body: {
397
+ authenticated: true,
398
+ ...typeof tokens.idClaims?.sub === "string" ? { sub: tokens.idClaims.sub } : {},
399
+ expiresIn: tokens.expiresIn
400
+ }
401
+ };
402
+ }
403
+
180
404
  // src/middleware/verifyCore.ts
181
405
  async function authenticateRequest(session, token) {
182
406
  let claims;
@@ -294,6 +518,36 @@ function requireRole(session, ...roles) {
294
518
  next();
295
519
  };
296
520
  }
521
+ function sendOidcOutcome(res, outcome) {
522
+ if (outcome.kind === "redirect") {
523
+ res.redirect(outcome.url);
524
+ return;
525
+ }
526
+ if (outcome.kind === "json") {
527
+ res.status(200).json(outcome.body);
528
+ return;
529
+ }
530
+ res.status(outcome.status).json(outcome.body);
531
+ }
532
+ function oidcLoginHandlers(options) {
533
+ const login = async (req, res) => {
534
+ const returnTo = typeof req.query.returnTo === "string" ? req.query.returnTo : void 0;
535
+ sendOidcOutcome(res, await beginOidcLogin(options, returnTo));
536
+ };
537
+ const callback = async (req, res) => {
538
+ const query = req.query;
539
+ sendOidcOutcome(
540
+ res,
541
+ await completeOidcLogin(options, {
542
+ ...typeof query.state === "string" ? { state: query.state } : {},
543
+ ...typeof query.code === "string" ? { code: query.code } : {},
544
+ ...typeof query.error === "string" ? { error: query.error } : {},
545
+ ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
546
+ })
547
+ );
548
+ };
549
+ return { login, callback };
550
+ }
297
551
 
298
552
  // src/middleware/fastify.ts
299
553
  function missingCredentialsBody2() {
@@ -396,7 +650,850 @@ function requireRoleHook(session, ...roles) {
396
650
  }
397
651
  };
398
652
  }
653
+ async function sendOidcOutcome2(reply, outcome) {
654
+ if (outcome.kind === "redirect") {
655
+ await reply.code(302).header("location", outcome.url).send();
656
+ return;
657
+ }
658
+ if (outcome.kind === "json") {
659
+ await reply.code(200).send(outcome.body);
660
+ return;
661
+ }
662
+ await reply.code(outcome.status).send(outcome.body);
663
+ }
664
+ var oidcLoginPlugin = (options) => {
665
+ const loginPath = options.loginPath ?? "/auth/login";
666
+ const callbackPath = options.callbackPath ?? "/auth/callback";
667
+ const plugin = async (fastify) => {
668
+ fastify.get(loginPath, async (request, reply) => {
669
+ const query = request.query;
670
+ const returnTo = typeof query.returnTo === "string" ? query.returnTo : void 0;
671
+ await sendOidcOutcome2(reply, await beginOidcLogin(options, returnTo));
672
+ });
673
+ fastify.get(callbackPath, async (request, reply) => {
674
+ const query = request.query;
675
+ await sendOidcOutcome2(
676
+ reply,
677
+ await completeOidcLogin(options, {
678
+ ...typeof query.state === "string" ? { state: query.state } : {},
679
+ ...typeof query.code === "string" ? { code: query.code } : {},
680
+ ...typeof query.error === "string" ? { error: query.error } : {},
681
+ ...typeof query.error_description === "string" ? { error_description: query.error_description } : {}
682
+ })
683
+ );
684
+ });
685
+ };
686
+ plugin[/* @__PURE__ */ Symbol.for("fastify.display-name")] = "axiam-oidc-login";
687
+ return plugin;
688
+ };
689
+ var MAX_CLOCK_SKEW_SEC = 60;
690
+ function idTokenAuthError(reason, message) {
691
+ return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);
692
+ }
693
+ function resolveClockSkewSec(clockSkewSec) {
694
+ if (clockSkewSec === void 0) {
695
+ return MAX_CLOCK_SKEW_SEC;
696
+ }
697
+ return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
698
+ }
699
+ function constantTimeEquals(a, b) {
700
+ const left = Buffer.from(a, "utf8");
701
+ const right = Buffer.from(b, "utf8");
702
+ if (left.length !== right.length) {
703
+ return false;
704
+ }
705
+ return timingSafeEqual(left, right);
706
+ }
707
+ var ID_TOKEN_ALG = "EdDSA";
708
+ function assertIdTokenAlg(alg) {
709
+ if (alg !== ID_TOKEN_ALG) {
710
+ throw idTokenAuthError(
711
+ "invalid_alg",
712
+ `expected alg "${ID_TOKEN_ALG}", got ${typeof alg === "string" ? `"${alg}"` : "no alg header"}`
713
+ );
714
+ }
715
+ }
716
+ function checkIdTokenClaims(claims, expectations, nowSec = Math.floor(Date.now() / 1e3)) {
717
+ const skew = resolveClockSkewSec(expectations.clockSkewSec);
718
+ if (claims.iss !== expectations.issuer) {
719
+ throw idTokenAuthError("invalid_issuer", "iss does not equal the discovery document issuer");
720
+ }
721
+ const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
722
+ if (!audiences.includes(expectations.clientId)) {
723
+ throw idTokenAuthError("invalid_audience", "aud does not contain this client_id");
724
+ }
725
+ if (audiences.length > 1 && claims.azp !== expectations.clientId) {
726
+ throw idTokenAuthError(
727
+ "invalid_audience",
728
+ "aud holds multiple audiences and azp is absent or does not equal this client_id"
729
+ );
730
+ }
731
+ if (typeof claims.exp !== "number") {
732
+ throw idTokenAuthError("token_expired", "exp claim is missing or not a number");
733
+ }
734
+ if (claims.exp + skew <= nowSec) {
735
+ throw idTokenAuthError("token_expired", "exp is in the past");
736
+ }
737
+ if (typeof claims.iat !== "number") {
738
+ throw idTokenAuthError("token_expired", "iat claim is missing or not a number");
739
+ }
740
+ if (claims.iat - skew > nowSec) {
741
+ throw idTokenAuthError("token_expired", "iat is in the future");
742
+ }
743
+ if (typeof claims.nbf === "number" && claims.nbf - skew > nowSec) {
744
+ throw idTokenAuthError("token_expired", "nbf is in the future");
745
+ }
746
+ if (expectations.nonce !== void 0) {
747
+ if (typeof claims.nonce !== "string" || !constantTimeEquals(claims.nonce, expectations.nonce)) {
748
+ throw idTokenAuthError("nonce_mismatch", "nonce claim is absent or does not match the request nonce");
749
+ }
750
+ }
751
+ return claims;
752
+ }
753
+
754
+ // src/node/jwks.ts
755
+ var COOLDOWN_DURATION_MS = 6e4;
756
+ var TIMEOUT_DURATION_MS = 5e3;
757
+ function createJwksVerifier(jwksUri) {
758
+ let jwksPromise = null;
759
+ async function getJwks() {
760
+ if (!jwksPromise) {
761
+ jwksPromise = import('jose').then(
762
+ ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
763
+ cooldownDuration: COOLDOWN_DURATION_MS,
764
+ timeoutDuration: TIMEOUT_DURATION_MS
765
+ })
766
+ );
767
+ }
768
+ return jwksPromise;
769
+ }
770
+ return {
771
+ async verifyAccessToken(token) {
772
+ const { jwtVerify } = await import('jose');
773
+ const jwks = await getJwks();
774
+ const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
775
+ return payload;
776
+ },
777
+ async verifyIdToken(token, expectations) {
778
+ const { decodeProtectedHeader, jwtVerify } = await import('jose');
779
+ let header;
780
+ try {
781
+ header = decodeProtectedHeader(token);
782
+ } catch {
783
+ throw idTokenAuthError("invalid_alg", "token is not a well-formed JWS");
784
+ }
785
+ assertIdTokenAlg(header.alg);
786
+ if (!header.kid) {
787
+ throw idTokenAuthError("unknown_kid", "token carries no kid header");
788
+ }
789
+ const jwks = await getJwks();
790
+ const skew = resolveClockSkewSec(expectations.clockSkewSec);
791
+ let claims;
792
+ try {
793
+ const { payload } = await jwtVerify(token, jwks, {
794
+ algorithms: [ID_TOKEN_ALG],
795
+ clockTolerance: skew
796
+ });
797
+ claims = payload;
798
+ } catch (err) {
799
+ throw mapJoseVerifyError(err);
800
+ }
801
+ return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });
802
+ }
803
+ };
804
+ }
805
+ function mapJoseVerifyError(err) {
806
+ const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
807
+ switch (code) {
808
+ case "ERR_JWKS_NO_MATCHING_KEY":
809
+ return idTokenAuthError("unknown_kid", "no JWKS key matches the token kid");
810
+ case "ERR_JWT_EXPIRED":
811
+ return idTokenAuthError("token_expired", "exp is in the past");
812
+ case "ERR_JWT_CLAIM_VALIDATION_FAILED":
813
+ return idTokenAuthError("token_expired", "a time-based claim (nbf/iat) is not yet valid");
814
+ default:
815
+ return idTokenAuthError("invalid_signature", "signature verification failed");
816
+ }
817
+ }
818
+ var CODE_CHALLENGE_METHOD_S256 = "S256";
819
+ var CSPRNG_BYTES = 32;
820
+ function randomUrlSafeToken(bytes = CSPRNG_BYTES) {
821
+ return randomBytes(bytes).toString("base64url");
822
+ }
823
+ function generateCodeVerifier() {
824
+ return new Sensitive(randomUrlSafeToken(CSPRNG_BYTES));
825
+ }
826
+ function computeCodeChallenge(codeVerifier) {
827
+ return createHash("sha256").update(codeVerifier, "ascii").digest("base64url");
828
+ }
829
+
830
+ // src/node/oidc.ts
831
+ var DISCOVERY_PATH = "/.well-known/openid-configuration";
832
+ var SSO_START_PATH = "/api/v1/auth/federation/oidc/start";
833
+ var SSO_CALLBACK_PATH = "/api/v1/auth/federation/oidc/callback";
834
+ var MIN_DISCOVERY_TTL_MS = 3e5;
835
+ var OPENID_SCOPE = "openid";
836
+ var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
837
+ "response_type",
838
+ "client_id",
839
+ "redirect_uri",
840
+ "scope",
841
+ "state",
842
+ "nonce",
843
+ "code_challenge",
844
+ "code_challenge_method"
845
+ ]);
846
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
847
+ var DiscoveryCache = class {
848
+ #documents = /* @__PURE__ */ new Map();
849
+ #inFlight = /* @__PURE__ */ new Map();
850
+ #ttlMs;
851
+ constructor(ttlMs) {
852
+ this.#ttlMs = Math.max(ttlMs, MIN_DISCOVERY_TTL_MS);
853
+ }
854
+ async get(originKey, fetcher) {
855
+ const cached = this.#documents.get(originKey);
856
+ if (cached && cached.expiresAt > Date.now()) {
857
+ return cached.document;
858
+ }
859
+ const pending = this.#inFlight.get(originKey);
860
+ if (pending) {
861
+ return pending;
862
+ }
863
+ const fetch = fetcher().then((document) => {
864
+ this.#documents.set(originKey, { document, expiresAt: Date.now() + this.#ttlMs });
865
+ return document;
866
+ }).finally(() => {
867
+ this.#inFlight.delete(originKey);
868
+ });
869
+ this.#inFlight.set(originKey, fetch);
870
+ return fetch;
871
+ }
872
+ };
873
+ function normalizeOrigin(url) {
874
+ const parsed = new URL(url);
875
+ const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
876
+ const host = parsed.hostname.toLowerCase();
877
+ const defaultPort = scheme === "https" ? "443" : scheme === "http" ? "80" : "";
878
+ const port = parsed.port || defaultPort;
879
+ return `${scheme}://${host}:${port}`;
880
+ }
881
+ function exposeSecret(value) {
882
+ return typeof value === "string" ? value : value.expose();
883
+ }
884
+ function axiosStatus(err) {
885
+ if (err && typeof err === "object" && "response" in err) {
886
+ return err.response?.status;
887
+ }
888
+ return void 0;
889
+ }
890
+ function axiosBody(err) {
891
+ if (err && typeof err === "object" && "response" in err) {
892
+ return err.response?.data;
893
+ }
894
+ return void 0;
895
+ }
896
+ function bodyMessage(body, fallback) {
897
+ if (body && typeof body === "object") {
898
+ const record = body;
899
+ if (typeof record.error_description === "string") {
900
+ return record.error_description;
901
+ }
902
+ if (typeof record.message === "string") {
903
+ return record.message;
904
+ }
905
+ }
906
+ return fallback;
907
+ }
908
+ function mapOidcError(err, url, fallbackMessage) {
909
+ if (err instanceof AxiamError) {
910
+ return err;
911
+ }
912
+ const status = axiosStatus(err);
913
+ if (status !== void 0) {
914
+ const body = axiosBody(err);
915
+ return mapHttpStatusToError(status, bodyMessage(body, fallbackMessage), { url, body, cause: err });
916
+ }
917
+ return new NetworkError(fallbackMessage, sanitizeAxiosError(err));
918
+ }
919
+ var OidcClient = class {
920
+ #session;
921
+ #options;
922
+ #discoveryCache;
923
+ /** One verifier per `jwks_uri` — the same node/jwks.ts implementation the §10 middleware uses. */
924
+ #verifiers = /* @__PURE__ */ new Map();
925
+ /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */
926
+ #adoptedCredential = null;
927
+ #adoptionInterceptorInstalled = false;
928
+ /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */
929
+ #pendingRefresh = null;
930
+ constructor(session, options) {
931
+ this.#session = session;
932
+ this.#options = options;
933
+ this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);
934
+ }
935
+ // -------------------------------------------------------------------------
936
+ // 1. oidcDiscover
937
+ // -------------------------------------------------------------------------
938
+ /**
939
+ * `GET /.well-known/openid-configuration` (§12.1) — fetch the OIDC discovery
940
+ * document, cached per origin with a ≥5-minute TTL and single-flight
941
+ * de-duplication of concurrent calls (§12.3 rule 6).
942
+ *
943
+ * The document's own `issuer` is authoritative for ID-token validation and
944
+ * may legitimately differ from `baseUrl` behind a proxy, so a mismatch is
945
+ * never treated as an error.
946
+ */
947
+ async oidcDiscover() {
948
+ const originKey = normalizeOrigin(this.#session.baseUrl);
949
+ return this.#discoveryCache.get(originKey, async () => {
950
+ const response = await this.#get(DISCOVERY_PATH, "oidc discovery request failed");
951
+ return response.data;
952
+ });
953
+ }
954
+ // -------------------------------------------------------------------------
955
+ // 2. oidcBegin
956
+ // -------------------------------------------------------------------------
957
+ /**
958
+ * Build an authorization request (§12.1) — **pure local computation, no
959
+ * network I/O**.
960
+ *
961
+ * Generates a 32-byte CSPRNG `state` and `nonce` (base64url, unpadded) and a
962
+ * fresh PKCE verifier/challenge pair using **S256 only** — `plain` is not
963
+ * implemented anywhere in this SDK. The URL is built from the discovery
964
+ * document's `authorization_endpoint` with exactly the eight parameters
965
+ * §12.1 rule 5 mandates, plus any `extraParams` the caller adds.
966
+ *
967
+ * Nothing is stored: persist the returned `state`, `nonce` and
968
+ * `codeVerifier` yourself (§12.3 rule 1).
969
+ *
970
+ * @throws Error when `extraParams` tries to override one of the eight
971
+ * SDK-owned parameters — a programming error, caught at call time.
972
+ */
973
+ oidcBegin(params) {
974
+ const state = randomUrlSafeToken();
975
+ const nonce = randomUrlSafeToken();
976
+ const codeVerifier = generateCodeVerifier();
977
+ const codeChallenge = computeCodeChallenge(codeVerifier.expose());
978
+ const scope = normalizeScope(params.scope);
979
+ const target = new URL(params.configuration.authorization_endpoint);
980
+ const query = new URLSearchParams(target.search);
981
+ for (const [key, value] of Object.entries(params.extraParams ?? {})) {
982
+ if (RESERVED_AUTHORIZE_PARAMS.has(key)) {
983
+ throw new Error(
984
+ `oidcBegin: extraParams may not override the SDK-owned authorization parameter "${key}" (CONTRACT.md \xA712.1 rule 5).`
985
+ );
986
+ }
987
+ query.set(key, value);
988
+ }
989
+ query.set("response_type", "code");
990
+ query.set("client_id", this.#options.clientId);
991
+ query.set("redirect_uri", params.redirectUri);
992
+ query.set("scope", scope);
993
+ query.set("state", state);
994
+ query.set("nonce", nonce);
995
+ query.set("code_challenge", codeChallenge);
996
+ query.set("code_challenge_method", CODE_CHALLENGE_METHOD_S256);
997
+ target.search = query.toString().replace(/\+/g, "%20");
998
+ return { url: target.toString(), state, nonce, codeVerifier };
999
+ }
1000
+ // -------------------------------------------------------------------------
1001
+ // 3. oidcExchange
1002
+ // -------------------------------------------------------------------------
1003
+ /**
1004
+ * `POST /oauth2/token` with `grant_type=authorization_code` (§12.1) —
1005
+ * exchange an authorization code for a token set, validating the returned
1006
+ * ID token in full before returning.
1007
+ *
1008
+ * The `nonce` argument is mandatory: this grant always requests the `openid`
1009
+ * scope, so §12.4 rule 6 always applies. If **any** §12.4 rule fails, the
1010
+ * whole token set is discarded and `AuthError` is raised with the matching
1011
+ * reason code — the access and refresh tokens from the same response are
1012
+ * never returned (§12.4 rule 7).
1013
+ */
1014
+ async oidcExchange(params) {
1015
+ const configuration = params.configuration ?? await this.oidcDiscover();
1016
+ const form = new URLSearchParams();
1017
+ form.set("grant_type", "authorization_code");
1018
+ form.set("code", params.code);
1019
+ form.set("code_verifier", exposeSecret(params.codeVerifier));
1020
+ form.set("redirect_uri", params.redirectUri);
1021
+ form.set("client_id", this.#options.clientId);
1022
+ this.#appendClientSecret(form);
1023
+ const wire = await this.#postToken(configuration, form, params.tenantId);
1024
+ return this.#toTokenSet(wire, configuration, params.nonce);
1025
+ }
1026
+ // -------------------------------------------------------------------------
1027
+ // 4. oidcRefresh
1028
+ // -------------------------------------------------------------------------
1029
+ /**
1030
+ * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an
1031
+ * {@link OidcTokenSet}, under the §9 single-flight refresh guard.
1032
+ *
1033
+ * @remarks
1034
+ * This is a **distinct operation** from `AxiamClient.refresh()`, which drives
1035
+ * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The
1036
+ * two are never merged or aliased and neither falls back to the other
1037
+ * (§12.1). They do share the session's §9 guard, so at most one refresh of
1038
+ * either kind is ever in flight for a session.
1039
+ *
1040
+ * Concurrent `oidcRefresh` calls collapse into one HTTP request and all
1041
+ * receive the same token set — §9 rule 2's result sharing.
1042
+ *
1043
+ * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;
1044
+ * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce
1045
+ * in a refresh-issued ID token.
1046
+ */
1047
+ oidcRefresh(params) {
1048
+ const existing = this.#pendingRefresh;
1049
+ if (existing) {
1050
+ return existing;
1051
+ }
1052
+ const pending = this.#refreshUnderGuard(params);
1053
+ this.#pendingRefresh = pending;
1054
+ const clear = () => {
1055
+ if (this.#pendingRefresh === pending) {
1056
+ this.#pendingRefresh = null;
1057
+ }
1058
+ };
1059
+ pending.then(clear, clear);
1060
+ return pending;
1061
+ }
1062
+ // -------------------------------------------------------------------------
1063
+ // 5. loginClientCredentials
1064
+ // -------------------------------------------------------------------------
1065
+ /**
1066
+ * `POST /oauth2/token` with `grant_type=client_credentials` (§12.1) —
1067
+ * service-account machine-to-machine login.
1068
+ *
1069
+ * Requests no `openid` scope, so the response carries no `id_token`. Pass
1070
+ * `adoptAsCredential: true` to additionally use the returned access token as
1071
+ * this session's bearer credential for subsequent REST calls (§12.1, a MAY).
1072
+ *
1073
+ * @throws AuthError when no `clientSecret` is configured — this grant cannot
1074
+ * be performed by a public client.
1075
+ */
1076
+ async loginClientCredentials(params = {}) {
1077
+ const configuration = params.configuration ?? await this.oidcDiscover();
1078
+ const form = new URLSearchParams();
1079
+ form.set("grant_type", "client_credentials");
1080
+ form.set("client_id", this.#options.clientId);
1081
+ form.set("client_secret", this.#requireClientSecret("loginClientCredentials"));
1082
+ if (params.scope !== void 0) {
1083
+ form.set("scope", params.scope);
1084
+ }
1085
+ const wire = await this.#postToken(configuration, form, params.tenantId);
1086
+ const tokenSet = await this.#toTokenSet(wire, configuration, void 0);
1087
+ if (params.adoptAsCredential) {
1088
+ this.#adoptCredential(tokenSet.accessToken);
1089
+ }
1090
+ return tokenSet;
1091
+ }
1092
+ // -------------------------------------------------------------------------
1093
+ // 6. introspect
1094
+ // -------------------------------------------------------------------------
1095
+ /**
1096
+ * `POST /oauth2/introspect` (RFC 7662, §12.1) — ask the server whether a
1097
+ * token is active and, if so, for its metadata.
1098
+ *
1099
+ * Requires confidential-client credentials (§12.1 note 4). A `401` here is a
1100
+ * *client-credential* failure surfaced as `OAuthProtocolError`; it never
1101
+ * enters the §9 refresh guard, because refreshing the user session cannot
1102
+ * fix a bad `client_secret` (§12.3 rule 3).
1103
+ *
1104
+ * @throws AuthError when no `clientSecret` is configured.
1105
+ */
1106
+ async introspect(params) {
1107
+ const configuration = params.configuration ?? await this.oidcDiscover();
1108
+ const form = new URLSearchParams();
1109
+ form.set("token", exposeSecret(params.token));
1110
+ form.set("client_id", this.#options.clientId);
1111
+ form.set("client_secret", this.#requireClientSecret("introspect"));
1112
+ if (params.tokenTypeHint !== void 0) {
1113
+ form.set("token_type_hint", params.tokenTypeHint);
1114
+ }
1115
+ const url = this.#endpointUrl(configuration.introspection_endpoint, params.tenantId);
1116
+ const response = await this.#postForm(url, form, "introspect request failed");
1117
+ const wire = response.data;
1118
+ return {
1119
+ active: wire.active,
1120
+ ...wire.sub != null ? { sub: wire.sub } : {},
1121
+ ...wire.client_id != null ? { clientId: wire.client_id } : {},
1122
+ ...wire.scope != null ? { scope: wire.scope } : {},
1123
+ ...wire.token_type != null ? { tokenType: wire.token_type } : {},
1124
+ ...wire.exp != null ? { exp: wire.exp } : {},
1125
+ ...wire.iat != null ? { iat: wire.iat } : {}
1126
+ };
1127
+ }
1128
+ // -------------------------------------------------------------------------
1129
+ // 7. revoke
1130
+ // -------------------------------------------------------------------------
1131
+ /**
1132
+ * `POST /oauth2/revoke` (RFC 7009, §12.1) — revoke an access or refresh
1133
+ * token. Returns nothing.
1134
+ *
1135
+ * Per RFC 7009 the server answers `200` for unknown, expired and
1136
+ * already-revoked tokens alike, so revocation is **idempotent**: any `200`
1137
+ * is success and no error is raised for a token the server has never seen.
1138
+ * Only a `401` (client authentication failed) is an error, surfaced as
1139
+ * `OAuthProtocolError` (§12.1 note 5, §12.3 rule 3).
1140
+ *
1141
+ * @throws AuthError when no `clientSecret` is configured.
1142
+ */
1143
+ async revoke(params) {
1144
+ const configuration = params.configuration ?? await this.oidcDiscover();
1145
+ const form = new URLSearchParams();
1146
+ form.set("token", exposeSecret(params.token));
1147
+ form.set("client_id", this.#options.clientId);
1148
+ form.set("client_secret", this.#requireClientSecret("revoke"));
1149
+ if (params.tokenTypeHint !== void 0) {
1150
+ form.set("token_type_hint", params.tokenTypeHint);
1151
+ }
1152
+ const url = this.#endpointUrl(configuration.revocation_endpoint, params.tenantId);
1153
+ await this.#postForm(url, form, "revoke request failed");
1154
+ }
1155
+ // -------------------------------------------------------------------------
1156
+ // 8. ssoStart
1157
+ // -------------------------------------------------------------------------
1158
+ /**
1159
+ * `POST /api/v1/auth/federation/oidc/start` (§12.1) — step 1 of first-time
1160
+ * SSO against an **upstream** IdP. No JWT required.
1161
+ *
1162
+ * One tenant form (`tenantId` or `tenantSlug`) and one org form (`orgId` or
1163
+ * `orgSlug`) must be resolvable, from the arguments or from the session's
1164
+ * construction options (§5.1). Redirect the browser to the returned
1165
+ * `authorizeUrl` and round-trip `state` back into {@link ssoComplete}
1166
+ * unmodified — the server keeps the nonce to itself (§12.1 note 7).
1167
+ *
1168
+ * @throws AuthError client-side, without a wire call, when tenant or org
1169
+ * context cannot be resolved.
1170
+ */
1171
+ async ssoStart(params) {
1172
+ const tenantId = params.tenantId ?? this.#session.tenantId;
1173
+ const tenantSlug = params.tenantSlug ?? this.#session.tenantSlug;
1174
+ const orgId = params.orgId ?? this.#session.orgId;
1175
+ const orgSlug = params.orgSlug ?? this.#session.orgSlug;
1176
+ if (!tenantId && !tenantSlug) {
1177
+ throw new AuthError(
1178
+ "ssoStart requires tenant context: pass tenantId or tenantSlug, or construct the client with one (CONTRACT.md \xA75.1)."
1179
+ );
1180
+ }
1181
+ if (!orgId && !orgSlug) {
1182
+ throw new AuthError(
1183
+ "ssoStart requires organization context: pass orgId or orgSlug, or construct the client with one (CONTRACT.md \xA75.1)."
1184
+ );
1185
+ }
1186
+ const body = {
1187
+ federation_config_id: params.federationConfigId,
1188
+ redirect_uri: params.redirectUri
1189
+ };
1190
+ if (tenantId) {
1191
+ body.tenant_id = tenantId;
1192
+ } else if (tenantSlug) {
1193
+ body.tenant_slug = tenantSlug;
1194
+ }
1195
+ if (orgId) {
1196
+ body.org_id = orgId;
1197
+ } else if (orgSlug) {
1198
+ body.org_slug = orgSlug;
1199
+ }
1200
+ const response = await this.#postJson(
1201
+ SSO_START_PATH,
1202
+ body,
1203
+ "ssoStart request failed"
1204
+ );
1205
+ return {
1206
+ authorizeUrl: response.data.authorize_url,
1207
+ state: response.data.state,
1208
+ expiresInSecs: response.data.expires_in_secs
1209
+ };
1210
+ }
1211
+ // -------------------------------------------------------------------------
1212
+ // 9. ssoComplete
1213
+ // -------------------------------------------------------------------------
1214
+ /**
1215
+ * `POST /api/v1/auth/federation/oidc/callback` (§12.1) — step 2 of upstream
1216
+ * SSO: consumes the single-use `state`, provisions or links the user, and
1217
+ * establishes the session.
1218
+ *
1219
+ * @remarks
1220
+ * The session arrives as **`Set-Cookie`**, not in the response body
1221
+ * (§12.1 note 6), so this call must go through the §4 cookie jar: use a
1222
+ * `NodeSession` (`createNodeSession`/`createNodeClient`) or the session is
1223
+ * silently lost. On success the session is marked authenticated and its
1224
+ * post-authentication hook runs, syncing the CSRF token and cached access
1225
+ * token out of the jar exactly as `login()` does.
1226
+ *
1227
+ * §12.4 does not apply here — no ID token ever reaches the SDK on the
1228
+ * federation path.
1229
+ */
1230
+ async ssoComplete(params) {
1231
+ const response = await this.#postJson(
1232
+ SSO_CALLBACK_PATH,
1233
+ { state: params.state, code: params.code },
1234
+ "ssoComplete request failed"
1235
+ );
1236
+ this.#session.authenticated = true;
1237
+ await this.#session.onAuthenticated?.();
1238
+ return {
1239
+ userId: response.data.user_id,
1240
+ sessionId: response.data.session_id,
1241
+ expiresIn: response.data.expires_in,
1242
+ redirectUri: response.data.redirect_uri
1243
+ };
1244
+ }
1245
+ // -------------------------------------------------------------------------
1246
+ // internals
1247
+ // -------------------------------------------------------------------------
1248
+ /**
1249
+ * Run one `refresh_token` grant under the session's §9 single-flight guard.
1250
+ *
1251
+ * The guard's callback signature returns `void`, so the token set is
1252
+ * published through a local variable. When the callback does NOT run, the
1253
+ * guard was already busy with a *different* refresh (the §1 cookie-session
1254
+ * path, which cannot produce an `OidcTokenSet`); rather than return a stale
1255
+ * or wrong result we simply try again now that the other refresh has
1256
+ * settled. Bounded, so a pathologically busy guard fails loudly instead of
1257
+ * spinning.
1258
+ */
1259
+ async #refreshUnderGuard(params) {
1260
+ const configuration = params.configuration ?? await this.oidcDiscover();
1261
+ const form = new URLSearchParams();
1262
+ form.set("grant_type", "refresh_token");
1263
+ form.set("refresh_token", exposeSecret(params.refreshToken));
1264
+ form.set("client_id", this.#options.clientId);
1265
+ this.#appendClientSecret(form);
1266
+ if (params.scope !== void 0) {
1267
+ form.set("scope", params.scope);
1268
+ }
1269
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1270
+ let refreshed;
1271
+ await this.#session.refreshGuard(async () => {
1272
+ const wire = await this.#postToken(configuration, form, params.tenantId);
1273
+ refreshed = await this.#toTokenSet(wire, configuration, void 0);
1274
+ });
1275
+ if (refreshed) {
1276
+ return refreshed;
1277
+ }
1278
+ }
1279
+ throw new AuthError(
1280
+ "oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md \xA79); another refresh kept it busy."
1281
+ );
1282
+ }
1283
+ /** POST a form body to the token endpoint from the discovery document. */
1284
+ async #postToken(configuration, form, tenantId) {
1285
+ const url = this.#endpointUrl(configuration.token_endpoint, tenantId);
1286
+ const response = await this.#postForm(url, form, "token request failed");
1287
+ return response.data;
1288
+ }
1289
+ /**
1290
+ * Convert a `TokenResponse` into an {@link OidcTokenSet}, validating any
1291
+ * `id_token` first (§12.4). Validation precedes construction, so a failure
1292
+ * discards the whole set — the caller never sees the access or refresh token
1293
+ * from a response whose ID token was rejected (§12.4 rule 7).
1294
+ */
1295
+ async #toTokenSet(wire, configuration, nonce) {
1296
+ let idClaims;
1297
+ if (wire.id_token) {
1298
+ idClaims = await this.#verifierFor(configuration.jwks_uri).verifyIdToken(wire.id_token, {
1299
+ issuer: configuration.issuer,
1300
+ clientId: this.#options.clientId,
1301
+ ...nonce !== void 0 ? { nonce } : {},
1302
+ ...this.#options.clockSkewSec !== void 0 ? { clockSkewSec: this.#options.clockSkewSec } : {}
1303
+ });
1304
+ }
1305
+ return {
1306
+ accessToken: new Sensitive(wire.access_token),
1307
+ tokenType: wire.token_type,
1308
+ expiresIn: wire.expires_in,
1309
+ ...wire.scope != null ? { scope: wire.scope } : {},
1310
+ ...wire.refresh_token != null ? { refreshToken: new Sensitive(wire.refresh_token) } : {},
1311
+ ...wire.id_token != null ? { idToken: new Sensitive(wire.id_token) } : {},
1312
+ ...idClaims !== void 0 ? { idClaims } : {}
1313
+ };
1314
+ }
1315
+ /** Lazily build (and reuse) the JWKS verifier for a `jwks_uri` (§12.3 rule 6). */
1316
+ #verifierFor(jwksUri) {
1317
+ const existing = this.#verifiers.get(jwksUri);
1318
+ if (existing) {
1319
+ return existing;
1320
+ }
1321
+ const verifier = createJwksVerifier(jwksUri);
1322
+ this.#verifiers.set(jwksUri, verifier);
1323
+ return verifier;
1324
+ }
1325
+ /**
1326
+ * Build the final endpoint URL: the discovery document's endpoint plus the
1327
+ * mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2). Existing
1328
+ * query parameters on the endpoint are preserved.
1329
+ */
1330
+ #endpointUrl(endpoint, tenantId) {
1331
+ const url = new URL(endpoint);
1332
+ url.searchParams.set("tenant_id", this.#resolveTenantId(tenantId));
1333
+ return url.toString();
1334
+ }
1335
+ /**
1336
+ * Resolve the tenant UUID for the `tenant_id` query parameter (§12.3
1337
+ * rule 4): the explicit argument, else the client-level `tenantId`, else the
1338
+ * session's `tenantId` — and only ever a UUID. A slug-only client raises the
1339
+ * taxonomy error client-side, with no wire call, rather than sending a slug
1340
+ * where the server requires a UUID.
1341
+ */
1342
+ #resolveTenantId(explicit) {
1343
+ const candidate = explicit ?? this.#options.tenantId ?? this.#session.tenantId;
1344
+ if (!candidate) {
1345
+ throw new AuthError(
1346
+ "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)."
1347
+ );
1348
+ }
1349
+ if (!UUID_RE.test(candidate)) {
1350
+ throw new AuthError(
1351
+ "tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted (CONTRACT.md \xA712.3 rule 4)."
1352
+ );
1353
+ }
1354
+ return candidate;
1355
+ }
1356
+ /**
1357
+ * Add `client_secret` to a form body for a confidential client, and omit it
1358
+ * entirely for a public client — §12.1 forbids sending an empty/null value
1359
+ * for an absent optional field.
1360
+ */
1361
+ #appendClientSecret(form) {
1362
+ const secret = this.#options.clientSecret;
1363
+ if (secret !== void 0) {
1364
+ form.set("client_secret", exposeSecret(secret));
1365
+ }
1366
+ }
1367
+ /** The `client_secret` for an operation that cannot be performed without one (§12.1 note 4). */
1368
+ #requireClientSecret(operation) {
1369
+ const secret = this.#options.clientSecret;
1370
+ if (secret === void 0) {
1371
+ throw new AuthError(
1372
+ `${operation} requires confidential-client credentials: construct the OidcClient with a clientSecret (CONTRACT.md \xA712.1 note 4).`
1373
+ );
1374
+ }
1375
+ return exposeSecret(secret);
1376
+ }
1377
+ /**
1378
+ * Adopt an access token as this session's bearer credential (§12.1, opt-in).
1379
+ *
1380
+ * The token lives only inside the interceptor closure, behind
1381
+ * {@link Sensitive} — never on `axios.defaults`, a public property or the
1382
+ * cookie jar — so it stays unreachable through any public getter (§12.3
1383
+ * rule 2). It is deliberately NOT sent to `/oauth2/*`: those endpoints
1384
+ * authenticate the client through the form body (§12.1 note 3).
1385
+ */
1386
+ #adoptCredential(accessToken) {
1387
+ this.#adoptedCredential = accessToken;
1388
+ if (this.#adoptionInterceptorInstalled) {
1389
+ return;
1390
+ }
1391
+ this.#adoptionInterceptorInstalled = true;
1392
+ this.#session.axios.interceptors.request.use((config) => {
1393
+ const adopted = this.#adoptedCredential;
1394
+ const url = config.url ?? "";
1395
+ if (!adopted || this.#session.isForeignHost(url) || url.includes("/oauth2/")) {
1396
+ return config;
1397
+ }
1398
+ config.headers = config.headers ?? {};
1399
+ config.headers["Authorization"] = `Bearer ${adopted.expose()}`;
1400
+ return config;
1401
+ });
1402
+ }
1403
+ /** GET through the session transport, mapping failures onto the §2 taxonomy. */
1404
+ async #get(url, fallbackMessage) {
1405
+ try {
1406
+ return await this.#session.axios.get(url);
1407
+ } catch (err) {
1408
+ throw mapOidcError(err, url, fallbackMessage);
1409
+ }
1410
+ }
1411
+ /** POST a form-encoded body (§12.1 note 1) through the session transport. */
1412
+ async #postForm(url, form, fallbackMessage) {
1413
+ const config = {
1414
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
1415
+ };
1416
+ try {
1417
+ return await this.#session.axios.post(url, form.toString(), config);
1418
+ } catch (err) {
1419
+ throw mapOidcError(err, url, fallbackMessage);
1420
+ }
1421
+ }
1422
+ /** POST a JSON body (the federation endpoints) through the session transport. */
1423
+ async #postJson(url, body, fallbackMessage) {
1424
+ try {
1425
+ return await this.#session.axios.post(url, body);
1426
+ } catch (err) {
1427
+ throw mapOidcError(err, url, fallbackMessage);
1428
+ }
1429
+ }
1430
+ };
1431
+ function normalizeScope(scope) {
1432
+ const requested = Array.isArray(scope) ? scope : (scope ?? "").split(" ");
1433
+ const values = requested.map((value) => value.trim()).filter(Boolean);
1434
+ if (!values.includes(OPENID_SCOPE)) {
1435
+ values.unshift(OPENID_SCOPE);
1436
+ }
1437
+ return [...new Set(values)].join(" ");
1438
+ }
1439
+ function createOidcClient(session, options) {
1440
+ return new OidcClient(session, options);
1441
+ }
1442
+
1443
+ // src/node/oidcState.ts
1444
+ var OIDC_STATE_TTL_MS = 6e5;
1445
+ var MemoryOidcStateStore = class {
1446
+ #entries = /* @__PURE__ */ new Map();
1447
+ #ttlMs;
1448
+ /**
1449
+ * @param ttlMs entry lifetime in milliseconds. Defaults to
1450
+ * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a
1451
+ * shorter TTL is honoured (useful in tests), a longer one is reduced,
1452
+ * because §12.3 rule 1 fixes 10 minutes as the maximum.
1453
+ */
1454
+ constructor(ttlMs = OIDC_STATE_TTL_MS) {
1455
+ this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);
1456
+ }
1457
+ /** Number of unexpired entries currently held. Intended for tests and metrics. */
1458
+ get size() {
1459
+ this.#sweep();
1460
+ return this.#entries.size;
1461
+ }
1462
+ /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */
1463
+ async save(entry) {
1464
+ this.#sweep();
1465
+ this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });
1466
+ }
1467
+ /**
1468
+ * Atomically return and delete the entry for `state`. Deletion happens
1469
+ * before the expiry check, so even an expired hit is removed rather than
1470
+ * left to accumulate — and a second call can never return the same entry
1471
+ * twice regardless of timing (JavaScript's single-threaded event loop makes
1472
+ * this get-then-delete pair genuinely atomic; a store backed by real
1473
+ * concurrency must use an atomic primitive such as Redis `GETDEL`).
1474
+ */
1475
+ async consume(state) {
1476
+ const held = this.#entries.get(state);
1477
+ if (!held) {
1478
+ return void 0;
1479
+ }
1480
+ this.#entries.delete(state);
1481
+ if (held.expiresAt <= Date.now()) {
1482
+ return void 0;
1483
+ }
1484
+ return held.entry;
1485
+ }
1486
+ /** Drop every expired entry. Lazy housekeeping — no background timer. */
1487
+ #sweep() {
1488
+ const now = Date.now();
1489
+ for (const [state, held] of this.#entries) {
1490
+ if (held.expiresAt <= now) {
1491
+ this.#entries.delete(state);
1492
+ }
1493
+ }
1494
+ }
1495
+ };
399
1496
 
400
- export { ACCESS_COOKIE_NAME, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, ResourceResolutionError, assertAuthzClient, authenticateRequest, axiamMiddleware, axiamPlugin, evaluateAccess, extractCredential, extractToken, fromParam, hasAnyRole, isCsrfValid, isSafeMethod, parseCookieHeader, requireAccess, requireAccessHook, requireAuth, requireAuthHook, requireRole, requireRoleHook, resolveResourceId };
1497
+ export { ACCESS_COOKIE_NAME, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, MIN_DISCOVERY_TTL_MS, MemoryOidcStateStore, OIDC_STATE_TTL_MS, OidcClient, ResourceResolutionError, assertAuthzClient, authenticateRequest, axiamMiddleware, axiamPlugin, beginOidcLogin, completeOidcLogin, createOidcClient, evaluateAccess, extractCredential, extractToken, fromParam, hasAnyRole, isCsrfValid, isSafeMethod, oidcLoginHandlers, oidcLoginPlugin, parseCookieHeader, requireAccess, requireAccessHook, requireAuth, requireAuthHook, requireRole, requireRoleHook, resolveResourceId };
401
1498
  //# sourceMappingURL=index.mjs.map
402
1499
  //# sourceMappingURL=index.mjs.map