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,8 +1,8 @@
1
- import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-DuRI1aJf.cjs';
1
+ import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-CA9zFm1n.cjs';
2
2
  import { CanActivate, ExecutionContext } from '@nestjs/common';
3
3
  import { Reflector } from '@nestjs/core';
4
4
  import '../types-BVkMoqLU.cjs';
5
- import '../jwks-BgojMGC5.cjs';
5
+ import '../jwks-DEiwxlku.cjs';
6
6
 
7
7
  /** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
8
8
  interface NestParamResource {
@@ -1,8 +1,8 @@
1
- import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-DtSN59if.js';
1
+ import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-a-wZL2P3.js';
2
2
  import { CanActivate, ExecutionContext } from '@nestjs/common';
3
3
  import { Reflector } from '@nestjs/core';
4
4
  import '../types-BVkMoqLU.js';
5
- import '../jwks-BgojMGC5.js';
5
+ import '../jwks-DEiwxlku.js';
6
6
 
7
7
  /** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
8
8
  interface NestParamResource {
@@ -1,11 +1,11 @@
1
- export { A as ACCESS_COOKIE, C as CSRF_COOKIE, N as NodeSession, R as REFRESH_COOKIE, T as TokenManager, c as createJar, a as createNodeClient, b as createNodeSession, e as extractCookieValue, w as wrapAxios } from '../cookieJar-BTDnjjbL.cjs';
2
- export { A as AxiamClaims, I as ID_TOKEN_ALG, a as IdTokenClaims, b as IdTokenExpectations, c as IdTokenVerifier, J as JWKS_PATH, d as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, V as Verifier, e as createJwksVerifier, f as createVerifier } from '../jwks-BgojMGC5.cjs';
3
- export { A as AuthorizationRequest, D as DISCOVERY_PATH, I as IntrospectParams, a as IntrospectionResult, L as LoginClientCredentialsParams, M as MIN_DISCOVERY_TTL_MS, b as MemoryOidcStateStore, O as OIDC_STATE_TTL_MS, c as OidcBeginParams, d as OidcClient, e as OidcClientOptions, f as OidcConfiguration, g as OidcExchangeParams, h as OidcRefreshParams, i as OidcStateEntry, j as OidcStateStore, k as OidcTokenSet, R as RevokeParams, S as SSO_CALLBACK_PATH, l as SSO_START_PATH, m as SsoCompleteParams, n as SsoCompleteResult, o as SsoStartParams, p as SsoStartResult, q as createOidcClient, r as normalizeOrigin } from '../oidcState-BGxqWUun.cjs';
1
+ export { A as ACCESS_COOKIE, C as CSRF_COOKIE, N as NodeSession, R as REFRESH_COOKIE, T as TokenManager, c as createJar, a as createNodeClient, b as createNodeSession, e as extractCookieValue, w as wrapAxios } from '../cookieJar-DeJKczxD.cjs';
2
+ export { A as AccessTokenExpectations, a as AxiamClaims, C as CLOCK_SKEW_LEEWAY_SEC, I as ID_TOKEN_ALG, b as IdTokenClaims, c as IdTokenExpectations, d as IdTokenVerifier, J as JWKS_PATH, e as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, V as Verifier, f as assertTenantClaim, g as createJwksVerifier, h as createVerifier } from '../jwks-DEiwxlku.cjs';
3
+ export { A as AuthorizationRequest, D as DISCOVERY_PATH, I as IntrospectParams, a as IntrospectionResult, L as LoginClientCredentialsParams, M as MIN_DISCOVERY_TTL_MS, b as MemoryOidcStateStore, O as OIDC_STATE_TTL_MS, c as OidcBeginParams, d as OidcClient, e as OidcClientOptions, f as OidcConfiguration, g as OidcExchangeParams, h as OidcRefreshParams, i as OidcStateEntry, j as OidcStateStore, k as OidcTokenSet, R as RevokeParams, S as SSO_CALLBACK_PATH, l as SSO_START_PATH, m as SsoCompleteParams, n as SsoCompleteResult, o as SsoStartParams, p as SsoStartResult, q as createOidcClient, r as normalizeOrigin } from '../oidcState-tHRAg5bu.cjs';
4
4
  import { S as Sensitive } from '../sensitive-BC_s7Rrd.cjs';
5
5
  import 'tough-cookie';
6
- import '../session-BWUWhhyB.cjs';
6
+ import '../session-ti3C9ZJU.cjs';
7
7
  import 'axios';
8
- import '../client-B_FqmZ0i.cjs';
8
+ import '../client-CtT9nHQP.cjs';
9
9
  import '../types-BVkMoqLU.cjs';
10
10
 
11
11
  /**
@@ -57,4 +57,92 @@ declare function generateCodeVerifier(): Sensitive<string>;
57
57
  */
58
58
  declare function computeCodeChallenge(codeVerifier: string): string;
59
59
 
60
- export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, computeCodeChallenge, generateCodeVerifier, randomUrlSafeToken };
60
+ /** Default freshness window, in seconds, for the `t=` timestamp (CONTRACT.md §13.2). */
61
+ declare const DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
62
+ /**
63
+ * Stable, machine-readable reason codes for a failed {@link verifyWebhook}
64
+ * call. Never derived from — and never leaks — the expected/computed
65
+ * signature or the secret (CONTRACT.md §13.3 rule 6).
66
+ */
67
+ type WebhookVerifyFailureReason = 'malformed_header' | 'invalid_timestamp' | 'signature_mismatch' | 'stale_timestamp' | 'future_timestamp';
68
+ /**
69
+ * Thrown by {@link verifyWebhook} on any verification failure.
70
+ *
71
+ * @remarks
72
+ * Carries a stable {@link reason} code for programmatic branching. `message`
73
+ * is short and generic — it MUST NOT, and never does, include the expected
74
+ * or computed signature, the secret, or the raw signature header value
75
+ * (CONTRACT.md §13.3 rule 6). Callers should treat any `WebhookVerifyError`
76
+ * uniformly (reject the delivery); the `reason` is for logging/metrics, not
77
+ * for varying the trust decision.
78
+ */
79
+ declare class WebhookVerifyError extends Error {
80
+ /** Stable reason code — see {@link WebhookVerifyFailureReason}. */
81
+ readonly reason: WebhookVerifyFailureReason;
82
+ constructor(reason: WebhookVerifyFailureReason, message: string);
83
+ }
84
+ /** The verified event returned by {@link verifyWebhook} on success. */
85
+ interface VerifiedWebhookEvent {
86
+ /** The delivery body's `event` field (event type), when the body is a JSON object carrying one. */
87
+ event?: string;
88
+ /**
89
+ * The delivery body's `id` field. Use this — or the separate
90
+ * `X-Axiam-Delivery` request header — as the at-least-once dedup key
91
+ * (CONTRACT.md §13.3 rule 7): a retried delivery replays a validly-signed
92
+ * request inside the freshness window, so receivers should keep a
93
+ * short-lived seen-set keyed on it.
94
+ */
95
+ id?: string;
96
+ /** The verified `t=` timestamp, epoch seconds. */
97
+ timestamp: number;
98
+ /** The JSON-parsed body, when it parses as JSON; `undefined` for a non-JSON payload (the signature is still verified either way). */
99
+ body?: unknown;
100
+ /** The exact raw body bytes that were verified. */
101
+ rawBody: Buffer;
102
+ }
103
+ /** Options for {@link verifyWebhook}. */
104
+ interface VerifyWebhookOptions {
105
+ /**
106
+ * Freshness window in seconds. Defaults to
107
+ * {@link DEFAULT_WEBHOOK_TOLERANCE_SEC} (300s). Two-sided: a `t=` more
108
+ * than `tolerance` seconds in the past OR more than `tolerance` seconds in
109
+ * the future is rejected (CONTRACT.md §13.3 rule 5 — rejecting
110
+ * future-dated timestamps too is required, not optional, as a guard
111
+ * against clock-skew abuse).
112
+ */
113
+ tolerance?: number;
114
+ /**
115
+ * Injectable "current time" in epoch seconds, for deterministic tests.
116
+ * Defaults to `Math.floor(Date.now() / 1000)`.
117
+ */
118
+ now?: number;
119
+ }
120
+ /**
121
+ * Verify an AXIAM webhook delivery's `X-Axiam-Signature` header against the
122
+ * raw request body (CONTRACT.md §13).
123
+ *
124
+ * Verification order (§13.3, normative): parse the header → parse `t` →
125
+ * recompute `HMAC-SHA256(secret, "<t>.<raw_body>")` → constant-time compare
126
+ * against every supplied `v1` candidate → two-sided freshness check → on
127
+ * success, return the parsed event.
128
+ *
129
+ * @param secret The webhook's plaintext signing secret, wrapped per
130
+ * CONTRACT.md §7.
131
+ * @param signatureHeader The raw `X-Axiam-Signature` header value. (Do NOT
132
+ * pass `X-Axiam-Timestamp` here — `t=` in this header is the value
133
+ * actually covered by the MAC; if you also read the separate
134
+ * `X-Axiam-Timestamp` header, require it to equal the parsed `t` yourself
135
+ * before calling this function.)
136
+ * @param body The **exact raw bytes** received off the wire (`Buffer`,
137
+ * `Uint8Array`, or the identical raw string) — never a re-serialized
138
+ * `JSON.stringify` of the parsed body, which changes key order/whitespace
139
+ * and breaks the MAC.
140
+ * @param options Freshness tolerance (default 300s) and a `now` injection
141
+ * seam for tests.
142
+ * @returns The verified event on success.
143
+ * @throws {WebhookVerifyError} On any verification failure. Never throws a
144
+ * generic `Error` whose message could leak the expected signature.
145
+ */
146
+ declare function verifyWebhook(secret: Sensitive<string>, signatureHeader: string, body: Buffer | Uint8Array | string, options?: VerifyWebhookOptions): VerifiedWebhookEvent;
147
+
148
+ export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, Sensitive, type VerifiedWebhookEvent, type VerifyWebhookOptions, WebhookVerifyError, type WebhookVerifyFailureReason, computeCodeChallenge, generateCodeVerifier, randomUrlSafeToken, verifyWebhook };
@@ -1,11 +1,11 @@
1
- export { A as ACCESS_COOKIE, C as CSRF_COOKIE, N as NodeSession, R as REFRESH_COOKIE, T as TokenManager, c as createJar, a as createNodeClient, b as createNodeSession, e as extractCookieValue, w as wrapAxios } from '../cookieJar-Cl8Lq9dL.js';
2
- export { A as AxiamClaims, I as ID_TOKEN_ALG, a as IdTokenClaims, b as IdTokenExpectations, c as IdTokenVerifier, J as JWKS_PATH, d as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, V as Verifier, e as createJwksVerifier, f as createVerifier } from '../jwks-BgojMGC5.js';
3
- export { A as AuthorizationRequest, D as DISCOVERY_PATH, I as IntrospectParams, a as IntrospectionResult, L as LoginClientCredentialsParams, M as MIN_DISCOVERY_TTL_MS, b as MemoryOidcStateStore, O as OIDC_STATE_TTL_MS, c as OidcBeginParams, d as OidcClient, e as OidcClientOptions, f as OidcConfiguration, g as OidcExchangeParams, h as OidcRefreshParams, i as OidcStateEntry, j as OidcStateStore, k as OidcTokenSet, R as RevokeParams, S as SSO_CALLBACK_PATH, l as SSO_START_PATH, m as SsoCompleteParams, n as SsoCompleteResult, o as SsoStartParams, p as SsoStartResult, q as createOidcClient, r as normalizeOrigin } from '../oidcState-CkFuCjpM.js';
1
+ export { A as ACCESS_COOKIE, C as CSRF_COOKIE, N as NodeSession, R as REFRESH_COOKIE, T as TokenManager, c as createJar, a as createNodeClient, b as createNodeSession, e as extractCookieValue, w as wrapAxios } from '../cookieJar-C9fqLqbh.js';
2
+ export { A as AccessTokenExpectations, a as AxiamClaims, C as CLOCK_SKEW_LEEWAY_SEC, I as ID_TOKEN_ALG, b as IdTokenClaims, c as IdTokenExpectations, d as IdTokenVerifier, J as JWKS_PATH, e as JwksVerifier, M as MAX_CLOCK_SKEW_SEC, V as Verifier, f as assertTenantClaim, g as createJwksVerifier, h as createVerifier } from '../jwks-DEiwxlku.js';
3
+ export { A as AuthorizationRequest, D as DISCOVERY_PATH, I as IntrospectParams, a as IntrospectionResult, L as LoginClientCredentialsParams, M as MIN_DISCOVERY_TTL_MS, b as MemoryOidcStateStore, O as OIDC_STATE_TTL_MS, c as OidcBeginParams, d as OidcClient, e as OidcClientOptions, f as OidcConfiguration, g as OidcExchangeParams, h as OidcRefreshParams, i as OidcStateEntry, j as OidcStateStore, k as OidcTokenSet, R as RevokeParams, S as SSO_CALLBACK_PATH, l as SSO_START_PATH, m as SsoCompleteParams, n as SsoCompleteResult, o as SsoStartParams, p as SsoStartResult, q as createOidcClient, r as normalizeOrigin } from '../oidcState-CfebuJ0n.js';
4
4
  import { S as Sensitive } from '../sensitive-BC_s7Rrd.js';
5
5
  import 'tough-cookie';
6
- import '../session-BWUWhhyB.js';
6
+ import '../session-ti3C9ZJU.js';
7
7
  import 'axios';
8
- import '../client-Dn1fs5MH.js';
8
+ import '../client-utwuwc9m.js';
9
9
  import '../types-BVkMoqLU.js';
10
10
 
11
11
  /**
@@ -57,4 +57,92 @@ declare function generateCodeVerifier(): Sensitive<string>;
57
57
  */
58
58
  declare function computeCodeChallenge(codeVerifier: string): string;
59
59
 
60
- export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, computeCodeChallenge, generateCodeVerifier, randomUrlSafeToken };
60
+ /** Default freshness window, in seconds, for the `t=` timestamp (CONTRACT.md §13.2). */
61
+ declare const DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
62
+ /**
63
+ * Stable, machine-readable reason codes for a failed {@link verifyWebhook}
64
+ * call. Never derived from — and never leaks — the expected/computed
65
+ * signature or the secret (CONTRACT.md §13.3 rule 6).
66
+ */
67
+ type WebhookVerifyFailureReason = 'malformed_header' | 'invalid_timestamp' | 'signature_mismatch' | 'stale_timestamp' | 'future_timestamp';
68
+ /**
69
+ * Thrown by {@link verifyWebhook} on any verification failure.
70
+ *
71
+ * @remarks
72
+ * Carries a stable {@link reason} code for programmatic branching. `message`
73
+ * is short and generic — it MUST NOT, and never does, include the expected
74
+ * or computed signature, the secret, or the raw signature header value
75
+ * (CONTRACT.md §13.3 rule 6). Callers should treat any `WebhookVerifyError`
76
+ * uniformly (reject the delivery); the `reason` is for logging/metrics, not
77
+ * for varying the trust decision.
78
+ */
79
+ declare class WebhookVerifyError extends Error {
80
+ /** Stable reason code — see {@link WebhookVerifyFailureReason}. */
81
+ readonly reason: WebhookVerifyFailureReason;
82
+ constructor(reason: WebhookVerifyFailureReason, message: string);
83
+ }
84
+ /** The verified event returned by {@link verifyWebhook} on success. */
85
+ interface VerifiedWebhookEvent {
86
+ /** The delivery body's `event` field (event type), when the body is a JSON object carrying one. */
87
+ event?: string;
88
+ /**
89
+ * The delivery body's `id` field. Use this — or the separate
90
+ * `X-Axiam-Delivery` request header — as the at-least-once dedup key
91
+ * (CONTRACT.md §13.3 rule 7): a retried delivery replays a validly-signed
92
+ * request inside the freshness window, so receivers should keep a
93
+ * short-lived seen-set keyed on it.
94
+ */
95
+ id?: string;
96
+ /** The verified `t=` timestamp, epoch seconds. */
97
+ timestamp: number;
98
+ /** The JSON-parsed body, when it parses as JSON; `undefined` for a non-JSON payload (the signature is still verified either way). */
99
+ body?: unknown;
100
+ /** The exact raw body bytes that were verified. */
101
+ rawBody: Buffer;
102
+ }
103
+ /** Options for {@link verifyWebhook}. */
104
+ interface VerifyWebhookOptions {
105
+ /**
106
+ * Freshness window in seconds. Defaults to
107
+ * {@link DEFAULT_WEBHOOK_TOLERANCE_SEC} (300s). Two-sided: a `t=` more
108
+ * than `tolerance` seconds in the past OR more than `tolerance` seconds in
109
+ * the future is rejected (CONTRACT.md §13.3 rule 5 — rejecting
110
+ * future-dated timestamps too is required, not optional, as a guard
111
+ * against clock-skew abuse).
112
+ */
113
+ tolerance?: number;
114
+ /**
115
+ * Injectable "current time" in epoch seconds, for deterministic tests.
116
+ * Defaults to `Math.floor(Date.now() / 1000)`.
117
+ */
118
+ now?: number;
119
+ }
120
+ /**
121
+ * Verify an AXIAM webhook delivery's `X-Axiam-Signature` header against the
122
+ * raw request body (CONTRACT.md §13).
123
+ *
124
+ * Verification order (§13.3, normative): parse the header → parse `t` →
125
+ * recompute `HMAC-SHA256(secret, "<t>.<raw_body>")` → constant-time compare
126
+ * against every supplied `v1` candidate → two-sided freshness check → on
127
+ * success, return the parsed event.
128
+ *
129
+ * @param secret The webhook's plaintext signing secret, wrapped per
130
+ * CONTRACT.md §7.
131
+ * @param signatureHeader The raw `X-Axiam-Signature` header value. (Do NOT
132
+ * pass `X-Axiam-Timestamp` here — `t=` in this header is the value
133
+ * actually covered by the MAC; if you also read the separate
134
+ * `X-Axiam-Timestamp` header, require it to equal the parsed `t` yourself
135
+ * before calling this function.)
136
+ * @param body The **exact raw bytes** received off the wire (`Buffer`,
137
+ * `Uint8Array`, or the identical raw string) — never a re-serialized
138
+ * `JSON.stringify` of the parsed body, which changes key order/whitespace
139
+ * and breaks the MAC.
140
+ * @param options Freshness tolerance (default 300s) and a `now` injection
141
+ * seam for tests.
142
+ * @returns The verified event on success.
143
+ * @throws {WebhookVerifyError} On any verification failure. Never throws a
144
+ * generic `Error` whose message could leak the expected signature.
145
+ */
146
+ declare function verifyWebhook(secret: Sensitive<string>, signatureHeader: string, body: Buffer | Uint8Array | string, options?: VerifyWebhookOptions): VerifiedWebhookEvent;
147
+
148
+ export { CODE_CHALLENGE_METHOD_S256, CSPRNG_BYTES, DEFAULT_WEBHOOK_TOLERANCE_SEC, Sensitive, type VerifiedWebhookEvent, type VerifyWebhookOptions, WebhookVerifyError, type WebhookVerifyFailureReason, computeCodeChallenge, generateCodeVerifier, randomUrlSafeToken, verifyWebhook };
@@ -2,7 +2,7 @@
2
2
 
3
3
  var axios = require('axios');
4
4
  var toughCookie = require('tough-cookie');
5
- var axiosCookiejarSupport = require('axios-cookiejar-support');
5
+ var http = require('http-cookie-agent/http');
6
6
  var crypto = require('crypto');
7
7
 
8
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -264,6 +264,10 @@ var SharedSession = class {
264
264
  orgId;
265
265
  /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */
266
266
  orgSlug;
267
+ /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */
268
+ expectedIssuer;
269
+ /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */
270
+ expectedAudience;
267
271
  /**
268
272
  * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`
269
273
  * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config
@@ -301,6 +305,8 @@ var SharedSession = class {
301
305
  this.tenantSlug = options.tenantSlug;
302
306
  this.orgId = options.orgId;
303
307
  this.orgSlug = options.orgSlug;
308
+ this.expectedIssuer = options.expectedIssuer;
309
+ this.expectedAudience = options.expectedAudience;
304
310
  this.resolvedTenantId = options.tenantId;
305
311
  this.resolvedOrgId = options.orgId;
306
312
  this.refreshGuard = createRefreshGuard();
@@ -379,7 +385,20 @@ function resolveTenantHeaderValue(options) {
379
385
  "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
380
386
  );
381
387
  }
382
- function maybeBuildHttpsAgent(customCa, identity) {
388
+ function loadNodeHttps() {
389
+ const getBuiltinModule = process.getBuiltinModule;
390
+ if (typeof getBuiltinModule === "function") {
391
+ return getBuiltinModule.call(process, "node:https");
392
+ }
393
+ try {
394
+ return __require("https");
395
+ } catch {
396
+ throw new Error(
397
+ `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).`
398
+ );
399
+ }
400
+ }
401
+ function tlsOptionsFrom(customCa, identity) {
383
402
  if (!customCa) {
384
403
  if (!identity) {
385
404
  return void 0;
@@ -389,15 +408,24 @@ function maybeBuildHttpsAgent(customCa, identity) {
389
408
  'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
390
409
  );
391
410
  }
411
+ return {
412
+ ...customCa ? { ca: customCa } : {},
413
+ ...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
414
+ };
415
+ }
416
+ function resolveNodeTlsOptions(options) {
417
+ return tlsOptionsFrom(options.customCa, resolveClientIdentity(options));
418
+ }
419
+ function maybeBuildHttpsAgent(customCa, identity) {
420
+ const tls = tlsOptionsFrom(customCa, identity);
421
+ if (!tls) {
422
+ return void 0;
423
+ }
392
424
  if (typeof process === "undefined") {
393
425
  return void 0;
394
426
  }
395
- const https = __require("https");
396
- return new https.Agent({
397
- ...customCa ? { ca: customCa } : {},
398
- // rejectUnauthorized is intentionally left at its secure default (true).
399
- ...identity ? { cert: identity.cert, key: identity.key.expose() } : {}
400
- });
427
+ const https = loadNodeHttps();
428
+ return new https.Agent(tls);
401
429
  }
402
430
  function createSession(options) {
403
431
  const tenantHeaderValue = resolveTenantHeaderValue(options);
@@ -720,10 +748,11 @@ var CSRF_COOKIE = "axiam_csrf";
720
748
  function createJar() {
721
749
  return new toughCookie.CookieJar();
722
750
  }
723
- function wrapAxios(instance, jar) {
724
- const wrapped = axiosCookiejarSupport.wrapper(instance);
725
- wrapped.defaults.jar = jar;
726
- return wrapped;
751
+ function wrapAxios(instance, jar, tls) {
752
+ const cookies = { jar };
753
+ instance.defaults.httpAgent = new http.HttpCookieAgent({ cookies });
754
+ instance.defaults.httpsAgent = new http.HttpsCookieAgent({ cookies, ...tls ?? {} });
755
+ return instance;
727
756
  }
728
757
  async function extractCookieValue(jar, url, name) {
729
758
  const cookies = await jar.getCookies(url);
@@ -893,6 +922,7 @@ function checkIdTokenClaims(claims, expectations, nowSec = Math.floor(Date.now()
893
922
  var JWKS_PATH = "/oauth2/jwks";
894
923
  var COOLDOWN_DURATION_MS = 6e4;
895
924
  var TIMEOUT_DURATION_MS = 5e3;
925
+ var CLOCK_SKEW_LEEWAY_SEC = 60;
896
926
  function createVerifier(baseUrl) {
897
927
  return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);
898
928
  }
@@ -910,7 +940,20 @@ function createJwksVerifier(jwksUri) {
910
940
  return jwksPromise;
911
941
  }
912
942
  return {
913
- async verifyAccessToken(token) {
943
+ async verifyAccessToken(token, expectations) {
944
+ const { jwtVerify } = await import('jose');
945
+ const jwks = await getJwks();
946
+ const { payload } = await jwtVerify(token, jwks, {
947
+ algorithms: ["EdDSA"],
948
+ requiredClaims: ["exp"],
949
+ clockTolerance: CLOCK_SKEW_LEEWAY_SEC,
950
+ ...expectations.expectedIssuer !== void 0 ? { issuer: expectations.expectedIssuer } : {},
951
+ ...expectations.expectedAudience !== void 0 ? { audience: expectations.expectedAudience } : {}
952
+ });
953
+ assertTenantClaim(payload.tenant_id, expectations.expectedTenantId);
954
+ return payload;
955
+ },
956
+ async verifySignatureOnlyUnchecked(token) {
914
957
  const { jwtVerify } = await import('jose');
915
958
  const jwks = await getJwks();
916
959
  const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
@@ -944,6 +987,30 @@ function createJwksVerifier(jwksUri) {
944
987
  }
945
988
  };
946
989
  }
990
+ function assertTenantClaim(claim, expected) {
991
+ if (typeof expected !== "string" || expected === "") {
992
+ throw new AuthError(
993
+ "no configured tenant to verify the token against; refusing the request (CONTRACT.md \xA710.1 rule 4 fails closed)"
994
+ );
995
+ }
996
+ if (typeof claim !== "string" || claim === "") {
997
+ throw new AuthError("invalid tenant_id claim");
998
+ }
999
+ if (claim !== expected) {
1000
+ warnOnceIfComparandLooksLikeASlug(claim, expected);
1001
+ throw new AuthError("token tenant_id does not match configured tenant");
1002
+ }
1003
+ }
1004
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1005
+ var slugComparandWarned = false;
1006
+ function warnOnceIfComparandLooksLikeASlug(claim, expected) {
1007
+ if (slugComparandWarned) return;
1008
+ if (!UUID_RE.test(claim) || UUID_RE.test(expected)) return;
1009
+ slugComparandWarned = true;
1010
+ console.warn(
1011
+ `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.)`
1012
+ );
1013
+ }
947
1014
  function mapJoseVerifyError(err) {
948
1015
  const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
949
1016
  switch (code) {
@@ -1021,7 +1088,7 @@ var NodeSession = class extends SharedSession {
1021
1088
  function createNodeSession(options) {
1022
1089
  const base = createSession(options);
1023
1090
  const jar = createJar();
1024
- wrapAxios(base.axios, jar);
1091
+ wrapAxios(base.axios, jar, resolveNodeTlsOptions(options));
1025
1092
  const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
1026
1093
  const jwksVerifier = createVerifier(options.baseUrl);
1027
1094
  return new NodeSession(options, base, tokenManager, jwksVerifier, jar);
@@ -1057,7 +1124,7 @@ var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
1057
1124
  "code_challenge",
1058
1125
  "code_challenge_method"
1059
1126
  ]);
1060
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1127
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1061
1128
  var DiscoveryCache = class {
1062
1129
  #documents = /* @__PURE__ */ new Map();
1063
1130
  #inFlight = /* @__PURE__ */ new Map();
@@ -1560,7 +1627,7 @@ var OidcClient = class {
1560
1627
  "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)."
1561
1628
  );
1562
1629
  }
1563
- if (!UUID_RE.test(candidate)) {
1630
+ if (!UUID_RE2.test(candidate)) {
1564
1631
  throw new AuthError(
1565
1632
  "tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted (CONTRACT.md \xA712.3 rule 4)."
1566
1633
  );
@@ -1707,11 +1774,107 @@ var MemoryOidcStateStore = class {
1707
1774
  }
1708
1775
  }
1709
1776
  };
1777
+ var DEFAULT_WEBHOOK_TOLERANCE_SEC = 300;
1778
+ var WebhookVerifyError = class _WebhookVerifyError extends Error {
1779
+ /** Stable reason code — see {@link WebhookVerifyFailureReason}. */
1780
+ reason;
1781
+ constructor(reason, message) {
1782
+ super(message);
1783
+ this.name = "WebhookVerifyError";
1784
+ this.reason = reason;
1785
+ Object.setPrototypeOf(this, _WebhookVerifyError.prototype);
1786
+ }
1787
+ };
1788
+ function fail(reason, message) {
1789
+ throw new WebhookVerifyError(reason, message);
1790
+ }
1791
+ var STRICT_HEX_PATTERN = /^[0-9a-fA-F]+$/;
1792
+ var STRICT_INTEGER_PATTERN = /^-?\d+$/;
1793
+ function parseSignatureHeader(header) {
1794
+ let t;
1795
+ let tCount = 0;
1796
+ const v1 = [];
1797
+ for (const rawPair of header.split(",")) {
1798
+ const pair = rawPair.trim();
1799
+ if (pair.length === 0) continue;
1800
+ const eq = pair.indexOf("=");
1801
+ if (eq === -1) continue;
1802
+ const key = pair.slice(0, eq).trim();
1803
+ const value = pair.slice(eq + 1).trim();
1804
+ if (key === "t") {
1805
+ t = value;
1806
+ tCount += 1;
1807
+ } else if (key === "v1") {
1808
+ v1.push(value);
1809
+ }
1810
+ }
1811
+ if (tCount !== 1 || t === void 0) {
1812
+ fail("malformed_header", 'signature header must carry exactly one "t" field');
1813
+ }
1814
+ if (v1.length === 0) {
1815
+ fail("malformed_header", 'signature header carries no "v1" field');
1816
+ }
1817
+ return { t, v1 };
1818
+ }
1819
+ function verifyWebhook(secret, signatureHeader, body, options = {}) {
1820
+ const { t, v1 } = parseSignatureHeader(signatureHeader);
1821
+ if (!STRICT_INTEGER_PATTERN.test(t)) {
1822
+ fail("invalid_timestamp", 'signature header "t" is not an integer');
1823
+ }
1824
+ const timestamp = Number(t);
1825
+ if (!Number.isFinite(timestamp)) {
1826
+ fail("invalid_timestamp", 'signature header "t" is out of range');
1827
+ }
1828
+ const rawBody = typeof body === "string" ? Buffer.from(body, "utf8") : Buffer.from(body);
1829
+ const secretBytes = Buffer.from(secret.expose(), "utf8");
1830
+ const signedPayload = Buffer.concat([Buffer.from(`${t}.`, "utf8"), rawBody]);
1831
+ const expected = crypto.createHmac("sha256", secretBytes).update(signedPayload).digest();
1832
+ let matched = false;
1833
+ for (const candidate of v1) {
1834
+ if (!STRICT_HEX_PATTERN.test(candidate) || candidate.length % 2 !== 0) {
1835
+ continue;
1836
+ }
1837
+ const candidateBytes = Buffer.from(candidate, "hex");
1838
+ if (candidateBytes.length !== expected.length) continue;
1839
+ if (crypto.timingSafeEqual(candidateBytes, expected)) {
1840
+ matched = true;
1841
+ break;
1842
+ }
1843
+ }
1844
+ if (!matched) {
1845
+ fail("signature_mismatch", "no v1 signature in the header matched the computed HMAC");
1846
+ }
1847
+ const nowSec = options.now ?? Math.floor(Date.now() / 1e3);
1848
+ const tolerance = options.tolerance ?? DEFAULT_WEBHOOK_TOLERANCE_SEC;
1849
+ const age = nowSec - timestamp;
1850
+ if (age > tolerance) {
1851
+ fail("stale_timestamp", `timestamp is ${age}s old, outside the ${tolerance}s tolerance`);
1852
+ }
1853
+ if (-age > tolerance) {
1854
+ fail("future_timestamp", `timestamp is ${-age}s in the future, outside the ${tolerance}s tolerance`);
1855
+ }
1856
+ let parsedBody;
1857
+ let event;
1858
+ let id;
1859
+ try {
1860
+ parsedBody = JSON.parse(rawBody.toString("utf8"));
1861
+ if (parsedBody !== null && typeof parsedBody === "object") {
1862
+ const obj = parsedBody;
1863
+ if (typeof obj.event === "string") event = obj.event;
1864
+ if (typeof obj.id === "string") id = obj.id;
1865
+ }
1866
+ } catch {
1867
+ parsedBody = void 0;
1868
+ }
1869
+ return { event, id, timestamp, body: parsedBody, rawBody };
1870
+ }
1710
1871
 
1711
1872
  exports.ACCESS_COOKIE = ACCESS_COOKIE;
1873
+ exports.CLOCK_SKEW_LEEWAY_SEC = CLOCK_SKEW_LEEWAY_SEC;
1712
1874
  exports.CODE_CHALLENGE_METHOD_S256 = CODE_CHALLENGE_METHOD_S256;
1713
1875
  exports.CSPRNG_BYTES = CSPRNG_BYTES;
1714
1876
  exports.CSRF_COOKIE = CSRF_COOKIE;
1877
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SEC = DEFAULT_WEBHOOK_TOLERANCE_SEC;
1715
1878
  exports.DISCOVERY_PATH = DISCOVERY_PATH;
1716
1879
  exports.ID_TOKEN_ALG = ID_TOKEN_ALG;
1717
1880
  exports.JWKS_PATH = JWKS_PATH;
@@ -1724,7 +1887,10 @@ exports.OidcClient = OidcClient;
1724
1887
  exports.REFRESH_COOKIE = REFRESH_COOKIE;
1725
1888
  exports.SSO_CALLBACK_PATH = SSO_CALLBACK_PATH;
1726
1889
  exports.SSO_START_PATH = SSO_START_PATH;
1890
+ exports.Sensitive = Sensitive;
1727
1891
  exports.TokenManager = TokenManager;
1892
+ exports.WebhookVerifyError = WebhookVerifyError;
1893
+ exports.assertTenantClaim = assertTenantClaim;
1728
1894
  exports.computeCodeChallenge = computeCodeChallenge;
1729
1895
  exports.createJar = createJar;
1730
1896
  exports.createJwksVerifier = createJwksVerifier;
@@ -1736,6 +1902,7 @@ exports.extractCookieValue = extractCookieValue;
1736
1902
  exports.generateCodeVerifier = generateCodeVerifier;
1737
1903
  exports.normalizeOrigin = normalizeOrigin;
1738
1904
  exports.randomUrlSafeToken = randomUrlSafeToken;
1905
+ exports.verifyWebhook = verifyWebhook;
1739
1906
  exports.wrapAxios = wrapAxios;
1740
1907
  //# sourceMappingURL=index.js.map
1741
1908
  //# sourceMappingURL=index.js.map