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