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