axiam-sdk 1.0.0-alpha

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 (45) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +231 -0
  3. package/dist/amqp/index.d.cts +246 -0
  4. package/dist/amqp/index.d.ts +246 -0
  5. package/dist/amqp/index.js +179 -0
  6. package/dist/amqp/index.js.map +1 -0
  7. package/dist/amqp/index.mjs +166 -0
  8. package/dist/amqp/index.mjs.map +1 -0
  9. package/dist/client-B2SB-C7c.d.cts +207 -0
  10. package/dist/client-B2SB-C7c.d.ts +207 -0
  11. package/dist/grpc/index.d.cts +106 -0
  12. package/dist/grpc/index.d.ts +106 -0
  13. package/dist/grpc/index.js +908 -0
  14. package/dist/grpc/index.js.map +1 -0
  15. package/dist/grpc/index.mjs +868 -0
  16. package/dist/grpc/index.mjs.map +1 -0
  17. package/dist/index.d.cts +3 -0
  18. package/dist/index.d.ts +3 -0
  19. package/dist/index.js +561 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/index.mjs +552 -0
  22. package/dist/index.mjs.map +1 -0
  23. package/dist/jwks-CX-nhD6A.d.cts +29 -0
  24. package/dist/jwks-CX-nhD6A.d.ts +29 -0
  25. package/dist/middleware/index.d.cts +153 -0
  26. package/dist/middleware/index.d.ts +153 -0
  27. package/dist/middleware/index.js +232 -0
  28. package/dist/middleware/index.js.map +1 -0
  29. package/dist/middleware/index.mjs +220 -0
  30. package/dist/middleware/index.mjs.map +1 -0
  31. package/dist/node/index.d.cts +103 -0
  32. package/dist/node/index.d.ts +103 -0
  33. package/dist/node/index.js +717 -0
  34. package/dist/node/index.js.map +1 -0
  35. package/dist/node/index.mjs +700 -0
  36. package/dist/node/index.mjs.map +1 -0
  37. package/dist/rest/index.d.cts +27 -0
  38. package/dist/rest/index.d.ts +27 -0
  39. package/dist/rest/index.js +561 -0
  40. package/dist/rest/index.js.map +1 -0
  41. package/dist/rest/index.mjs +552 -0
  42. package/dist/rest/index.mjs.map +1 -0
  43. package/dist/sensitive-CWBH_tHr.d.cts +12 -0
  44. package/dist/sensitive-CWBH_tHr.d.ts +12 -0
  45. package/package.json +145 -0
@@ -0,0 +1,700 @@
1
+ import axios from 'axios';
2
+ import { CookieJar } from 'tough-cookie';
3
+ import { wrapper } from 'axios-cookiejar-support';
4
+
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+
12
+ // src/core/errors.ts
13
+ var AxiamError = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ Object.setPrototypeOf(this, new.target.prototype);
17
+ }
18
+ };
19
+ var AuthError = class _AuthError extends AxiamError {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "AuthError";
23
+ Object.setPrototypeOf(this, _AuthError.prototype);
24
+ }
25
+ };
26
+ var AuthzError = class _AuthzError extends AxiamError {
27
+ action;
28
+ resourceId;
29
+ constructor(message, action, resourceId) {
30
+ super(message);
31
+ this.name = "AuthzError";
32
+ this.action = action;
33
+ this.resourceId = resourceId;
34
+ Object.setPrototypeOf(this, _AuthzError.prototype);
35
+ }
36
+ };
37
+ var NetworkError = class _NetworkError extends AxiamError {
38
+ cause;
39
+ constructor(message, cause) {
40
+ super(message);
41
+ this.name = "NetworkError";
42
+ this.cause = cause;
43
+ Object.setPrototypeOf(this, _NetworkError.prototype);
44
+ }
45
+ };
46
+
47
+ // src/core/errorMapper.ts
48
+ function extractAuthzFieldsFromBody(body) {
49
+ if (body === null || typeof body !== "object") {
50
+ return {};
51
+ }
52
+ const record = body;
53
+ const action = typeof record.action === "string" ? record.action : void 0;
54
+ const resourceId = typeof record.resource_id === "string" ? record.resource_id : void 0;
55
+ return { action, resourceId };
56
+ }
57
+ var SAFE_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
58
+ "content-type",
59
+ "content-length",
60
+ "date",
61
+ "server",
62
+ "retry-after",
63
+ "x-request-id",
64
+ "x-tenant-id"
65
+ ]);
66
+ var REDACTED_HEADER = "[REDACTED]";
67
+ function sanitizeAxiosError(err) {
68
+ if (err === null || typeof err !== "object") {
69
+ return err;
70
+ }
71
+ const candidate = err;
72
+ if (candidate.response === null || typeof candidate.response !== "object") {
73
+ return err;
74
+ }
75
+ const response = candidate.response;
76
+ if (response.headers === null || typeof response.headers !== "object") {
77
+ return err;
78
+ }
79
+ const sanitizedHeaders = { ...response.headers };
80
+ for (const key of Object.keys(sanitizedHeaders)) {
81
+ if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {
82
+ sanitizedHeaders[key] = REDACTED_HEADER;
83
+ }
84
+ }
85
+ return {
86
+ ...err,
87
+ response: {
88
+ ...response,
89
+ headers: sanitizedHeaders
90
+ }
91
+ };
92
+ }
93
+ function mapHttpStatusToError(status, message, ctx) {
94
+ if (status === 401) {
95
+ return new AuthError(message);
96
+ }
97
+ if (status === 403 || status === 409) {
98
+ const fromBody = extractAuthzFieldsFromBody(ctx?.body);
99
+ return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);
100
+ }
101
+ return new NetworkError(message, sanitizeAxiosError(ctx?.cause));
102
+ }
103
+
104
+ // src/core/sensitive.ts
105
+ var REDACTED = "[SENSITIVE]";
106
+ var NODE_INSPECT_CUSTOM = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
107
+ var Sensitive = class {
108
+ #value;
109
+ constructor(value) {
110
+ this.#value = value;
111
+ }
112
+ /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */
113
+ expose() {
114
+ return this.#value;
115
+ }
116
+ toString() {
117
+ return REDACTED;
118
+ }
119
+ toJSON() {
120
+ return REDACTED;
121
+ }
122
+ [NODE_INSPECT_CUSTOM]() {
123
+ return REDACTED;
124
+ }
125
+ };
126
+
127
+ // src/core/csrf.ts
128
+ var CSRF_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
129
+ var CSRF_COOKIE_REGEX = /(?:^|;\s*)axiam_csrf=([^;]*)/;
130
+ function readCsrfCookie(cookieString) {
131
+ const match = CSRF_COOKIE_REGEX.exec(cookieString);
132
+ if (!match) {
133
+ return null;
134
+ }
135
+ return decodeURIComponent(match[1]);
136
+ }
137
+ function csrfHeaderForMethod(method, cookieString) {
138
+ if (!CSRF_METHODS.has(method.toLowerCase())) {
139
+ return void 0;
140
+ }
141
+ const token = readCsrfCookie(cookieString);
142
+ return token ?? void 0;
143
+ }
144
+
145
+ // src/core/singleFlightRefresh.ts
146
+ function createRefreshGuard() {
147
+ let refreshPromise = null;
148
+ const guard = ((doRefresh) => {
149
+ if (!refreshPromise) {
150
+ refreshPromise = doRefresh().finally(() => {
151
+ refreshPromise = null;
152
+ });
153
+ }
154
+ return refreshPromise;
155
+ });
156
+ guard.__reset = () => {
157
+ refreshPromise = null;
158
+ };
159
+ return guard;
160
+ }
161
+ createRefreshGuard();
162
+
163
+ // src/core/config.ts
164
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
165
+
166
+ // src/rest/session.ts
167
+ var PEM_MARKER = "-----BEGIN CERTIFICATE-----";
168
+ var SharedSession = class {
169
+ /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */
170
+ axios;
171
+ /** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */
172
+ baseUrl;
173
+ /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */
174
+ tenantHeaderValue;
175
+ /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */
176
+ csrfToken;
177
+ /** Set true once a successful login/verifyMfa has completed. */
178
+ authenticated = false;
179
+ /**
180
+ * Per-instance single-flight refresh guard (CR-02, D-13). Shared across
181
+ * this session's REST and gRPC transports (rest/interceptors.ts,
182
+ * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but
183
+ * NEVER shared with a different SharedSession/NodeSession instance.
184
+ *
185
+ * @internal SDK-internal transport wiring, not intended to be invoked
186
+ * directly by SDK consumers — refreshes are driven automatically by the
187
+ * response interceptor (rest) or `callWithRefresh` (grpc).
188
+ */
189
+ refreshGuard;
190
+ constructor(options, axiosInstance, tenantHeaderValue) {
191
+ this.axios = axiosInstance;
192
+ this.baseUrl = options.baseUrl;
193
+ this.tenantHeaderValue = tenantHeaderValue;
194
+ this.refreshGuard = createRefreshGuard();
195
+ }
196
+ /**
197
+ * Host-isolation guard (3A, defense in depth): returns `true` when `url`
198
+ * targets a host other than this session's base origin — an absolute
199
+ * third-party URL, or a redirect that axios/the browser resolved off-origin.
200
+ * The tenant identifier and CSRF token must never be attached to such a
201
+ * request. A relative/host-less `url` (the normal case, merged against
202
+ * `baseUrl`) is same-origin and returns `false`. Mirrors the Python SDK's
203
+ * `_prepare_request` guard. Malformed input fails closed (treated as
204
+ * foreign).
205
+ */
206
+ isForeignHost(url) {
207
+ if (!url) {
208
+ return false;
209
+ }
210
+ try {
211
+ const target = new URL(url, this.baseUrl);
212
+ return target.host !== new URL(this.baseUrl).host;
213
+ } catch {
214
+ return true;
215
+ }
216
+ }
217
+ };
218
+ function resolveTenantHeaderValue(options) {
219
+ if (options.tenantSlug) {
220
+ return options.tenantSlug;
221
+ }
222
+ if (options.tenantId) {
223
+ return options.tenantId;
224
+ }
225
+ throw new Error(
226
+ "AxiamClient construction requires a tenant: provide either tenantSlug or tenantId (CONTRACT.md \xA75)."
227
+ );
228
+ }
229
+ function maybeBuildHttpsAgent(customCa) {
230
+ if (!customCa) {
231
+ return void 0;
232
+ }
233
+ if (!customCa.includes(PEM_MARKER)) {
234
+ throw new Error(
235
+ 'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
236
+ );
237
+ }
238
+ if (typeof process === "undefined") {
239
+ return void 0;
240
+ }
241
+ const https = __require("https");
242
+ return new https.Agent({ ca: customCa });
243
+ }
244
+ function createSession(options) {
245
+ const tenantHeaderValue = resolveTenantHeaderValue(options);
246
+ if (options.customCa !== void 0 && !options.customCa.includes(PEM_MARKER)) {
247
+ throw new Error(
248
+ 'customCa must be a PEM-encoded certificate (expected to contain "-----BEGIN CERTIFICATE-----") (CONTRACT.md \xA76).'
249
+ );
250
+ }
251
+ const httpsAgent = maybeBuildHttpsAgent(options.customCa);
252
+ const axiosInstance = axios.create({
253
+ baseURL: options.baseUrl,
254
+ withCredentials: true,
255
+ timeout: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
256
+ ...httpsAgent ? { httpsAgent } : {}
257
+ });
258
+ const session = new SharedSession(options, axiosInstance, tenantHeaderValue);
259
+ axiosInstance.interceptors.request.use((config) => {
260
+ if (session.isForeignHost(config.url)) {
261
+ return config;
262
+ }
263
+ config.headers = config.headers ?? {};
264
+ config.headers["X-Tenant-ID"] = session.tenantHeaderValue;
265
+ return config;
266
+ });
267
+ return session;
268
+ }
269
+
270
+ // src/rest/interceptors.ts
271
+ var SKIP_REFRESH = ["/api/v1/auth/refresh", "/api/v1/auth/login", "/api/v1/auth/logout"];
272
+ function installCsrfInterceptor(axiosInstance, session) {
273
+ axiosInstance.interceptors.request.use((config) => {
274
+ if (session.isForeignHost(config.url)) {
275
+ return config;
276
+ }
277
+ const method = (config.method ?? "get").toLowerCase();
278
+ const cookieString = typeof document !== "undefined" ? document.cookie : "";
279
+ const csrfToken = typeof document !== "undefined" ? csrfHeaderForMethod(method, cookieString) : csrfHeaderForMethod(method, session.csrfToken ? `axiam_csrf=${session.csrfToken}` : "");
280
+ if (csrfToken) {
281
+ config.headers = config.headers ?? {};
282
+ config.headers["X-CSRF-Token"] = csrfToken;
283
+ }
284
+ return config;
285
+ });
286
+ }
287
+ function installRefreshInterceptor(axiosInstance, session) {
288
+ axiosInstance.interceptors.response.use(
289
+ (response) => response,
290
+ async (error) => {
291
+ const originalRequest = error.config;
292
+ if (!originalRequest || !error.response) {
293
+ return Promise.reject(error);
294
+ }
295
+ const status = error.response.status;
296
+ const url = originalRequest.url ?? "";
297
+ const isSkipRefresh = SKIP_REFRESH.some((skipUrl) => url.includes(skipUrl));
298
+ if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated) {
299
+ originalRequest._retry = true;
300
+ try {
301
+ await session.refreshGuard(async () => {
302
+ await session.axios.post("/api/v1/auth/refresh", {});
303
+ });
304
+ return axiosInstance(originalRequest);
305
+ } catch (refreshError) {
306
+ session.authenticated = false;
307
+ session.csrfToken = void 0;
308
+ return Promise.reject(
309
+ mapHttpStatusToError(401, "session refresh failed; re-authentication required", {
310
+ cause: refreshError
311
+ })
312
+ );
313
+ }
314
+ }
315
+ if (status === 401 && isSkipRefresh) {
316
+ return Promise.reject(mapHttpStatusToError(401, "authentication failed"));
317
+ }
318
+ return Promise.reject(error);
319
+ }
320
+ );
321
+ }
322
+ function installInterceptors(axiosInstance, session) {
323
+ installCsrfInterceptor(axiosInstance, session);
324
+ installRefreshInterceptor(axiosInstance, session);
325
+ }
326
+
327
+ // src/rest/auth.ts
328
+ var LOGIN_PATH = "/api/v1/auth/login";
329
+ var MFA_VERIFY_PATH = "/api/v1/auth/mfa/verify";
330
+ var REFRESH_PATH = "/api/v1/auth/refresh";
331
+ var LOGOUT_PATH = "/api/v1/auth/logout";
332
+ function loginSuccessToResult(wire) {
333
+ return {
334
+ status: "authenticated",
335
+ user: { id: wire.user.id, username: wire.user.username, email: wire.user.email },
336
+ sessionId: wire.session_id,
337
+ expiresIn: wire.expires_in
338
+ };
339
+ }
340
+ function mfaRequiredToResult(wire) {
341
+ return {
342
+ status: "mfa_required",
343
+ mfaToken: wire.challenge_token,
344
+ availableMethods: wire.available_methods
345
+ };
346
+ }
347
+ function extractErrorMessage(err) {
348
+ if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
349
+ return err.message;
350
+ }
351
+ return "request failed";
352
+ }
353
+ async function login(client, email, password) {
354
+ const body = { username_or_email: email, password };
355
+ try {
356
+ const response = await client.session.axios.post(
357
+ LOGIN_PATH,
358
+ body
359
+ );
360
+ if (response.status === 202) {
361
+ return mfaRequiredToResult(response.data);
362
+ }
363
+ client.session.authenticated = true;
364
+ await client.session.onAuthenticated?.();
365
+ return loginSuccessToResult(response.data);
366
+ } catch (err) {
367
+ const status = extractAxiosStatus(err);
368
+ if (status !== void 0) {
369
+ throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? "login failed", {
370
+ cause: err
371
+ });
372
+ }
373
+ throw new NetworkError("login request failed", sanitizeAxiosError(err));
374
+ }
375
+ }
376
+ async function verifyMfa(client, mfaToken, code) {
377
+ const body = { challenge_token: mfaToken, totp_code: code };
378
+ try {
379
+ const response = await client.session.axios.post(MFA_VERIFY_PATH, body);
380
+ client.session.authenticated = true;
381
+ await client.session.onAuthenticated?.();
382
+ return loginSuccessToResult(response.data);
383
+ } catch (err) {
384
+ const status = extractAxiosStatus(err);
385
+ if (status !== void 0) {
386
+ throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? "verifyMfa failed", {
387
+ cause: err
388
+ });
389
+ }
390
+ throw new NetworkError("verifyMfa request failed", sanitizeAxiosError(err));
391
+ }
392
+ }
393
+ async function refresh(client) {
394
+ try {
395
+ await client.session.axios.post(REFRESH_PATH, {});
396
+ } catch (err) {
397
+ const status = extractAxiosStatus(err);
398
+ if (status !== void 0) {
399
+ throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? "refresh failed", {
400
+ cause: err
401
+ });
402
+ }
403
+ throw new NetworkError("refresh request failed", sanitizeAxiosError(err));
404
+ }
405
+ }
406
+ async function logout(client) {
407
+ try {
408
+ await client.session.axios.post(LOGOUT_PATH, {});
409
+ } catch (err) {
410
+ const status = extractAxiosStatus(err);
411
+ if (status !== void 0) {
412
+ throw mapHttpStatusToError(status, extractErrorMessage(extractAxiosData(err)) ?? "logout failed", {
413
+ cause: err
414
+ });
415
+ }
416
+ throw new NetworkError("logout request failed", sanitizeAxiosError(err));
417
+ } finally {
418
+ client.session.authenticated = false;
419
+ client.session.csrfToken = void 0;
420
+ }
421
+ }
422
+ function extractAxiosStatus(err) {
423
+ if (err && typeof err === "object" && "response" in err) {
424
+ const response = err.response;
425
+ return response?.status;
426
+ }
427
+ return void 0;
428
+ }
429
+ function extractAxiosData(err) {
430
+ if (err && typeof err === "object" && "response" in err) {
431
+ const response = err.response;
432
+ return response?.data;
433
+ }
434
+ return void 0;
435
+ }
436
+
437
+ // src/rest/authz.ts
438
+ var CHECK_PATH = "/api/v1/authz/check";
439
+ var BATCH_CHECK_PATH = "/api/v1/authz/check/batch";
440
+ function toWireBody(check) {
441
+ return {
442
+ action: check.action,
443
+ resource_id: check.resourceId,
444
+ scope: check.scope,
445
+ subject_id: check.subjectId
446
+ };
447
+ }
448
+ function fromWireDecision(wire) {
449
+ return { allowed: wire.allowed, reason: wire.reason };
450
+ }
451
+ async function checkAccess(client, check) {
452
+ try {
453
+ const response = await client.session.axios.post(CHECK_PATH, toWireBody(check));
454
+ return fromWireDecision(response.data);
455
+ } catch (err) {
456
+ throw mapAuthzError(err, check.action, check.resourceId);
457
+ }
458
+ }
459
+ async function can(client, action, resourceId, scope) {
460
+ const decision = await checkAccess(client, { action, resourceId, scope });
461
+ return decision.allowed;
462
+ }
463
+ async function batchCheck(client, checks) {
464
+ const body = { checks: checks.map(toWireBody) };
465
+ try {
466
+ const response = await client.session.axios.post(BATCH_CHECK_PATH, body);
467
+ return response.data.results.map(fromWireDecision);
468
+ } catch (err) {
469
+ throw mapAuthzError(err);
470
+ }
471
+ }
472
+ function mapAuthzError(err, action, resourceId) {
473
+ if (err && typeof err === "object" && "response" in err) {
474
+ const response = err.response;
475
+ if (response?.status !== void 0) {
476
+ if (response.status === 403) {
477
+ return mapHttpStatusToError(403, response.data?.message ?? "authorization denied", {
478
+ action,
479
+ resourceId,
480
+ body: response.data
481
+ });
482
+ }
483
+ return mapHttpStatusToError(response.status, response.data?.message ?? "authz request failed", {
484
+ action,
485
+ resourceId,
486
+ body: response.data,
487
+ cause: err
488
+ });
489
+ }
490
+ }
491
+ return new NetworkError("authz request failed", err);
492
+ }
493
+
494
+ // src/rest/client.ts
495
+ var AxiamClient = class {
496
+ /** @internal — exposed for auth.ts/authz.ts method implementations and other transports (D-13). */
497
+ session;
498
+ /**
499
+ * @param options client configuration (§5/§6).
500
+ * @param session optional pre-built session to adopt instead of the default
501
+ * browser `SharedSession`. This is the injection point for the Node
502
+ * persona (SDK-Q05): a Node REST consumer builds a `NodeSession` (cookie
503
+ * jar + CSRF/refresh token sync) via `createNodeClient`/`createNodeSession`
504
+ * from the Node-only `axiam-sdk/node` (or `axiam-sdk/grpc`) subpath and it
505
+ * is adopted here, so httpOnly login/refresh cookies persist. When omitted
506
+ * the browser `SharedSession` is built by default — the Node modules are
507
+ * NEVER statically imported from this browser-safe module, so a `/rest`
508
+ * browser bundle keeps pulling zero Node dependencies (SC#1).
509
+ */
510
+ constructor(options, session) {
511
+ this.session = session ?? createSession(options);
512
+ installInterceptors(this.session.axios, this.session);
513
+ }
514
+ /** `POST /api/v1/auth/login` (§1, D-18). */
515
+ login(email, password) {
516
+ return login(this, email, password);
517
+ }
518
+ /** `POST /api/v1/auth/mfa/verify` (§1, D-18). Completes the two-phase flow started by login(). */
519
+ verifyMfa(mfaToken, code) {
520
+ return verifyMfa(this, mfaToken, code);
521
+ }
522
+ /** `POST /api/v1/auth/refresh` (§1). Usually driven reactively by the response interceptor (D-07). */
523
+ refresh() {
524
+ return refresh(this);
525
+ }
526
+ /** `POST /api/v1/auth/logout` (§1). Clears session csrf/auth state. */
527
+ logout() {
528
+ return logout(this);
529
+ }
530
+ /** `POST /api/v1/authz/check` (§1, FND-04). */
531
+ checkAccess(check) {
532
+ return checkAccess(this, check);
533
+ }
534
+ /** `can` — alias for checkAccess targeting browser/UI scenarios (§1 note). */
535
+ can(action, resourceId, scope) {
536
+ return can(this, action, resourceId, scope);
537
+ }
538
+ /** `POST /api/v1/authz/check/batch` (§1). Results preserve input order. */
539
+ batchCheck(checks) {
540
+ return batchCheck(this, checks);
541
+ }
542
+ };
543
+ var ACCESS_COOKIE = "axiam_access";
544
+ var REFRESH_COOKIE = "axiam_refresh";
545
+ var CSRF_COOKIE = "axiam_csrf";
546
+ function createJar() {
547
+ return new CookieJar();
548
+ }
549
+ function wrapAxios(instance, jar) {
550
+ const wrapped = wrapper(instance);
551
+ wrapped.defaults.jar = jar;
552
+ return wrapped;
553
+ }
554
+ async function extractCookieValue(jar, url, name) {
555
+ const cookies = await jar.getCookies(url);
556
+ return cookies.find((c) => c.key === name)?.value;
557
+ }
558
+
559
+ // src/node/tokenManager.ts
560
+ var REFRESH_COOKIE_PATH = "/api/v1/auth/refresh";
561
+ var TokenManager = class {
562
+ #jar;
563
+ #baseUrl;
564
+ #tenantId;
565
+ /**
566
+ * Non-blocking cached copy of the current access token, kept in sync via
567
+ * `syncFromJar()` after each REST call/refresh. Read via
568
+ * `cachedAccessToken()` without ever touching the jar's async API — this
569
+ * is the fast-path the grpc-js interceptor's synchronous `start()` needs
570
+ * (Pitfall 3).
571
+ */
572
+ #cachedAccess = null;
573
+ constructor(jar, baseUrl, tenantId) {
574
+ this.#jar = jar;
575
+ this.#baseUrl = baseUrl;
576
+ this.#tenantId = tenantId;
577
+ }
578
+ /**
579
+ * Synchronous, best-effort read of the last-known access token. Returns
580
+ * `null` if no token has been cached yet (no request/refresh has
581
+ * completed since construction, or `syncFromJar()` was never called).
582
+ */
583
+ cachedAccessToken() {
584
+ return this.#cachedAccess;
585
+ }
586
+ /**
587
+ * Async read of the current `axiam_refresh` cookie value from the jar,
588
+ * wrapped in Sensitive<T>. Queried against the refresh endpoint's URL
589
+ * since the cookie is path-scoped to `/api/v1/auth/refresh` (not visible
590
+ * at the bare base URL).
591
+ */
592
+ async refreshTokenValue() {
593
+ const value = await extractCookieValue(this.#jar, `${this.#baseUrl}${REFRESH_COOKIE_PATH}`, REFRESH_COOKIE);
594
+ return value === void 0 ? null : new Sensitive(value);
595
+ }
596
+ /**
597
+ * Refresh the in-memory cached access token from the jar. Call this after
598
+ * every REST request/refresh so the synchronous gRPC-interceptor fast-path
599
+ * (`cachedAccessToken()`) stays current (Pitfall 3).
600
+ */
601
+ async syncFromJar() {
602
+ const value = await extractCookieValue(this.#jar, this.#baseUrl, ACCESS_COOKIE);
603
+ this.#cachedAccess = value === void 0 ? null : new Sensitive(value);
604
+ }
605
+ /** The resolved tenant identifier (slug or UUID form), if known. */
606
+ tenantId() {
607
+ return this.#tenantId;
608
+ }
609
+ /** Set/update the resolved tenant identifier (e.g. after decoding the access token's tenant_id claim). */
610
+ setTenantId(tenantId) {
611
+ this.#tenantId = tenantId;
612
+ }
613
+ /** Clear all cached token state (used by logout()). */
614
+ clear() {
615
+ this.#cachedAccess = null;
616
+ }
617
+ };
618
+
619
+ // src/node/jwks.ts
620
+ var JWKS_PATH = "/oauth2/jwks";
621
+ var COOLDOWN_DURATION_MS = 6e4;
622
+ var TIMEOUT_DURATION_MS = 5e3;
623
+ function createVerifier(baseUrl) {
624
+ let jwksPromise = null;
625
+ async function getJwks() {
626
+ if (!jwksPromise) {
627
+ jwksPromise = import('jose').then(
628
+ ({ createRemoteJWKSet }) => createRemoteJWKSet(new URL(`${baseUrl}${JWKS_PATH}`), {
629
+ cooldownDuration: COOLDOWN_DURATION_MS,
630
+ timeoutDuration: TIMEOUT_DURATION_MS
631
+ })
632
+ );
633
+ }
634
+ return jwksPromise;
635
+ }
636
+ return {
637
+ async verifyAccessToken(token) {
638
+ const { jwtVerify } = await import('jose');
639
+ const jwks = await getJwks();
640
+ const { payload } = await jwtVerify(token, jwks, { algorithms: ["EdDSA"] });
641
+ return payload;
642
+ }
643
+ };
644
+ }
645
+
646
+ // src/node/session.ts
647
+ var NodeSession = class extends SharedSession {
648
+ tokenManager;
649
+ jwksVerifier;
650
+ #jar;
651
+ constructor(options, base, tokenManager, jwksVerifier, jar) {
652
+ super(options, base.axios, base.tenantHeaderValue);
653
+ this.tokenManager = tokenManager;
654
+ this.jwksVerifier = jwksVerifier;
655
+ this.#jar = jar;
656
+ }
657
+ /**
658
+ * Drives the actual `POST /api/v1/auth/refresh` HTTP call. Passed to this
659
+ * session's per-instance `refreshGuard` (inherited from SharedSession) by
660
+ * both REST's reactive interceptor (rest/interceptors.ts) and gRPC's
661
+ * callWithRefresh — since `refreshGuard` is scoped to THIS session
662
+ * instance (CR-02, D-13), both transports share exactly one in-flight
663
+ * refresh for this session regardless of which one triggers it, while
664
+ * remaining fully independent from any other session's guard.
665
+ */
666
+ doRefresh = async () => {
667
+ await this.axios.post("/api/v1/auth/refresh", {});
668
+ await this.tokenManager.syncFromJar();
669
+ await this.#syncCsrfFromJar();
670
+ };
671
+ /**
672
+ * Session-level hook (CR-01, D-05) invoked by rest/auth.ts after a
673
+ * successful login()/verifyMfa(). Refreshes the cached access token (so
674
+ * the gRPC interceptor's synchronous fast-path is current immediately
675
+ * after login) and reads the `axiam_csrf` cookie out of the jar into
676
+ * `session.csrfToken`, mirroring TokenManager.syncFromJar()'s pattern.
677
+ */
678
+ onAuthenticated = async () => {
679
+ await this.tokenManager.syncFromJar();
680
+ await this.#syncCsrfFromJar();
681
+ };
682
+ async #syncCsrfFromJar() {
683
+ this.csrfToken = await extractCookieValue(this.#jar, this.baseUrl, CSRF_COOKIE);
684
+ }
685
+ };
686
+ function createNodeSession(options) {
687
+ const base = createSession(options);
688
+ const jar = createJar();
689
+ wrapAxios(base.axios, jar);
690
+ const tokenManager = new TokenManager(jar, options.baseUrl, base.tenantHeaderValue);
691
+ const jwksVerifier = createVerifier(options.baseUrl);
692
+ return new NodeSession(options, base, tokenManager, jwksVerifier, jar);
693
+ }
694
+ function createNodeClient(options) {
695
+ return new AxiamClient(options, createNodeSession(options));
696
+ }
697
+
698
+ export { ACCESS_COOKIE, CSRF_COOKIE, JWKS_PATH, NodeSession, REFRESH_COOKIE, TokenManager, createJar, createNodeClient, createNodeSession, createVerifier, extractCookieValue, wrapAxios };
699
+ //# sourceMappingURL=index.mjs.map
700
+ //# sourceMappingURL=index.mjs.map