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
@@ -4,6 +4,7 @@ var grpc2 = require('@grpc/grpc-js');
4
4
  var axios = require('axios');
5
5
  var toughCookie = require('tough-cookie');
6
6
  var axiosCookiejarSupport = require('axios-cookiejar-support');
7
+ var crypto = require('crypto');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
@@ -57,14 +58,40 @@ var AxiamError = class extends Error {
57
58
  }
58
59
  };
59
60
  var AuthError = class _AuthError extends AxiamError {
60
- constructor(message) {
61
+ /**
62
+ * Optional stable, machine-readable reason code for the failure.
63
+ *
64
+ * Populated by the CONTRACT.md §12.4 ID-token validation checklist with
65
+ * one of the seven codes §12.3 rule 3 enumerates (see
66
+ * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.
67
+ * It is a *code*, never free text, so callers can branch on it without
68
+ * parsing `message`.
69
+ */
70
+ reason;
71
+ constructor(message, reason) {
61
72
  super(message);
62
73
  this.name = "AuthError";
74
+ this.reason = reason;
63
75
  Object.setPrototypeOf(this, _AuthError.prototype);
64
76
  }
65
77
  };
78
+ var OAuthProtocolError = class _OAuthProtocolError extends AuthError {
79
+ /** The RFC 6749 `error` code (e.g. `"invalid_grant"`, `"invalid_client"`, `"unsupported_grant_type"`). */
80
+ error;
81
+ /** The server's human-readable `error_description`. Never contains token material. */
82
+ errorDescription;
83
+ constructor(error, errorDescription) {
84
+ super(`${error}: ${errorDescription}`);
85
+ this.name = "OAuthProtocolError";
86
+ this.error = error;
87
+ this.errorDescription = errorDescription;
88
+ Object.setPrototypeOf(this, _OAuthProtocolError.prototype);
89
+ }
90
+ };
66
91
  var AuthzError = class _AuthzError extends AxiamError {
92
+ /** The denied action, when the server reported it. */
67
93
  action;
94
+ /** The resource the denied action targeted, when the server reported it. */
68
95
  resourceId;
69
96
  constructor(message, action, resourceId) {
70
97
  super(message);
@@ -75,6 +102,7 @@ var AuthzError = class _AuthzError extends AxiamError {
75
102
  }
76
103
  };
77
104
  var NetworkError = class _NetworkError extends AxiamError {
105
+ /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */
78
106
  cause;
79
107
  constructor(message, cause) {
80
108
  super(message);
@@ -98,6 +126,24 @@ function extractAuthzFieldsFromBody(body) {
98
126
  const resourceId = typeof record.resource_id === "string" ? record.resource_id : void 0;
99
127
  return { action, resourceId };
100
128
  }
129
+ var OAUTH2_PATH_PREFIX = "/oauth2/";
130
+ function isOAuth2EndpointUrl(url) {
131
+ if (!url) {
132
+ return false;
133
+ }
134
+ try {
135
+ return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);
136
+ } catch {
137
+ return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);
138
+ }
139
+ }
140
+ function isOAuth2ErrorBody(body) {
141
+ if (body === null || typeof body !== "object") {
142
+ return false;
143
+ }
144
+ const record = body;
145
+ return typeof record.error === "string" && typeof record.error_description === "string";
146
+ }
101
147
  var SAFE_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
102
148
  "content-type",
103
149
  "content-length",
@@ -135,6 +181,9 @@ function sanitizeAxiosError(err) {
135
181
  };
136
182
  }
137
183
  function mapHttpStatusToError(status, message, ctx) {
184
+ if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {
185
+ return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);
186
+ }
138
187
  if (status === 401) {
139
188
  return new AuthError(message);
140
189
  }
@@ -159,6 +208,7 @@ var REDACTED = "[SENSITIVE]";
159
208
  var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
160
209
  var Sensitive = class {
161
210
  #value;
211
+ /** Wrap `value` so it can never be logged or serialized by accident. */
162
212
  constructor(value) {
163
213
  this.#value = value;
164
214
  }
@@ -166,12 +216,15 @@ var Sensitive = class {
166
216
  expose() {
167
217
  return this.#value;
168
218
  }
219
+ /** Returns the `"[SENSITIVE]"` placeholder — never the wrapped value. */
169
220
  toString() {
170
221
  return REDACTED;
171
222
  }
223
+ /** Makes `JSON.stringify()` emit the `"[SENSITIVE]"` placeholder. */
172
224
  toJSON() {
173
225
  return REDACTED;
174
226
  }
227
+ /** Makes `console.log`/`util.inspect` print the `"[SENSITIVE]"` placeholder. */
175
228
  [NODE_INSPECT_CUSTOM]() {
176
229
  return REDACTED;
177
230
  }
@@ -215,6 +268,31 @@ createRefreshGuard();
215
268
 
216
269
  // src/core/config.ts
217
270
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
271
+ var CERT_PEM_MARKER = "-----BEGIN CERTIFICATE-----";
272
+ var PRIVATE_KEY_PEM_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/;
273
+ function resolveClientIdentity(options) {
274
+ const hasCert = options.clientCert !== void 0;
275
+ const hasKey = options.clientKey !== void 0;
276
+ if (hasCert !== hasKey) {
277
+ throw new Error(
278
+ "clientCert and clientKey must be provided together for mutual TLS (one was given without the other) (CONTRACT.md \xA76.1)."
279
+ );
280
+ }
281
+ if (!hasCert || !hasKey) {
282
+ return void 0;
283
+ }
284
+ if (!options.clientCert.includes(CERT_PEM_MARKER)) {
285
+ throw new Error(
286
+ 'clientCert must be a PEM-encoded certificate chain (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76.1).'
287
+ );
288
+ }
289
+ if (!PRIVATE_KEY_PEM_RE.test(options.clientKey)) {
290
+ throw new Error(
291
+ 'clientKey must be a PEM-encoded private key (expected to contain "-----BEGIN PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----") (CONTRACT.md \xA76.1).'
292
+ );
293
+ }
294
+ return { cert: options.clientCert, key: new Sensitive(options.clientKey) };
295
+ }
218
296
 
219
297
  // src/grpc/callWithRefresh.ts
220
298
  function isGrpcServiceError(err) {
@@ -257,6 +335,17 @@ function fromWireResponse(resp) {
257
335
  reason: resp.deny_reason ? resp.deny_reason : void 0
258
336
  };
259
337
  }
338
+ function fromWireUserInfo(resp) {
339
+ return {
340
+ sub: resp.sub,
341
+ tenantId: resp.tenant_id,
342
+ orgId: resp.org_id,
343
+ // Preserve absence: a missing (scope-gated) claim stays `undefined` rather
344
+ // than becoming an empty string.
345
+ email: resp.email ? resp.email : void 0,
346
+ preferredUsername: resp.preferred_username ? resp.preferred_username : void 0
347
+ };
348
+ }
260
349
  function promisifyUnary(call, request) {
261
350
  return new Promise((resolve, reject) => {
262
351
  call(request, new grpc2__namespace.Metadata(), (error, response) => {
@@ -268,7 +357,7 @@ function promisifyUnary(call, request) {
268
357
  });
269
358
  });
270
359
  }
271
- function buildCredentials(baseUrl, customCa, allowInsecure) {
360
+ function buildCredentials(baseUrl, customCa, allowInsecure, identity) {
272
361
  const isSecure = baseUrl.startsWith("https://") || baseUrl.startsWith("grpcs://");
273
362
  if (!isSecure) {
274
363
  if (!allowInsecure) {
@@ -281,8 +370,16 @@ function buildCredentials(baseUrl, customCa, allowInsecure) {
281
370
  );
282
371
  return grpc2__namespace.ChannelCredentials.createInsecure();
283
372
  }
373
+ const rootCerts = customCa ? Buffer.from(customCa, "utf8") : null;
374
+ if (identity) {
375
+ return grpc2__namespace.ChannelCredentials.createSsl(
376
+ rootCerts,
377
+ Buffer.from(identity.key.expose(), "utf8"),
378
+ Buffer.from(identity.cert, "utf8")
379
+ );
380
+ }
284
381
  if (customCa) {
285
- return grpc2__namespace.ChannelCredentials.createSsl(Buffer.from(customCa, "utf8"));
382
+ return grpc2__namespace.ChannelCredentials.createSsl(rootCerts);
286
383
  }
287
384
  return grpc2__namespace.ChannelCredentials.createSsl();
288
385
  }
@@ -326,12 +423,39 @@ function buildAuthorizationServiceClient(baseUrl, credentials, interceptors) {
326
423
  interceptors
327
424
  });
328
425
  }
426
+ function buildUserInfoServiceClient(baseUrl, credentials, interceptors) {
427
+ const reqCodec = jsonCodec();
428
+ const respCodec = jsonCodec();
429
+ const ServiceClientConstructor = grpc2__namespace.makeClientConstructor(
430
+ {
431
+ getUserInfo: {
432
+ path: "/axiam.v1.UserInfoService/GetUserInfo",
433
+ requestStream: false,
434
+ responseStream: false,
435
+ requestSerialize: reqCodec.serialize,
436
+ requestDeserialize: reqCodec.deserialize,
437
+ responseSerialize: respCodec.serialize,
438
+ responseDeserialize: respCodec.deserialize
439
+ }
440
+ },
441
+ "axiam.v1.UserInfoService"
442
+ );
443
+ return new ServiceClientConstructor(grpcTarget(baseUrl), credentials, {
444
+ interceptors
445
+ });
446
+ }
329
447
  var AuthzGrpcClient = class {
330
448
  #session;
331
449
  #inner;
332
450
  constructor(session, options, clientFactory = buildAuthorizationServiceClient) {
333
451
  this.#session = session;
334
- const credentials = buildCredentials(options.baseUrl, options.customCa, options.allowInsecure ?? false);
452
+ const identity = resolveClientIdentity(options);
453
+ const credentials = buildCredentials(
454
+ options.baseUrl,
455
+ options.customCa,
456
+ options.allowInsecure ?? false,
457
+ identity
458
+ );
335
459
  this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);
336
460
  }
337
461
  /** `CheckAccess` over gRPC (SC#2 Node half). UNAUTHENTICATED triggers exactly one shared-guard refresh + one retry (§9.3). */
@@ -357,7 +481,47 @@ var AuthzGrpcClient = class {
357
481
  this.#inner.close();
358
482
  }
359
483
  };
360
- var PEM_MARKER = "-----BEGIN CERTIFICATE-----";
484
+ var UserInfoGrpcClient = class {
485
+ #session;
486
+ #inner;
487
+ constructor(session, options, clientFactory = buildUserInfoServiceClient) {
488
+ this.#session = session;
489
+ const identity = resolveClientIdentity(options);
490
+ const credentials = buildCredentials(
491
+ options.baseUrl,
492
+ options.customCa,
493
+ options.allowInsecure ?? false,
494
+ identity
495
+ );
496
+ this.#inner = clientFactory(options.baseUrl, credentials, [authInterceptor(session)]);
497
+ }
498
+ /**
499
+ * `GetUserInfo` over gRPC (CONTRACT.md §1.1). Returns the authenticated
500
+ * caller's identity claims; the request is empty (identity comes from the
501
+ * bearer token in the interceptor-injected metadata).
502
+ *
503
+ * Pre-flight (§1.1.3): with no cached access token this raises `AuthError`
504
+ * client-side, WITHOUT a wire call — the same synchronous cached-token view
505
+ * the auth interceptor reads. A gRPC `UNAUTHENTICATED` response otherwise
506
+ * drives exactly one shared-guard refresh + one retry (§9.3), identical to
507
+ * {@link AuthzGrpcClient.checkAccess}.
508
+ */
509
+ async getUserInfo() {
510
+ if (this.#session.tokenManager.cachedAccessToken() === null) {
511
+ throw new AuthError("getUserInfo requires a prior successful login() (no access token present)");
512
+ }
513
+ const response = await callWithRefresh(
514
+ this.#session,
515
+ () => promisifyUnary(this.#inner.getUserInfo.bind(this.#inner), {})
516
+ );
517
+ return fromWireUserInfo(response);
518
+ }
519
+ /** Close the underlying gRPC channel. */
520
+ close() {
521
+ this.#inner.close();
522
+ }
523
+ };
524
+ var PEM_MARKER = CERT_PEM_MARKER;
361
525
  var SharedSession = class {
362
526
  /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */
363
527
  axios;
@@ -365,6 +529,28 @@ var SharedSession = class {
365
529
  baseUrl;
366
530
  /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
367
531
  tenantHeaderValue;
532
+ /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */
533
+ tenantId;
534
+ /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */
535
+ tenantSlug;
536
+ /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */
537
+ orgId;
538
+ /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */
539
+ orgSlug;
540
+ /**
541
+ * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`
542
+ * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config
543
+ * when the UUID was supplied, then updated from the access-token `tenant_id`
544
+ * claim after each successful login/refresh (Node persona only — the browser
545
+ * cannot read the httpOnly access-token cookie).
546
+ */
547
+ resolvedTenantId;
548
+ /**
549
+ * Resolved organization UUID used to build the `refresh` body. Seeded from
550
+ * `orgId` config, then updated from the access-token `org_id` claim after a
551
+ * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.
552
+ */
553
+ resolvedOrgId;
368
554
  /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
369
555
  csrfToken;
370
556
  /** Set true once a successful login/verifyMfa has completed. */
@@ -384,8 +570,55 @@ var SharedSession = class {
384
570
  this.axios = axiosInstance;
385
571
  this.baseUrl = options.baseUrl;
386
572
  this.tenantHeaderValue = tenantHeaderValue;
573
+ this.tenantId = options.tenantId;
574
+ this.tenantSlug = options.tenantSlug;
575
+ this.orgId = options.orgId;
576
+ this.orgSlug = options.orgSlug;
577
+ this.resolvedTenantId = options.tenantId;
578
+ this.resolvedOrgId = options.orgId;
387
579
  this.refreshGuard = createRefreshGuard();
388
580
  }
581
+ /**
582
+ * Build the `POST /api/v1/auth/refresh` request body (§1). The server's
583
+ * `RefreshRequest` requires both `tenant_id` and `org_id` as UUIDs, so this
584
+ * emits the resolved UUIDs — from the access-token claims after login, or
585
+ * from UUID-form construction options as a fallback. Fields that could not
586
+ * be resolved are omitted (the server then answers with a clear 400), rather
587
+ * than sending a slug where a UUID is required.
588
+ */
589
+ buildRefreshBody() {
590
+ const body = {};
591
+ if (this.resolvedTenantId) {
592
+ body.tenant_id = this.resolvedTenantId;
593
+ }
594
+ if (this.resolvedOrgId) {
595
+ body.org_id = this.resolvedOrgId;
596
+ }
597
+ return body;
598
+ }
599
+ /**
600
+ * Build the `POST /api/v1/auth/login` request body (§1/§5). Carries the
601
+ * configured tenant and organization identifiers (UUID or slug form) in
602
+ * addition to the credentials — the server resolves the workspace from the
603
+ * body, not the `X-Tenant-ID` header, and rejects a login that omits org
604
+ * context. Undefined identifiers are omitted.
605
+ */
606
+ buildLoginBody(email, password) {
607
+ const body = { username_or_email: email, password };
608
+ if (this.tenantId) {
609
+ body.tenant_id = this.tenantId;
610
+ }
611
+ if (this.tenantSlug) {
612
+ body.tenant_slug = this.tenantSlug;
613
+ }
614
+ if (this.orgId) {
615
+ body.org_id = this.orgId;
616
+ }
617
+ if (this.orgSlug) {
618
+ body.org_slug = this.orgSlug;
619
+ }
620
+ return body;
621
+ }
389
622
  /**
390
623
  * Host-isolation guard (3A, defense in depth): returns `true` when `url`
391
624
  * targets a host other than this session's base origin — an absolute
@@ -419,11 +652,12 @@ function resolveTenantHeaderValue(options) {
419
652
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
420
653
  );
421
654
  }
422
- function maybeBuildHttpsAgent(customCa) {
655
+ function maybeBuildHttpsAgent(customCa, identity) {
423
656
  if (!customCa) {
424
- return void 0;
425
- }
426
- if (!customCa.includes(PEM_MARKER)) {
657
+ if (!identity) {
658
+ return void 0;
659
+ }
660
+ } else if (!customCa.includes(PEM_MARKER)) {
427
661
  throw new Error(
428
662
  'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
429
663
  );
@@ -432,7 +666,11 @@ function maybeBuildHttpsAgent(customCa) {
432
666
  return void 0;
433
667
  }
434
668
  const https = __require("https");
435
- return new https.Agent({ ca: customCa });
669
+ return new https.Agent({
670
+ ...customCa ? { ca: customCa } : {},
671
+ // rejectUnauthorized is intentionally left at its secure default (true).
672
+ ...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
673
+ });
436
674
  }
437
675
  function createSession(options) {
438
676
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -441,7 +679,8 @@ function createSession(options) {
441
679
  'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
442
680
  );
443
681
  }
444
- const httpsAgent = maybeBuildHttpsAgent(options.customCa);
682
+ const clientIdentity = resolveClientIdentity(options);
683
+ const httpsAgent = maybeBuildHttpsAgent(options.customCa, clientIdentity);
445
684
  const axiosInstance = axios__default.default.create({
446
685
  baseURL: options.baseUrl,
447
686
  withCredentials: true,
@@ -461,7 +700,14 @@ function createSession(options) {
461
700
  }
462
701
 
463
702
  // src/rest/interceptors.ts
464
- var SKIP_REFRESH = ["/api/v1/auth/refresh", "/api/v1/auth/login", "/api/v1/auth/logout"];
703
+ var SKIP_REFRESH = [
704
+ "/api/v1/auth/refresh",
705
+ "/api/v1/auth/login",
706
+ "/api/v1/auth/logout",
707
+ "/oauth2/token",
708
+ "/oauth2/introspect",
709
+ "/oauth2/revoke"
710
+ ];
465
711
  function installCsrfInterceptor(axiosInstance, session) {
466
712
  axiosInstance.interceptors.request.use((config) => {
467
713
  if (session.isForeignHost(config.url)) {
@@ -492,7 +738,8 @@ function installRefreshInterceptor(axiosInstance, session) {
492
738
  originalRequest._retry = true;
493
739
  try {
494
740
  await session.refreshGuard(async () => {
495
- await session.axios.post("/api/v1/auth/refresh", {});
741
+ await session.axios.post("/api/v1/auth/refresh", session.buildRefreshBody());
742
+ await session.onAuthenticated?.();
496
743
  });
497
744
  return axiosInstance(originalRequest);
498
745
  } catch (refreshError) {
@@ -506,7 +753,13 @@ function installRefreshInterceptor(axiosInstance, session) {
506
753
  }
507
754
  }
508
755
  if (status === 401 && isSkipRefresh) {
509
- return Promise.reject(mapHttpStatusToError(401, "authentication failed"));
756
+ return Promise.reject(
757
+ mapHttpStatusToError(401, "authentication failed", {
758
+ url,
759
+ body: error.response.data,
760
+ cause: error
761
+ })
762
+ );
510
763
  }
511
764
  return Promise.reject(error);
512
765
  }
@@ -544,7 +797,7 @@ function extractErrorMessage(err) {
544
797
  return "request failed";
545
798
  }
546
799
  async function login(client, email, password) {
547
- const body = { username_or_email: email, password };
800
+ const body = client.session.buildLoginBody(email, password);
548
801
  try {
549
802
  const response = await client.session.axios.post(
550
803
  LOGIN_PATH,
@@ -585,7 +838,8 @@ async function verifyMfa(client, mfaToken, code) {
585
838
  }
586
839
  async function refresh(client) {
587
840
  try {
588
- await client.session.axios.post(REFRESH_PATH, {});
841
+ await client.session.axios.post(REFRESH_PATH, client.session.buildRefreshBody());
842
+ await client.session.onAuthenticated?.();
589
843
  } catch (err) {
590
844
  const status = extractAxiosStatus(err);
591
845
  if (status !== void 0) {
@@ -803,22 +1057,124 @@ var TokenManager = class {
803
1057
  setTenantId(tenantId) {
804
1058
  this.#tenantId = tenantId;
805
1059
  }
1060
+ /**
1061
+ * Best-effort decode of the `tenant_id`/`org_id` claims out of the cached
1062
+ * access token, WITHOUT signature verification. Used only to populate the
1063
+ * `refresh` request body (`RefreshRequest` requires both UUIDs) — never as a
1064
+ * trust decision: the actual credential is the httpOnly `axiam_access` cookie
1065
+ * the server verifies, and the server re-derives the authoritative `org_id`
1066
+ * from the tenant on refresh (see crates/axiam-api-rest handlers/auth.rs),
1067
+ * so echoing these values back carries no security weight. A malformed or
1068
+ * absent token yields an empty result (the caller then keeps whatever UUIDs
1069
+ * were resolved from construction options).
1070
+ */
1071
+ claimsFromCachedToken() {
1072
+ const token = this.#cachedAccess?.expose();
1073
+ if (!token) {
1074
+ return {};
1075
+ }
1076
+ const claims = decodeJwtPayload(token);
1077
+ return {
1078
+ tenantId: typeof claims.tenant_id === "string" ? claims.tenant_id : void 0,
1079
+ orgId: typeof claims.org_id === "string" ? claims.org_id : void 0
1080
+ };
1081
+ }
806
1082
  /** Clear all cached token state (used by logout()). */
807
1083
  clear() {
808
1084
  this.#cachedAccess = null;
809
1085
  }
810
1086
  };
1087
+ function decodeJwtPayload(token) {
1088
+ try {
1089
+ const segments = token.split(".");
1090
+ if (segments.length !== 3) {
1091
+ return {};
1092
+ }
1093
+ const json = Buffer.from(segments[1], "base64url").toString("utf8");
1094
+ const parsed = JSON.parse(json);
1095
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
1096
+ } catch {
1097
+ return {};
1098
+ }
1099
+ }
1100
+ var MAX_CLOCK_SKEW_SEC = 60;
1101
+ function idTokenAuthError(reason, message) {
1102
+ return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);
1103
+ }
1104
+ function resolveClockSkewSec(clockSkewSec) {
1105
+ if (clockSkewSec === void 0) {
1106
+ return MAX_CLOCK_SKEW_SEC;
1107
+ }
1108
+ return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
1109
+ }
1110
+ function constantTimeEquals(a, b) {
1111
+ const left = Buffer.from(a, "utf8");
1112
+ const right = Buffer.from(b, "utf8");
1113
+ if (left.length !== right.length) {
1114
+ return false;
1115
+ }
1116
+ return crypto.timingSafeEqual(left, right);
1117
+ }
1118
+ var ID_TOKEN_ALG = "EdDSA";
1119
+ function assertIdTokenAlg(alg) {
1120
+ if (alg !== ID_TOKEN_ALG) {
1121
+ throw idTokenAuthError(
1122
+ "invalid_alg",
1123
+ `expected alg "${ID_TOKEN_ALG}", got ${typeof alg === "string" ? `"${alg}"` : "no alg header"}`
1124
+ );
1125
+ }
1126
+ }
1127
+ function checkIdTokenClaims(claims, expectations, nowSec = Math.floor(Date.now() / 1e3)) {
1128
+ const skew = resolveClockSkewSec(expectations.clockSkewSec);
1129
+ if (claims.iss !== expectations.issuer) {
1130
+ throw idTokenAuthError("invalid_issuer", "iss does not equal the discovery document issuer");
1131
+ }
1132
+ const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
1133
+ if (!audiences.includes(expectations.clientId)) {
1134
+ throw idTokenAuthError("invalid_audience", "aud does not contain this client_id");
1135
+ }
1136
+ if (audiences.length > 1 && claims.azp !== expectations.clientId) {
1137
+ throw idTokenAuthError(
1138
+ "invalid_audience",
1139
+ "aud holds multiple audiences and azp is absent or does not equal this client_id"
1140
+ );
1141
+ }
1142
+ if (typeof claims.exp !== "number") {
1143
+ throw idTokenAuthError("token_expired", "exp claim is missing or not a number");
1144
+ }
1145
+ if (claims.exp + skew <= nowSec) {
1146
+ throw idTokenAuthError("token_expired", "exp is in the past");
1147
+ }
1148
+ if (typeof claims.iat !== "number") {
1149
+ throw idTokenAuthError("token_expired", "iat claim is missing or not a number");
1150
+ }
1151
+ if (claims.iat - skew > nowSec) {
1152
+ throw idTokenAuthError("token_expired", "iat is in the future");
1153
+ }
1154
+ if (typeof claims.nbf === "number" && claims.nbf - skew > nowSec) {
1155
+ throw idTokenAuthError("token_expired", "nbf is in the future");
1156
+ }
1157
+ if (expectations.nonce !== void 0) {
1158
+ if (typeof claims.nonce !== "string" || !constantTimeEquals(claims.nonce, expectations.nonce)) {
1159
+ throw idTokenAuthError("nonce_mismatch", "nonce claim is absent or does not match the request nonce");
1160
+ }
1161
+ }
1162
+ return claims;
1163
+ }
811
1164
 
812
1165
  // src/node/jwks.ts
813
1166
  var JWKS_PATH = "/oauth2/jwks";
814
1167
  var COOLDOWN_DURATION_MS = 6e4;
815
1168
  var TIMEOUT_DURATION_MS = 5e3;
816
1169
  function createVerifier(baseUrl) {
1170
+ return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
1171
+ }
1172
+ function createJwksVerifier(jwksUri) {
817
1173
  let jwksPromise = null;
818
1174
  async function getJwks() {
819
1175
  if (!jwksPromise) {
820
1176
  jwksPromise = import('jose').then(
821
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(`${baseUrl}${JWKS_PATH}`), {
1177
+ ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
822
1178
  cooldownDuration: COOLDOWN_DURATION_MS,
823
1179
  timeoutDuration: TIMEOUT_DURATION_MS
824
1180
  })
@@ -832,13 +1188,54 @@ function createVerifier(baseUrl) {
832
1188
  const jwks = await getJwks();
833
1189
  const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
834
1190
  return payload;
1191
+ },
1192
+ async verifyIdToken(token, expectations) {
1193
+ const { decodeProtectedHeader, jwtVerify } = await import('jose');
1194
+ let header;
1195
+ try {
1196
+ header = decodeProtectedHeader(token);
1197
+ } catch {
1198
+ throw idTokenAuthError("invalid_alg", "token is not a well-formed JWS");
1199
+ }
1200
+ assertIdTokenAlg(header.alg);
1201
+ if (!header.kid) {
1202
+ throw idTokenAuthError("unknown_kid", "token carries no kid header");
1203
+ }
1204
+ const jwks = await getJwks();
1205
+ const skew = resolveClockSkewSec(expectations.clockSkewSec);
1206
+ let claims;
1207
+ try {
1208
+ const { payload } = await jwtVerify(token, jwks, {
1209
+ algorithms: [ID_TOKEN_ALG],
1210
+ clockTolerance: skew
1211
+ });
1212
+ claims = payload;
1213
+ } catch (err) {
1214
+ throw mapJoseVerifyError(err);
1215
+ }
1216
+ return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });
835
1217
  }
836
1218
  };
837
1219
  }
1220
+ function mapJoseVerifyError(err) {
1221
+ const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
1222
+ switch (code) {
1223
+ case "ERR_JWKS_NO_MATCHING_KEY":
1224
+ return idTokenAuthError("unknown_kid", "no JWKS key matches the token kid");
1225
+ case "ERR_JWT_EXPIRED":
1226
+ return idTokenAuthError("token_expired", "exp is in the past");
1227
+ case "ERR_JWT_CLAIM_VALIDATION_FAILED":
1228
+ return idTokenAuthError("token_expired", "a time-based claim (nbf/iat) is not yet valid");
1229
+ default:
1230
+ return idTokenAuthError("invalid_signature", "signature verification failed");
1231
+ }
1232
+ }
838
1233
 
839
1234
  // src/node/session.ts
840
1235
  var NodeSession = class extends SharedSession {
1236
+ /** Manages the access/refresh token pair backing this session. */
841
1237
  tokenManager;
1238
+ /** Local JWKS verifier for validating access tokens without a server round-trip. */
842
1239
  jwksVerifier;
843
1240
  #jar;
844
1241
  constructor(options, base, tokenManager, jwksVerifier, jar) {
@@ -857,8 +1254,9 @@ var NodeSession = class extends SharedSession {
857
1254
  * remaining fully independent from any other session's guard.
858
1255
  */
859
1256
  doRefresh = async () => {
860
- await this.axios.post("/api/v1/auth/refresh", {});
1257
+ await this.axios.post("/api/v1/auth/refresh", this.buildRefreshBody());
861
1258
  await this.tokenManager.syncFromJar();
1259
+ this.#resolveIdentifiersFromToken();
862
1260
  await this.#syncCsrfFromJar();
863
1261
  };
864
1262
  /**
@@ -870,8 +1268,25 @@ var NodeSession = class extends SharedSession {
870
1268
  */
871
1269
  onAuthenticated = async () => {
872
1270
  await this.tokenManager.syncFromJar();
1271
+ this.#resolveIdentifiersFromToken();
873
1272
  await this.#syncCsrfFromJar();
874
1273
  };
1274
+ /**
1275
+ * Populate `resolvedTenantId`/`resolvedOrgId` from the cached access token's
1276
+ * claims when present, leaving any UUID resolved from construction options in
1277
+ * place otherwise. Best-effort and unverified (see
1278
+ * TokenManager.claimsFromCachedToken) — used purely to build the refresh body.
1279
+ */
1280
+ #resolveIdentifiersFromToken() {
1281
+ const { tenantId, orgId } = this.tokenManager.claimsFromCachedToken();
1282
+ if (tenantId) {
1283
+ this.resolvedTenantId = tenantId;
1284
+ this.tokenManager.setTenantId(tenantId);
1285
+ }
1286
+ if (orgId) {
1287
+ this.resolvedOrgId = orgId;
1288
+ }
1289
+ }
875
1290
  async #syncCsrfFromJar() {
876
1291
  this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);
877
1292
  }
@@ -895,8 +1310,10 @@ exports.JWKS_PATH = JWKS_PATH;
895
1310
  exports.NodeSession = NodeSession;
896
1311
  exports.REFRESH_COOKIE = REFRESH_COOKIE;
897
1312
  exports.TokenManager = TokenManager;
1313
+ exports.UserInfoGrpcClient = UserInfoGrpcClient;
898
1314
  exports.authInterceptor = authInterceptor;
899
1315
  exports.buildAuthorizationServiceClient = buildAuthorizationServiceClient;
1316
+ exports.buildUserInfoServiceClient = buildUserInfoServiceClient;
900
1317
  exports.callWithRefresh = callWithRefresh;
901
1318
  exports.createJar = createJar;
902
1319
  exports.createNodeClient = createNodeClient;