axiam-sdk 1.3.0 → 1.4.0

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 (58) hide show
  1. package/README.md +130 -14
  2. package/dist/amqp/index.d.cts +384 -17
  3. package/dist/amqp/index.d.ts +384 -17
  4. package/dist/amqp/index.js +639 -66
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +631 -67
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
  9. package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
  10. package/dist/browser/index.d.cts +1 -1
  11. package/dist/browser/index.d.ts +1 -1
  12. package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
  13. package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
  14. package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
  15. package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
  16. package/dist/grpc/index.d.cts +5 -5
  17. package/dist/grpc/index.d.ts +5 -5
  18. package/dist/grpc/index.js +249 -18
  19. package/dist/grpc/index.js.map +1 -1
  20. package/dist/grpc/index.mjs +249 -18
  21. package/dist/grpc/index.mjs.map +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +29 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +29 -3
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
  29. package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
  30. package/dist/middleware/index.d.cts +220 -43
  31. package/dist/middleware/index.d.ts +220 -43
  32. package/dist/middleware/index.js +587 -149
  33. package/dist/middleware/index.js.map +1 -1
  34. package/dist/middleware/index.mjs +579 -150
  35. package/dist/middleware/index.mjs.map +1 -1
  36. package/dist/nestjs/index.d.cts +18 -4
  37. package/dist/nestjs/index.d.ts +18 -4
  38. package/dist/nestjs/index.js +20 -1
  39. package/dist/nestjs/index.js.map +1 -1
  40. package/dist/nestjs/index.mjs +19 -2
  41. package/dist/nestjs/index.mjs.map +1 -1
  42. package/dist/node/index.d.cts +5 -5
  43. package/dist/node/index.d.ts +5 -5
  44. package/dist/node/index.js +351 -66
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/index.mjs +348 -67
  47. package/dist/node/index.mjs.map +1 -1
  48. package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
  49. package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
  50. package/dist/rest/index.d.cts +3 -3
  51. package/dist/rest/index.d.ts +3 -3
  52. package/dist/rest/index.js +29 -3
  53. package/dist/rest/index.js.map +1 -1
  54. package/dist/rest/index.mjs +29 -3
  55. package/dist/rest/index.mjs.map +1 -1
  56. package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
  57. package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
  58. package/package.json +10 -10
@@ -1017,6 +1017,7 @@ var SharedSession = class {
1017
1017
  this.expectedIssuer = options.expectedIssuer;
1018
1018
  this.expectedAudience = options.expectedAudience;
1019
1019
  this.presentsClientCertificate = options.clientCert !== void 0 && options.clientKey !== void 0;
1020
+ registerTlsOptions(this, options);
1020
1021
  this.resolvedTenantId = options.tenantId;
1021
1022
  this.resolvedOrgId = options.orgId;
1022
1023
  this.refreshGuard = createRefreshGuard();
@@ -1068,7 +1069,7 @@ var SharedSession = class {
1068
1069
  }
1069
1070
  /**
1070
1071
  * Host-isolation guard (3A, defense in depth): returns `true` when `url`
1071
- * targets a host other than this session's base origin — an absolute
1072
+ * targets an origin (scheme, host and port) other than this session's base origin — an absolute
1072
1073
  * third-party URL, or a redirect that axios/the browser resolved off-origin.
1073
1074
  * The tenant identifier and CSRF token must never be attached to such a
1074
1075
  * request. A relative/host-less `url` (the normal case, merged against
@@ -1082,7 +1083,7 @@ var SharedSession = class {
1082
1083
  }
1083
1084
  try {
1084
1085
  const target = new URL(url, this.baseUrl);
1085
- return target.host !== new URL(this.baseUrl).host;
1086
+ return target.origin !== new URL(this.baseUrl).origin;
1086
1087
  } catch {
1087
1088
  return true;
1088
1089
  }
@@ -1144,6 +1145,19 @@ function resolveTenantHeaderValue(options) {
1144
1145
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
1145
1146
  );
1146
1147
  }
1148
+ function agentTlsOptions(tls) {
1149
+ if (tls === void 0) return {};
1150
+ if (tls.ca === void 0) {
1151
+ return { ...tls.cert !== void 0 ? { cert: tls.cert } : {}, ...tls.key !== void 0 ? { key: tls.key } : {} };
1152
+ }
1153
+ const tlsMod = loadNodeBuiltin("node:tls");
1154
+ const secureContext = tlsMod.createSecureContext({
1155
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
1156
+ ...tls.key !== void 0 ? { key: tls.key } : {}
1157
+ });
1158
+ secureContext.context.addCACert(tls.ca);
1159
+ return { secureContext };
1160
+ }
1147
1161
  function loadNodeBuiltin(id) {
1148
1162
  const getBuiltinModule = process.getBuiltinModule;
1149
1163
  if (typeof getBuiltinModule === "function") {
@@ -1160,6 +1174,15 @@ function loadNodeBuiltin(id) {
1160
1174
  function loadNodeHttps() {
1161
1175
  return loadNodeBuiltin("node:https");
1162
1176
  }
1177
+ var sessionTlsOptions = /* @__PURE__ */ new WeakMap();
1178
+ function registerTlsOptions(session, options) {
1179
+ if (options.customCa === void 0 && options.clientCert === void 0) return;
1180
+ try {
1181
+ const tls = resolveNodeTlsOptions(options);
1182
+ if (tls !== void 0) sessionTlsOptions.set(session, tls);
1183
+ } catch {
1184
+ }
1185
+ }
1163
1186
  function tlsOptionsFrom(customCa, identity) {
1164
1187
  if (!customCa) {
1165
1188
  if (!identity) {
@@ -1183,7 +1206,7 @@ function buildPlainNodeAgents(tls) {
1183
1206
  const https = loadNodeHttps();
1184
1207
  return {
1185
1208
  httpAgent: new http.Agent(),
1186
- httpsAgent: new https.Agent(tls ?? {})
1209
+ httpsAgent: new https.Agent(agentTlsOptions(tls))
1187
1210
  };
1188
1211
  }
1189
1212
  function maybeBuildHttpsAgent(customCa, identity) {
@@ -1195,7 +1218,7 @@ function maybeBuildHttpsAgent(customCa, identity) {
1195
1218
  return void 0;
1196
1219
  }
1197
1220
  const https = loadNodeHttps();
1198
- return new https.Agent(tls);
1221
+ return new https.Agent(agentTlsOptions(tls));
1199
1222
  }
1200
1223
  function createSession(options) {
1201
1224
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -4251,7 +4274,7 @@ function normalizeSearch(term) {
4251
4274
  const trimmed = term?.trim();
4252
4275
  return trimmed ? trimmed : void 0;
4253
4276
  }
4254
- async function collectPages(start, fetch) {
4277
+ async function collectPages(start, fetch2) {
4255
4278
  let request = {
4256
4279
  offset: start.offset ?? 0,
4257
4280
  limit: start.limit,
@@ -4259,7 +4282,7 @@ async function collectPages(start, fetch) {
4259
4282
  };
4260
4283
  const out = [];
4261
4284
  for (; ; ) {
4262
- const page = await fetch(request);
4285
+ const page = await fetch2(request);
4263
4286
  out.push(...page.items);
4264
4287
  const next = page.offset + page.items.length;
4265
4288
  if (page.items.length === 0 || next >= page.total) return out;
@@ -8649,7 +8672,7 @@ function createJar() {
8649
8672
  function wrapAxios(instance, jar, tls) {
8650
8673
  const cookies = { jar };
8651
8674
  instance.defaults.httpAgent = new http.HttpCookieAgent({ cookies });
8652
- instance.defaults.httpsAgent = new http.HttpsCookieAgent({ cookies, ...tls ?? {} });
8675
+ instance.defaults.httpsAgent = new http.HttpsCookieAgent({ cookies, ...agentTlsOptions(tls) });
8653
8676
  return instance;
8654
8677
  }
8655
8678
  async function extractCookieValue(jar, url, name) {
@@ -8759,6 +8782,9 @@ function resolveClockSkewSec(clockSkewSec) {
8759
8782
  if (clockSkewSec === void 0) {
8760
8783
  return MAX_CLOCK_SKEW_SEC;
8761
8784
  }
8785
+ if (typeof clockSkewSec !== "number" || !Number.isFinite(clockSkewSec)) {
8786
+ throw new TypeError("clockSkewSec must be a finite number of seconds");
8787
+ }
8762
8788
  return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
8763
8789
  }
8764
8790
  function constantTimeEquals(a, b) {
@@ -8855,26 +8881,196 @@ function constantTimeEqual(a, b) {
8855
8881
  var JWKS_PATH = "/oauth2/jwks";
8856
8882
  var COOLDOWN_DURATION_MS = 6e4;
8857
8883
  var TIMEOUT_DURATION_MS = 5e3;
8884
+ var JWKS_MAX_TTL_MS = 3e5;
8885
+ var JWKS_MAX_STALE_MS = 3e5;
8886
+ var JWKS_MAX_BODY_BYTES = 50 * 1024;
8887
+ async function readCappedJson(res, maxBytes) {
8888
+ const declared = res.headers.get("content-length");
8889
+ if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
8890
+ await res.body?.cancel().catch(() => void 0);
8891
+ throw new Error("JWKS response too large");
8892
+ }
8893
+ const reader = res.body?.getReader();
8894
+ if (reader === void 0) throw new Error("JWKS response has no body");
8895
+ const chunks = [];
8896
+ let total = 0;
8897
+ for (; ; ) {
8898
+ const { done, value } = await reader.read();
8899
+ if (done) break;
8900
+ total += value.byteLength;
8901
+ if (total > maxBytes) {
8902
+ await reader.cancel().catch(() => void 0);
8903
+ throw new Error("JWKS response too large");
8904
+ }
8905
+ chunks.push(value);
8906
+ }
8907
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
8908
+ }
8909
+ function ttlFromResponse(res) {
8910
+ const m = /(?:^|[\s,])max-age=(\d+)/i.exec(res.headers.get("cache-control") ?? "");
8911
+ if (m === null) return JWKS_MAX_TTL_MS;
8912
+ const ms = Number(m[1]) * 1e3;
8913
+ return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;
8914
+ }
8915
+ async function fetchWithTls(url, init, tls) {
8916
+ const https = (await import('https')).default;
8917
+ const { Readable } = await import('stream');
8918
+ const tlsMod = await import('tls');
8919
+ let secureContext;
8920
+ if (tls.ca !== void 0) {
8921
+ secureContext = tlsMod.createSecureContext({
8922
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8923
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8924
+ });
8925
+ secureContext.context.addCACert(tls.ca);
8926
+ }
8927
+ return new Promise((resolve, reject) => {
8928
+ let settled = false;
8929
+ const settle = (fn) => {
8930
+ if (settled) return;
8931
+ settled = true;
8932
+ fn();
8933
+ };
8934
+ const agent = new https.Agent(
8935
+ secureContext !== void 0 ? { secureContext } : {
8936
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8937
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8938
+ }
8939
+ );
8940
+ const fail = (message = "unexpected JWKS status") => {
8941
+ agent.destroy();
8942
+ settle(() => reject(new Error(message)));
8943
+ };
8944
+ const req = https.request(
8945
+ url,
8946
+ { method: "GET", headers: init.headers, signal: init.signal, agent },
8947
+ (res) => {
8948
+ try {
8949
+ const status = res.statusCode ?? 0;
8950
+ if (status !== 200 && status !== 304) {
8951
+ res.destroy();
8952
+ fail();
8953
+ return;
8954
+ }
8955
+ const headers = new Headers();
8956
+ for (const [name, value] of Object.entries(res.headers)) {
8957
+ if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
8958
+ }
8959
+ if (status === 304) res.resume();
8960
+ const body = status === 304 ? null : Readable.toWeb(res);
8961
+ const response = new Response(body, { status, headers });
8962
+ res.on("close", () => agent.destroy());
8963
+ settle(() => resolve(response));
8964
+ } catch {
8965
+ res.destroy();
8966
+ fail();
8967
+ }
8968
+ }
8969
+ );
8970
+ req.on("error", (err) => {
8971
+ agent.destroy();
8972
+ settle(() => reject(err));
8973
+ });
8974
+ req.on("close", () => {
8975
+ if (!settled) fail("JWKS request closed before a response");
8976
+ });
8977
+ req.end();
8978
+ });
8979
+ }
8980
+ var JwksCache = class {
8981
+ constructor(jwksUri, jose, tls) {
8982
+ this.jwksUri = jwksUri;
8983
+ this.jose = jose;
8984
+ this.#tls = tls;
8985
+ }
8986
+ jwksUri;
8987
+ jose;
8988
+ #resolver;
8989
+ #etag;
8990
+ #anchorMs = 0;
8991
+ #ttlMs = JWKS_MAX_TTL_MS;
8992
+ #lastAttemptMs;
8993
+ #inflight;
8994
+ /** Held privately: it may carry the client key, and must not be an enumerable property. */
8995
+ #tls;
8996
+ /** The key resolver handed to `jwtVerify`. */
8997
+ getKey = async (...args) => {
8998
+ const usable = () => this.#resolver !== void 0 && Date.now() >= this.#anchorMs && Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS ? this.#resolver : void 0;
8999
+ const nowMs = Date.now();
9000
+ if (this.#resolver === void 0 || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {
9001
+ const refresh2 = this.#refreshIfAllowed();
9002
+ if (usable() === void 0) await refresh2;
9003
+ }
9004
+ const held = usable();
9005
+ if (held === void 0) {
9006
+ throw new this.jose.errors.JOSEError("the JSON Web Key Set is unavailable");
9007
+ }
9008
+ try {
9009
+ return await held(...args);
9010
+ } catch (err) {
9011
+ if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;
9012
+ await this.#refreshIfAllowed();
9013
+ const refreshed = usable();
9014
+ if (refreshed === void 0) throw err;
9015
+ return refreshed(...args);
9016
+ }
9017
+ };
9018
+ async #refreshIfAllowed() {
9019
+ if (this.#inflight !== void 0) return this.#inflight;
9020
+ const now = Date.now();
9021
+ const sinceLast = this.#lastAttemptMs === void 0 ? Infinity : now - this.#lastAttemptMs;
9022
+ if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return;
9023
+ this.#lastAttemptMs = now;
9024
+ this.#inflight = this.#fetch().catch(() => void 0).finally(() => {
9025
+ this.#inflight = void 0;
9026
+ });
9027
+ return this.#inflight;
9028
+ }
9029
+ async #fetch() {
9030
+ const conditional = this.#resolver !== void 0 && this.#etag !== void 0;
9031
+ const headers = { accept: "application/json", ...conditional ? { "if-none-match": this.#etag } : {} };
9032
+ const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);
9033
+ const res = this.#tls !== void 0 && new URL(this.jwksUri).protocol === "https:" ? await fetchWithTls(this.jwksUri, { headers, signal }, this.#tls) : await fetch(this.jwksUri, { redirect: "manual", signal, headers });
9034
+ if (res.status === 304 && conditional) {
9035
+ await res.body?.cancel().catch(() => void 0);
9036
+ this.#anchorMs = Date.now();
9037
+ this.#ttlMs = ttlFromResponse(res);
9038
+ return;
9039
+ }
9040
+ if (res.status !== 200) {
9041
+ await res.body?.cancel().catch(() => void 0);
9042
+ throw new Error("unexpected JWKS status");
9043
+ }
9044
+ const doc = await readCappedJson(res, JWKS_MAX_BODY_BYTES);
9045
+ const isJwk = (k) => typeof k === "object" && k !== null && !Array.isArray(k) && typeof k.kty === "string";
9046
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {
9047
+ throw new Error("not a JWKS document with a key");
9048
+ }
9049
+ const usable = doc.keys.filter(isJwk);
9050
+ const resolver = this.jose.createLocalJWKSet({ keys: usable });
9051
+ this.#resolver = resolver;
9052
+ const etag = res.headers.get("etag");
9053
+ this.#etag = etag !== null && Buffer.byteLength(etag) <= 256 && !/[\x00-\x1f\x7f]/.test(etag) ? etag : void 0;
9054
+ this.#anchorMs = Date.now();
9055
+ this.#ttlMs = ttlFromResponse(res);
9056
+ }
9057
+ };
8858
9058
  var CLOCK_SKEW_LEEWAY_SEC = 60;
8859
- function createVerifier(baseUrl) {
8860
- return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
9059
+ function createVerifier(baseUrl, tlsOptions) {
9060
+ return createJwksVerifier(`${baseUrl}${JWKS_PATH}`, tlsOptions);
8861
9061
  }
8862
- function createJwksVerifier(jwksUri) {
9062
+ function createJwksVerifier(jwksUri, tlsOptions) {
8863
9063
  let jwksPromise = null;
8864
9064
  async function getJwks() {
8865
9065
  if (!jwksPromise) {
8866
- jwksPromise = import('jose').then(
8867
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
8868
- cooldownDuration: COOLDOWN_DURATION_MS,
8869
- timeoutDuration: TIMEOUT_DURATION_MS
8870
- })
8871
- );
9066
+ jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));
8872
9067
  }
8873
- return jwksPromise;
9068
+ return (await jwksPromise).getKey;
8874
9069
  }
8875
9070
  return {
8876
9071
  async verifyAccessToken(token, expectations, proofs = {}) {
8877
9072
  const { jwtVerify } = await import('jose');
9073
+ assertAccessTokenHeader(token);
8878
9074
  const jwks = await getJwks();
8879
9075
  const { payload } = await jwtVerify(token, jwks, {
8880
9076
  algorithms: ["EdDSA"],
@@ -8884,6 +9080,7 @@ function createJwksVerifier(jwksUri) {
8884
9080
  ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
8885
9081
  });
8886
9082
  assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
9083
+ assertNoPurposeClaim(payload);
8887
9084
  const claims = payload;
8888
9085
  verifyTokenBinding(claims, proofs);
8889
9086
  return claims;
@@ -8922,6 +9119,40 @@ function createJwksVerifier(jwksUri) {
8922
9119
  }
8923
9120
  };
8924
9121
  }
9122
+ function assertAccessTokenHeader(token) {
9123
+ let header;
9124
+ try {
9125
+ const segments = token.split(".");
9126
+ if (segments.length !== 3) {
9127
+ throw new Error("not three segments");
9128
+ }
9129
+ const parsed = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
9130
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
9131
+ throw new Error("header is not an object");
9132
+ }
9133
+ header = parsed;
9134
+ } catch {
9135
+ throw new AuthError("access token is not a well-formed JWS");
9136
+ }
9137
+ if (typeof header.kid !== "string" || header.kid.length === 0) {
9138
+ throw new AuthError("access token carries no kid header (CONTRACT.md \xA710.1 rule 12)");
9139
+ }
9140
+ if (header.typ !== void 0 && !isAccessTokenTyp(header.typ)) {
9141
+ throw new AuthError("token typ is not at+jwt: not an access token (CONTRACT.md \xA710.1 rule 10)");
9142
+ }
9143
+ }
9144
+ function assertNoPurposeClaim(payload) {
9145
+ if (Object.prototype.hasOwnProperty.call(payload, "purpose")) {
9146
+ throw new AuthError("token carries a purpose claim: not an access token (CONTRACT.md \xA710.1 rule 11)");
9147
+ }
9148
+ }
9149
+ function isAccessTokenTyp(typ) {
9150
+ if (typeof typ !== "string") {
9151
+ return false;
9152
+ }
9153
+ const lower = typ.toLowerCase();
9154
+ return lower === "at+jwt" || lower === "application/at+jwt";
9155
+ }
8925
9156
  function assertTenantClaim(claim, expected) {
8926
9157
  if (typeof expected !== "string" || expected === "") {
8927
9158
  throw new AuthError(
@@ -9054,7 +9285,7 @@ function createNodeSession(options) {
9054
9285
  const tlsOptions = resolveNodeTlsOptions(options);
9055
9286
  wrapAxios(base.axios, jar, tlsOptions);
9056
9287
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
9057
- const jwksVerifier = createVerifier(options.baseUrl);
9288
+ const jwksVerifier = createVerifier(options.baseUrl, tlsOptions);
9058
9289
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar, tlsOptions);
9059
9290
  }
9060
9291
  function createNodeClient(options) {