axiam-sdk 1.3.1 → 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 +9 -9
@@ -992,6 +992,7 @@ var SharedSession = class {
992
992
  this.expectedIssuer = options.expectedIssuer;
993
993
  this.expectedAudience = options.expectedAudience;
994
994
  this.presentsClientCertificate = options.clientCert !== void 0 && options.clientKey !== void 0;
995
+ registerTlsOptions(this, options);
995
996
  this.resolvedTenantId = options.tenantId;
996
997
  this.resolvedOrgId = options.orgId;
997
998
  this.refreshGuard = createRefreshGuard();
@@ -1043,7 +1044,7 @@ var SharedSession = class {
1043
1044
  }
1044
1045
  /**
1045
1046
  * Host-isolation guard (3A, defense in depth): returns `true` when `url`
1046
- * targets a host other than this session's base origin — an absolute
1047
+ * targets an origin (scheme, host and port) other than this session's base origin — an absolute
1047
1048
  * third-party URL, or a redirect that axios/the browser resolved off-origin.
1048
1049
  * The tenant identifier and CSRF token must never be attached to such a
1049
1050
  * request. A relative/host-less `url` (the normal case, merged against
@@ -1057,7 +1058,7 @@ var SharedSession = class {
1057
1058
  }
1058
1059
  try {
1059
1060
  const target = new URL(url, this.baseUrl);
1060
- return target.host !== new URL(this.baseUrl).host;
1061
+ return target.origin !== new URL(this.baseUrl).origin;
1061
1062
  } catch {
1062
1063
  return true;
1063
1064
  }
@@ -1119,6 +1120,19 @@ function resolveTenantHeaderValue(options) {
1119
1120
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
1120
1121
  );
1121
1122
  }
1123
+ function agentTlsOptions(tls) {
1124
+ if (tls === void 0) return {};
1125
+ if (tls.ca === void 0) {
1126
+ return { ...tls.cert !== void 0 ? { cert: tls.cert } : {}, ...tls.key !== void 0 ? { key: tls.key } : {} };
1127
+ }
1128
+ const tlsMod = loadNodeBuiltin("node:tls");
1129
+ const secureContext = tlsMod.createSecureContext({
1130
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
1131
+ ...tls.key !== void 0 ? { key: tls.key } : {}
1132
+ });
1133
+ secureContext.context.addCACert(tls.ca);
1134
+ return { secureContext };
1135
+ }
1122
1136
  function loadNodeBuiltin(id) {
1123
1137
  const getBuiltinModule = process.getBuiltinModule;
1124
1138
  if (typeof getBuiltinModule === "function") {
@@ -1135,6 +1149,15 @@ function loadNodeBuiltin(id) {
1135
1149
  function loadNodeHttps() {
1136
1150
  return loadNodeBuiltin("node:https");
1137
1151
  }
1152
+ var sessionTlsOptions = /* @__PURE__ */ new WeakMap();
1153
+ function registerTlsOptions(session, options) {
1154
+ if (options.customCa === void 0 && options.clientCert === void 0) return;
1155
+ try {
1156
+ const tls = resolveNodeTlsOptions(options);
1157
+ if (tls !== void 0) sessionTlsOptions.set(session, tls);
1158
+ } catch {
1159
+ }
1160
+ }
1138
1161
  function tlsOptionsFrom(customCa, identity) {
1139
1162
  if (!customCa) {
1140
1163
  if (!identity) {
@@ -1158,7 +1181,7 @@ function buildPlainNodeAgents(tls) {
1158
1181
  const https = loadNodeHttps();
1159
1182
  return {
1160
1183
  httpAgent: new http.Agent(),
1161
- httpsAgent: new https.Agent(tls ?? {})
1184
+ httpsAgent: new https.Agent(agentTlsOptions(tls))
1162
1185
  };
1163
1186
  }
1164
1187
  function maybeBuildHttpsAgent(customCa, identity) {
@@ -1170,7 +1193,7 @@ function maybeBuildHttpsAgent(customCa, identity) {
1170
1193
  return void 0;
1171
1194
  }
1172
1195
  const https = loadNodeHttps();
1173
- return new https.Agent(tls);
1196
+ return new https.Agent(agentTlsOptions(tls));
1174
1197
  }
1175
1198
  function createSession(options) {
1176
1199
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -4226,7 +4249,7 @@ function normalizeSearch(term) {
4226
4249
  const trimmed = term?.trim();
4227
4250
  return trimmed ? trimmed : void 0;
4228
4251
  }
4229
- async function collectPages(start, fetch) {
4252
+ async function collectPages(start, fetch2) {
4230
4253
  let request = {
4231
4254
  offset: start.offset ?? 0,
4232
4255
  limit: start.limit,
@@ -4234,7 +4257,7 @@ async function collectPages(start, fetch) {
4234
4257
  };
4235
4258
  const out = [];
4236
4259
  for (; ; ) {
4237
- const page = await fetch(request);
4260
+ const page = await fetch2(request);
4238
4261
  out.push(...page.items);
4239
4262
  const next = page.offset + page.items.length;
4240
4263
  if (page.items.length === 0 || next >= page.total) return out;
@@ -8624,7 +8647,7 @@ function createJar() {
8624
8647
  function wrapAxios(instance, jar, tls) {
8625
8648
  const cookies = { jar };
8626
8649
  instance.defaults.httpAgent = new HttpCookieAgent({ cookies });
8627
- instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...tls ?? {} });
8650
+ instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...agentTlsOptions(tls) });
8628
8651
  return instance;
8629
8652
  }
8630
8653
  async function extractCookieValue(jar, url, name) {
@@ -8734,6 +8757,9 @@ function resolveClockSkewSec(clockSkewSec) {
8734
8757
  if (clockSkewSec === void 0) {
8735
8758
  return MAX_CLOCK_SKEW_SEC;
8736
8759
  }
8760
+ if (typeof clockSkewSec !== "number" || !Number.isFinite(clockSkewSec)) {
8761
+ throw new TypeError("clockSkewSec must be a finite number of seconds");
8762
+ }
8737
8763
  return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);
8738
8764
  }
8739
8765
  function constantTimeEquals(a, b) {
@@ -8830,26 +8856,196 @@ function constantTimeEqual(a, b) {
8830
8856
  var JWKS_PATH = "/oauth2/jwks";
8831
8857
  var COOLDOWN_DURATION_MS = 6e4;
8832
8858
  var TIMEOUT_DURATION_MS = 5e3;
8859
+ var JWKS_MAX_TTL_MS = 3e5;
8860
+ var JWKS_MAX_STALE_MS = 3e5;
8861
+ var JWKS_MAX_BODY_BYTES = 50 * 1024;
8862
+ async function readCappedJson(res, maxBytes) {
8863
+ const declared = res.headers.get("content-length");
8864
+ if (declared !== null && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
8865
+ await res.body?.cancel().catch(() => void 0);
8866
+ throw new Error("JWKS response too large");
8867
+ }
8868
+ const reader = res.body?.getReader();
8869
+ if (reader === void 0) throw new Error("JWKS response has no body");
8870
+ const chunks = [];
8871
+ let total = 0;
8872
+ for (; ; ) {
8873
+ const { done, value } = await reader.read();
8874
+ if (done) break;
8875
+ total += value.byteLength;
8876
+ if (total > maxBytes) {
8877
+ await reader.cancel().catch(() => void 0);
8878
+ throw new Error("JWKS response too large");
8879
+ }
8880
+ chunks.push(value);
8881
+ }
8882
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
8883
+ }
8884
+ function ttlFromResponse(res) {
8885
+ const m = /(?:^|[\s,])max-age=(\d+)/i.exec(res.headers.get("cache-control") ?? "");
8886
+ if (m === null) return JWKS_MAX_TTL_MS;
8887
+ const ms = Number(m[1]) * 1e3;
8888
+ return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;
8889
+ }
8890
+ async function fetchWithTls(url, init, tls) {
8891
+ const https = (await import('https')).default;
8892
+ const { Readable } = await import('stream');
8893
+ const tlsMod = await import('tls');
8894
+ let secureContext;
8895
+ if (tls.ca !== void 0) {
8896
+ secureContext = tlsMod.createSecureContext({
8897
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8898
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8899
+ });
8900
+ secureContext.context.addCACert(tls.ca);
8901
+ }
8902
+ return new Promise((resolve, reject) => {
8903
+ let settled = false;
8904
+ const settle = (fn) => {
8905
+ if (settled) return;
8906
+ settled = true;
8907
+ fn();
8908
+ };
8909
+ const agent = new https.Agent(
8910
+ secureContext !== void 0 ? { secureContext } : {
8911
+ ...tls.cert !== void 0 ? { cert: tls.cert } : {},
8912
+ ...tls.key !== void 0 ? { key: tls.key } : {}
8913
+ }
8914
+ );
8915
+ const fail = (message = "unexpected JWKS status") => {
8916
+ agent.destroy();
8917
+ settle(() => reject(new Error(message)));
8918
+ };
8919
+ const req = https.request(
8920
+ url,
8921
+ { method: "GET", headers: init.headers, signal: init.signal, agent },
8922
+ (res) => {
8923
+ try {
8924
+ const status = res.statusCode ?? 0;
8925
+ if (status !== 200 && status !== 304) {
8926
+ res.destroy();
8927
+ fail();
8928
+ return;
8929
+ }
8930
+ const headers = new Headers();
8931
+ for (const [name, value] of Object.entries(res.headers)) {
8932
+ if (value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
8933
+ }
8934
+ if (status === 304) res.resume();
8935
+ const body = status === 304 ? null : Readable.toWeb(res);
8936
+ const response = new Response(body, { status, headers });
8937
+ res.on("close", () => agent.destroy());
8938
+ settle(() => resolve(response));
8939
+ } catch {
8940
+ res.destroy();
8941
+ fail();
8942
+ }
8943
+ }
8944
+ );
8945
+ req.on("error", (err) => {
8946
+ agent.destroy();
8947
+ settle(() => reject(err));
8948
+ });
8949
+ req.on("close", () => {
8950
+ if (!settled) fail("JWKS request closed before a response");
8951
+ });
8952
+ req.end();
8953
+ });
8954
+ }
8955
+ var JwksCache = class {
8956
+ constructor(jwksUri, jose, tls) {
8957
+ this.jwksUri = jwksUri;
8958
+ this.jose = jose;
8959
+ this.#tls = tls;
8960
+ }
8961
+ jwksUri;
8962
+ jose;
8963
+ #resolver;
8964
+ #etag;
8965
+ #anchorMs = 0;
8966
+ #ttlMs = JWKS_MAX_TTL_MS;
8967
+ #lastAttemptMs;
8968
+ #inflight;
8969
+ /** Held privately: it may carry the client key, and must not be an enumerable property. */
8970
+ #tls;
8971
+ /** The key resolver handed to `jwtVerify`. */
8972
+ getKey = async (...args) => {
8973
+ const usable = () => this.#resolver !== void 0 && Date.now() >= this.#anchorMs && Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS ? this.#resolver : void 0;
8974
+ const nowMs = Date.now();
8975
+ if (this.#resolver === void 0 || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {
8976
+ const refresh2 = this.#refreshIfAllowed();
8977
+ if (usable() === void 0) await refresh2;
8978
+ }
8979
+ const held = usable();
8980
+ if (held === void 0) {
8981
+ throw new this.jose.errors.JOSEError("the JSON Web Key Set is unavailable");
8982
+ }
8983
+ try {
8984
+ return await held(...args);
8985
+ } catch (err) {
8986
+ if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;
8987
+ await this.#refreshIfAllowed();
8988
+ const refreshed = usable();
8989
+ if (refreshed === void 0) throw err;
8990
+ return refreshed(...args);
8991
+ }
8992
+ };
8993
+ async #refreshIfAllowed() {
8994
+ if (this.#inflight !== void 0) return this.#inflight;
8995
+ const now = Date.now();
8996
+ const sinceLast = this.#lastAttemptMs === void 0 ? Infinity : now - this.#lastAttemptMs;
8997
+ if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return;
8998
+ this.#lastAttemptMs = now;
8999
+ this.#inflight = this.#fetch().catch(() => void 0).finally(() => {
9000
+ this.#inflight = void 0;
9001
+ });
9002
+ return this.#inflight;
9003
+ }
9004
+ async #fetch() {
9005
+ const conditional = this.#resolver !== void 0 && this.#etag !== void 0;
9006
+ const headers = { accept: "application/json", ...conditional ? { "if-none-match": this.#etag } : {} };
9007
+ const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);
9008
+ 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 });
9009
+ if (res.status === 304 && conditional) {
9010
+ await res.body?.cancel().catch(() => void 0);
9011
+ this.#anchorMs = Date.now();
9012
+ this.#ttlMs = ttlFromResponse(res);
9013
+ return;
9014
+ }
9015
+ if (res.status !== 200) {
9016
+ await res.body?.cancel().catch(() => void 0);
9017
+ throw new Error("unexpected JWKS status");
9018
+ }
9019
+ const doc = await readCappedJson(res, JWKS_MAX_BODY_BYTES);
9020
+ const isJwk = (k) => typeof k === "object" && k !== null && !Array.isArray(k) && typeof k.kty === "string";
9021
+ if (typeof doc !== "object" || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {
9022
+ throw new Error("not a JWKS document with a key");
9023
+ }
9024
+ const usable = doc.keys.filter(isJwk);
9025
+ const resolver = this.jose.createLocalJWKSet({ keys: usable });
9026
+ this.#resolver = resolver;
9027
+ const etag = res.headers.get("etag");
9028
+ this.#etag = etag !== null && Buffer.byteLength(etag) <= 256 && !/[\x00-\x1f\x7f]/.test(etag) ? etag : void 0;
9029
+ this.#anchorMs = Date.now();
9030
+ this.#ttlMs = ttlFromResponse(res);
9031
+ }
9032
+ };
8833
9033
  var CLOCK_SKEW_LEEWAY_SEC = 60;
8834
- function createVerifier(baseUrl) {
8835
- return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
9034
+ function createVerifier(baseUrl, tlsOptions) {
9035
+ return createJwksVerifier(`${baseUrl}${JWKS_PATH}`, tlsOptions);
8836
9036
  }
8837
- function createJwksVerifier(jwksUri) {
9037
+ function createJwksVerifier(jwksUri, tlsOptions) {
8838
9038
  let jwksPromise = null;
8839
9039
  async function getJwks() {
8840
9040
  if (!jwksPromise) {
8841
- jwksPromise = import('jose').then(
8842
- ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(jwksUri), {
8843
- cooldownDuration: COOLDOWN_DURATION_MS,
8844
- timeoutDuration: TIMEOUT_DURATION_MS
8845
- })
8846
- );
9041
+ jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));
8847
9042
  }
8848
- return jwksPromise;
9043
+ return (await jwksPromise).getKey;
8849
9044
  }
8850
9045
  return {
8851
9046
  async verifyAccessToken(token, expectations, proofs = {}) {
8852
9047
  const { jwtVerify } = await import('jose');
9048
+ assertAccessTokenHeader(token);
8853
9049
  const jwks = await getJwks();
8854
9050
  const { payload } = await jwtVerify(token, jwks, {
8855
9051
  algorithms: ["EdDSA"],
@@ -8859,6 +9055,7 @@ function createJwksVerifier(jwksUri) {
8859
9055
  ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
8860
9056
  });
8861
9057
  assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
9058
+ assertNoPurposeClaim(payload);
8862
9059
  const claims = payload;
8863
9060
  verifyTokenBinding(claims, proofs);
8864
9061
  return claims;
@@ -8897,6 +9094,40 @@ function createJwksVerifier(jwksUri) {
8897
9094
  }
8898
9095
  };
8899
9096
  }
9097
+ function assertAccessTokenHeader(token) {
9098
+ let header;
9099
+ try {
9100
+ const segments = token.split(".");
9101
+ if (segments.length !== 3) {
9102
+ throw new Error("not three segments");
9103
+ }
9104
+ const parsed = JSON.parse(Buffer.from(segments[0], "base64url").toString("utf8"));
9105
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
9106
+ throw new Error("header is not an object");
9107
+ }
9108
+ header = parsed;
9109
+ } catch {
9110
+ throw new AuthError("access token is not a well-formed JWS");
9111
+ }
9112
+ if (typeof header.kid !== "string" || header.kid.length === 0) {
9113
+ throw new AuthError("access token carries no kid header (CONTRACT.md \xA710.1 rule 12)");
9114
+ }
9115
+ if (header.typ !== void 0 && !isAccessTokenTyp(header.typ)) {
9116
+ throw new AuthError("token typ is not at+jwt: not an access token (CONTRACT.md \xA710.1 rule 10)");
9117
+ }
9118
+ }
9119
+ function assertNoPurposeClaim(payload) {
9120
+ if (Object.prototype.hasOwnProperty.call(payload, "purpose")) {
9121
+ throw new AuthError("token carries a purpose claim: not an access token (CONTRACT.md \xA710.1 rule 11)");
9122
+ }
9123
+ }
9124
+ function isAccessTokenTyp(typ) {
9125
+ if (typeof typ !== "string") {
9126
+ return false;
9127
+ }
9128
+ const lower = typ.toLowerCase();
9129
+ return lower === "at+jwt" || lower === "application/at+jwt";
9130
+ }
8900
9131
  function assertTenantClaim(claim, expected) {
8901
9132
  if (typeof expected !== "string" || expected === "") {
8902
9133
  throw new AuthError(
@@ -9029,7 +9260,7 @@ function createNodeSession(options) {
9029
9260
  const tlsOptions = resolveNodeTlsOptions(options);
9030
9261
  wrapAxios(base.axios, jar, tlsOptions);
9031
9262
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
9032
- const jwksVerifier = createVerifier(options.baseUrl);
9263
+ const jwksVerifier = createVerifier(options.baseUrl, tlsOptions);
9033
9264
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar, tlsOptions);
9034
9265
  }
9035
9266
  function createNodeClient(options) {