axiam-sdk 1.0.0-alpha21 → 1.0.0-alpha24

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 (46) hide show
  1. package/README.md +93 -2
  2. package/dist/{authzCore-DuRI1aJf.d.cts → authzCore-CA9zFm1n.d.cts} +38 -4
  3. package/dist/{authzCore-DtSN59if.d.ts → authzCore-a-wZL2P3.d.ts} +38 -4
  4. package/dist/{client-B_FqmZ0i.d.cts → client-CtT9nHQP.d.cts} +1 -1
  5. package/dist/{client-Dn1fs5MH.d.ts → client-utwuwc9m.d.ts} +1 -1
  6. package/dist/{cookieJar-Cl8Lq9dL.d.ts → cookieJar-C9fqLqbh.d.ts} +29 -6
  7. package/dist/{cookieJar-BTDnjjbL.d.cts → cookieJar-DeJKczxD.d.cts} +29 -6
  8. package/dist/grpc/index.d.cts +5 -5
  9. package/dist/grpc/index.d.ts +5 -5
  10. package/dist/grpc/index.js +81 -14
  11. package/dist/grpc/index.js.map +1 -1
  12. package/dist/grpc/index.mjs +81 -14
  13. package/dist/grpc/index.mjs.map +1 -1
  14. package/dist/index.d.cts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +32 -7
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +32 -7
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{jwks-BgojMGC5.d.cts → jwks-DEiwxlku.d.cts} +84 -3
  21. package/dist/{jwks-BgojMGC5.d.ts → jwks-DEiwxlku.d.ts} +84 -3
  22. package/dist/middleware/index.d.cts +6 -6
  23. package/dist/middleware/index.d.ts +6 -6
  24. package/dist/middleware/index.js +177 -138
  25. package/dist/middleware/index.js.map +1 -1
  26. package/dist/middleware/index.mjs +176 -139
  27. package/dist/middleware/index.mjs.map +1 -1
  28. package/dist/nestjs/index.d.cts +2 -2
  29. package/dist/nestjs/index.d.ts +2 -2
  30. package/dist/node/index.d.cts +94 -6
  31. package/dist/node/index.d.ts +94 -6
  32. package/dist/node/index.js +183 -16
  33. package/dist/node/index.js.map +1 -1
  34. package/dist/node/index.mjs +179 -18
  35. package/dist/node/index.mjs.map +1 -1
  36. package/dist/{oidcState-CkFuCjpM.d.ts → oidcState-CfebuJ0n.d.ts} +2 -2
  37. package/dist/{oidcState-BGxqWUun.d.cts → oidcState-tHRAg5bu.d.cts} +2 -2
  38. package/dist/rest/index.d.cts +2 -2
  39. package/dist/rest/index.d.ts +2 -2
  40. package/dist/rest/index.js +32 -7
  41. package/dist/rest/index.js.map +1 -1
  42. package/dist/rest/index.mjs +32 -7
  43. package/dist/rest/index.mjs.map +1 -1
  44. package/dist/{session-BWUWhhyB.d.cts → session-ti3C9ZJU.d.cts} +28 -1
  45. package/dist/{session-BWUWhhyB.d.ts → session-ti3C9ZJU.d.ts} +28 -1
  46. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  import axios from 'axios';
2
2
  import { CookieJar } from 'tough-cookie';
3
- import { wrapper } from 'axios-cookiejar-support';
4
- import { randomBytes, createHash, timingSafeEqual } from 'crypto';
3
+ import { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/http';
4
+ import { randomBytes, createHash, createHmac, timingSafeEqual } from 'crypto';
5
5
 
6
6
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
7
7
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -258,6 +258,10 @@ var SharedSession = class {
258
258
  orgId;
259
259
  /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */
260
260
  orgSlug;
261
+ /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */
262
+ expectedIssuer;
263
+ /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */
264
+ expectedAudience;
261
265
  /**
262
266
  * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`
263
267
  * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config
@@ -295,6 +299,8 @@ var SharedSession = class {
295
299
  this.tenantSlug = options.tenantSlug;
296
300
  this.orgId = options.orgId;
297
301
  this.orgSlug = options.orgSlug;
302
+ this.expectedIssuer = options.expectedIssuer;
303
+ this.expectedAudience = options.expectedAudience;
298
304
  this.resolvedTenantId = options.tenantId;
299
305
  this.resolvedOrgId = options.orgId;
300
306
  this.refreshGuard = createRefreshGuard();
@@ -373,7 +379,20 @@ function resolveTenantHeaderValue(options) {
373
379
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
374
380
  );
375
381
  }
376
- function maybeBuildHttpsAgent(customCa, identity) {
382
+ function loadNodeHttps() {
383
+ const getBuiltinModule = process.getBuiltinModule;
384
+ if (typeof getBuiltinModule === "function") {
385
+ return getBuiltinModule.call(process, "node:https");
386
+ }
387
+ try {
388
+ return __require("https");
389
+ } catch {
390
+ throw new Error(
391
+ `customCa and clientCert require Node's https module, which this ESM build cannot load on Node ${process.version}: process.getBuiltinModule is unavailable (added in Node 20.16 / 22.3) and \`require\` does not exist in an ES module. Upgrade Node to >= 20.16, or load the CommonJS build (CONTRACT.md \xA76 / \xA76.1).`
392
+ );
393
+ }
394
+ }
395
+ function tlsOptionsFrom(customCa, identity) {
377
396
  if (!customCa) {
378
397
  if (!identity) {
379
398
  return void 0;
@@ -383,15 +402,24 @@ function maybeBuildHttpsAgent(customCa, identity) {
383
402
  'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
384
403
  );
385
404
  }
405
+ return {
406
+ ...customCa ? { ca: customCa } : {},
407
+ ...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
408
+ };
409
+ }
410
+ function resolveNodeTlsOptions(options) {
411
+ return tlsOptionsFrom(options.customCa, resolveClientIdentity(options));
412
+ }
413
+ function maybeBuildHttpsAgent(customCa, identity) {
414
+ const tls = tlsOptionsFrom(customCa, identity);
415
+ if (!tls) {
416
+ return void 0;
417
+ }
386
418
  if (typeof process === "undefined") {
387
419
  return void 0;
388
420
  }
389
- const https = __require("https");
390
- return new https.Agent({
391
- ...customCa ? { ca: customCa } : {},
392
- // rejectUnauthorized is intentionally left at its secure default (true).
393
- ...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
394
- });
421
+ const https = loadNodeHttps();
422
+ return new https.Agent(tls);
395
423
  }
396
424
  function createSession(options) {
397
425
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -714,10 +742,11 @@ var CSRF_COOKIE = "axiam_csrf";
714
742
  function createJar() {
715
743
  return new CookieJar();
716
744
  }
717
- function wrapAxios(instance, jar) {
718
- const wrapped = wrapper(instance);
719
- wrapped.defaults.jar = jar;
720
- return wrapped;
745
+ function wrapAxios(instance, jar, tls) {
746
+ const cookies = { jar };
747
+ instance.defaults.httpAgent = new HttpCookieAgent({ cookies });
748
+ instance.defaults.httpsAgent = new HttpsCookieAgent({ cookies, ...tls ?? {} });
749
+ return instance;
721
750
  }
722
751
  async function extractCookieValue(jar, url, name) {
723
752
  const cookies = await jar.getCookies(url);
@@ -887,6 +916,7 @@ function checkIdTokenClaims(claims, expectations, nowSec = Math.floor(Date.now()
887
916
  var JWKS_PATH = "/oauth2/jwks";
888
917
  var COOLDOWN_DURATION_MS = 6e4;
889
918
  var TIMEOUT_DURATION_MS = 5e3;
919
+ var CLOCK_SKEW_LEEWAY_SEC = 60;
890
920
  function createVerifier(baseUrl) {
891
921
  return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
892
922
  }
@@ -904,7 +934,20 @@ function createJwksVerifier(jwksUri) {
904
934
  return jwksPromise;
905
935
  }
906
936
  return {
907
- async verifyAccessToken(token) {
937
+ async verifyAccessToken(token, expectations) {
938
+ const { jwtVerify } = await import('jose');
939
+ const jwks = await getJwks();
940
+ const { payload } = await jwtVerify(token, jwks, {
941
+ algorithms: ["EdDSA"],
942
+ requiredClaims: ["exp"],
943
+ clockTolerance: CLOCK_SKEW_LEEWAY_SEC,
944
+ ...expectations.expectedIssuer !== void 0 ? { issuer: expectations.expectedIssuer } : {},
945
+ ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
946
+ });
947
+ assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
948
+ return payload;
949
+ },
950
+ async verifySignatureOnlyUnchecked(token) {
908
951
  const { jwtVerify } = await import('jose');
909
952
  const jwks = await getJwks();
910
953
  const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
@@ -938,6 +981,30 @@ function createJwksVerifier(jwksUri) {
938
981
  }
939
982
  };
940
983
  }
984
+ function assertTenantClaim(claim, expected) {
985
+ if (typeof expected !== "string" || expected === "") {
986
+ throw new AuthError(
987
+ "no configured tenant to verify the token against; refusing the request (CONTRACT.md \xA710.1 rule 4 fails closed)"
988
+ );
989
+ }
990
+ if (typeof claim !== "string" || claim === "") {
991
+ throw new AuthError("invalid tenant_id claim");
992
+ }
993
+ if (claim !== expected) {
994
+ warnOnceIfComparandLooksLikeASlug(claim, expected);
995
+ throw new AuthError("token tenant_id does not match configured tenant");
996
+ }
997
+ }
998
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
999
+ var slugComparandWarned = false;
1000
+ function warnOnceIfComparandLooksLikeASlug(claim, expected) {
1001
+ if (slugComparandWarned) return;
1002
+ if (!UUID_RE.test(claim) || UUID_RE.test(expected)) return;
1003
+ slugComparandWarned = true;
1004
+ console.warn(
1005
+ `AXIAM: the tenant this guard was configured with ("${expected}") is not a UUID, but access tokens carry the tenant UUID in their \`tenant_id\` claim, so this guard will reject every request. Configure it with the tenant UUID, not the slug. (CONTRACT.md \xA710.1 rule 4; logged once per process, and it does not affect the rejection itself.)`
1006
+ );
1007
+ }
941
1008
  function mapJoseVerifyError(err) {
942
1009
  const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
943
1010
  switch (code) {
@@ -1015,7 +1082,7 @@ var NodeSession = class extends SharedSession {
1015
1082
  function createNodeSession(options) {
1016
1083
  const base = createSession(options);
1017
1084
  const jar = createJar();
1018
- wrapAxios(base.axios, jar);
1085
+ wrapAxios(base.axios, jar, resolveNodeTlsOptions(options));
1019
1086
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
1020
1087
  const jwksVerifier = createVerifier(options.baseUrl);
1021
1088
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar);
@@ -1051,7 +1118,7 @@ var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
1051
1118
  "code_challenge",
1052
1119
  "code_challenge_method"
1053
1120
  ]);
1054
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1121
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1055
1122
  var DiscoveryCache = class {
1056
1123
  #documents = /* @__PURE__ */ new Map();
1057
1124
  #inFlight = /* @__PURE__ */ new Map();
@@ -1554,7 +1621,7 @@ var OidcClient = class {
1554
1621
  "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)."
1555
1622
  );
1556
1623
  }
1557
- if (!UUID_RE.test(candidate)) {
1624
+ if (!UUID_RE2.test(candidate)) {
1558
1625
  throw new AuthError(
1559
1626
  "tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted (CONTRACT.md \xA712.3 rule 4)."
1560
1627
  );
@@ -1701,7 +1768,101 @@ var MemoryOidcStateStore = class {
1701
1768
  }
1702
1769
  }
1703
1770
  };
1771
+ var DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
1772
+ var WebhookVerifyError = class _WebhookVerifyError extends Error {
1773
+ /** Stable reason code — see {@link WebhookVerifyFailureReason}. */
1774
+ reason;
1775
+ constructor(reason, message) {
1776
+ super(message);
1777
+ this.name = "WebhookVerifyError";
1778
+ this.reason = reason;
1779
+ Object.setPrototypeOf(this, _WebhookVerifyError.prototype);
1780
+ }
1781
+ };
1782
+ function fail(reason, message) {
1783
+ throw new WebhookVerifyError(reason, message);
1784
+ }
1785
+ var STRICT_HEX_PATTERN = /^[0-9a-fA-F]+$/;
1786
+ var STRICT_INTEGER_PATTERN = /^-?\d+$/;
1787
+ function parseSignatureHeader(header) {
1788
+ let t;
1789
+ let tCount = 0;
1790
+ const v1 = [];
1791
+ for (const rawPair of header.split(",")) {
1792
+ const pair = rawPair.trim();
1793
+ if (pair.length === 0) continue;
1794
+ const eq = pair.indexOf("=");
1795
+ if (eq === -1) continue;
1796
+ const key = pair.slice(0, eq).trim();
1797
+ const value = pair.slice(eq + 1).trim();
1798
+ if (key === "t") {
1799
+ t = value;
1800
+ tCount += 1;
1801
+ } else if (key === "v1") {
1802
+ v1.push(value);
1803
+ }
1804
+ }
1805
+ if (tCount !== 1 || t === void 0) {
1806
+ fail("malformed_header", 'signature header must carry exactly one "t" field');
1807
+ }
1808
+ if (v1.length === 0) {
1809
+ fail("malformed_header", 'signature header carries no "v1" field');
1810
+ }
1811
+ return { t, v1 };
1812
+ }
1813
+ function verifyWebhook(secret, signatureHeader, body, options = {}) {
1814
+ const { t, v1 } = parseSignatureHeader(signatureHeader);
1815
+ if (!STRICT_INTEGER_PATTERN.test(t)) {
1816
+ fail("invalid_timestamp", 'signature header "t" is not an integer');
1817
+ }
1818
+ const timestamp = Number(t);
1819
+ if (!Number.isFinite(timestamp)) {
1820
+ fail("invalid_timestamp", 'signature header "t" is out of range');
1821
+ }
1822
+ const rawBody = typeof body === "string" ? Buffer.from(body, "utf8") : Buffer.from(body);
1823
+ const secretBytes = Buffer.from(secret.expose(), "utf8");
1824
+ const signedPayload = Buffer.concat([Buffer.from(`${t}.`, "utf8"), rawBody]);
1825
+ const expected = createHmac("sha256", secretBytes).update(signedPayload).digest();
1826
+ let matched = false;
1827
+ for (const candidate of v1) {
1828
+ if (!STRICT_HEX_PATTERN.test(candidate) || candidate.length % 2 !== 0) {
1829
+ continue;
1830
+ }
1831
+ const candidateBytes = Buffer.from(candidate, "hex");
1832
+ if (candidateBytes.length !== expected.length) continue;
1833
+ if (timingSafeEqual(candidateBytes, expected)) {
1834
+ matched = true;
1835
+ break;
1836
+ }
1837
+ }
1838
+ if (!matched) {
1839
+ fail("signature_mismatch", "no v1 signature in the header matched the computed HMAC");
1840
+ }
1841
+ const nowSec = options.now ?? Math.floor(Date.now() / 1e3);
1842
+ const tolerance = options.tolerance ?? DEFAULT_WEBHOOK_TOLERANCE_SEC;
1843
+ const age = nowSec - timestamp;
1844
+ if (age > tolerance) {
1845
+ fail("stale_timestamp", `timestamp is ${age}s old, outside the ${tolerance}s tolerance`);
1846
+ }
1847
+ if (-age > tolerance) {
1848
+ fail("future_timestamp", `timestamp is ${-age}s in the future, outside the ${tolerance}s tolerance`);
1849
+ }
1850
+ let parsedBody;
1851
+ let event;
1852
+ let id;
1853
+ try {
1854
+ parsedBody = JSON.parse(rawBody.toString("utf8"));
1855
+ if (parsedBody !== null && typeof parsedBody === "object") {
1856
+ const obj = parsedBody;
1857
+ if (typeof obj.event === "string") event = obj.event;
1858
+ if (typeof obj.id === "string") id = obj.id;
1859
+ }
1860
+ } catch {
1861
+ parsedBody = void 0;
1862
+ }
1863
+ return { event, id, timestamp, body: parsedBody, rawBody };
1864
+ }
1704
1865
 
1705
- export { ACCESS_COOKIE, CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, CSRF_COOKIE, DISCOVERY_PATH, ID_TOKEN_ALG, JWKS_PATH, MAX_CLOCK_SKEW_SEC, MIN_DISCOVERY_TTL_MS, MemoryOidcStateStore, NodeSession, OIDC_STATE_TTL_MS, OidcClient, REFRESH_COOKIE, SSO_CALLBACK_PATH, SSO_START_PATH, TokenManager, computeCodeChallenge, createJar, createJwksVerifier, createNodeClient, createNodeSession, createOidcClient, createVerifier, extractCookieValue, generateCodeVerifier, normalizeOrigin, randomUrlSafeToken, wrapAxios };
1866
+ export { ACCESS_COOKIE, CLOCK_SKEW_LEEWAY_SEC, CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, CSRF_COOKIE, DEFAULT_WEBHOOK_TOLERANCE_SEC, DISCOVERY_PATH, ID_TOKEN_ALG, JWKS_PATH, MAX_CLOCK_SKEW_SEC, MIN_DISCOVERY_TTL_MS, MemoryOidcStateStore, NodeSession, OIDC_STATE_TTL_MS, OidcClient, REFRESH_COOKIE, SSO_CALLBACK_PATH, SSO_START_PATH, Sensitive, TokenManager, WebhookVerifyError, assertTenantClaim, computeCodeChallenge, createJar, createJwksVerifier, createNodeClient, createNodeSession, createOidcClient, createVerifier, extractCookieValue, generateCodeVerifier, normalizeOrigin, randomUrlSafeToken, verifyWebhook, wrapAxios };
1706
1867
  //# sourceMappingURL=index.mjs.map
1707
1868
  //# sourceMappingURL=index.mjs.map