@authyon/server 0.2.0-beta.3 → 0.2.0-beta.30

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.
package/dist/index.js CHANGED
@@ -1,10 +1,36 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
1
+ import {
2
+ AuthyonError,
3
+ DEFAULT_BASE_URL,
4
+ DEFAULT_EXPIRY_SKEW_MS,
5
+ ErrorCodes,
6
+ FetchHttpAdapter,
7
+ JsonHttpClient,
8
+ LoggingHttpAdapter,
9
+ createSharedTransport
10
+ } from "./chunk-SUL2HLRR.js";
11
+ import {
12
+ AuthorizationError,
13
+ AuthyonAbility,
14
+ AuthyonAbilityBuilder,
15
+ CLIENT_IP_HEADER,
16
+ JwksTokenVerifier,
17
+ TokenVerificationError,
18
+ authorizeRequest,
19
+ authorizeToken,
20
+ clientIpHeaders,
21
+ createAuthorizationErrorResponse,
22
+ createAuthyonAbility,
23
+ createAuthyonRules,
24
+ createExpressAuthorizationMiddleware,
25
+ hasPermission,
26
+ hasPermissionGroup,
27
+ normalizeClientIp
28
+ } from "./chunk-V6JQIOSP.js";
29
+ import {
30
+ __privateAdd,
31
+ __privateGet,
32
+ __privateSet
33
+ } from "./chunk-77J4NURK.js";
8
34
 
9
35
  // src/client/credentialManagement.ts
10
36
  function segment(value) {
@@ -38,6 +64,25 @@ function lifetimeBody(input) {
38
64
  }
39
65
  return { lifetimeDays: input.lifetimeDays };
40
66
  }
67
+ var MAX_PERMISSION_FILTERS = 20;
68
+ var PERMISSION_FILTER = /^(?:\*|[a-z][a-z0-9_-]*)(?::(?:\*|[a-z][a-z0-9_-]*)){2,4}$/u;
69
+ function permissionFilter(values) {
70
+ if (values === void 0) return void 0;
71
+ if (!Array.isArray(values)) throw new TypeError("Authyon: permissions must be an array.");
72
+ const normalized = values.map((value) => {
73
+ if (typeof value !== "string") throw new TypeError("Authyon: invalid permission.");
74
+ return value.trim().toLowerCase();
75
+ });
76
+ const unique = [...new Set(normalized.filter((value) => value.length > 0))];
77
+ if (unique.length > MAX_PERMISSION_FILTERS)
78
+ throw new RangeError(
79
+ `Authyon: at most ${MAX_PERMISSION_FILTERS} permissions can be filtered at once.`
80
+ );
81
+ for (const value of unique)
82
+ if (!PERMISSION_FILTER.test(value))
83
+ throw new TypeError("Authyon: permissions must have namespace:resource:action format.");
84
+ return unique.length > 0 ? unique : void 0;
85
+ }
41
86
  function credentialQuery(options = {}) {
42
87
  const { skip, take, search } = options;
43
88
  if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
@@ -46,7 +91,8 @@ function credentialQuery(options = {}) {
46
91
  throw new RangeError("Authyon: take must be between 1 and 100.");
47
92
  if (search !== void 0 && (typeof search !== "string" || search.trim().length > 200))
48
93
  throw new RangeError("Authyon: search must contain at most 200 characters.");
49
- return { search: search?.trim() || void 0, skip, take };
94
+ const permission = permissionFilter(options.permissions);
95
+ return { search: search?.trim() || void 0, skip, take, permission };
50
96
  }
51
97
  function credentialSummary(value) {
52
98
  return {
@@ -77,28 +123,28 @@ function credentialDetail(value) {
77
123
  accessTokenLifetimeSeconds: value.accessTokenLifetimeSeconds
78
124
  };
79
125
  }
80
- async function credentialPage(request, path, options = {}) {
126
+ async function credentialPage(request, path2, options = {}) {
81
127
  const query = credentialQuery(options);
82
- const page = await request(path, { query });
128
+ const page = await request(path2, { query });
83
129
  if (!page || !Array.isArray(page.data))
84
130
  throw new TypeError("Authyon: expected a paginated credential response.");
85
131
  return {
86
132
  data: page.data.map(credentialSummary),
87
- ...page.perPage === void 0 ? {} : { perPage: page.perPage },
88
- pageSize: page.pageSize,
133
+ page: page.page,
134
+ perPage: page.perPage,
89
135
  total: page.total,
90
136
  pages: page.pages,
91
137
  hasNext: page.hasNext,
92
138
  hasPrev: page.hasPrev
93
139
  };
94
140
  }
95
- async function allCredentials(request, path) {
141
+ async function allCredentials(request, path2) {
96
142
  const result = [];
97
143
  const seen = /* @__PURE__ */ new Set();
98
144
  let skip = 0;
99
145
  for (let iteration = 0; iteration < 1e3; iteration++) {
100
146
  const page = await request(
101
- path,
147
+ path2,
102
148
  iteration === 0 ? {} : { query: { skip, take: 100 } }
103
149
  );
104
150
  if (Array.isArray(page)) {
@@ -121,138 +167,202 @@ async function allCredentials(request, path) {
121
167
  throw new Error("Authyon: use listPage for more than 1000 credential pages.");
122
168
  }
123
169
 
170
+ // ../../internal/core/http/memberQuery.ts
171
+ function memberQuery(options = {}) {
172
+ const { skip, take, search } = options;
173
+ if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
174
+ throw new RangeError("Authyon: invalid skip.");
175
+ if (take !== void 0 && (!Number.isInteger(take) || take < 1 || take > 100))
176
+ throw new RangeError("Authyon: take must be between 1 and 100.");
177
+ if (search !== void 0 && (typeof search !== "string" || search.trim().length > 100))
178
+ throw new RangeError("Authyon: search must contain at most 100 characters.");
179
+ return { search: search?.trim() || void 0, skip, take };
180
+ }
181
+
182
+ // ../../internal/core/http/subTenantQuery.ts
183
+ var ORDER_FIELDS = ["name", "createdAt", "updatedAt"];
184
+ var MAX_FILTERS = 10;
185
+ var MAX_FILTER_LENGTH = 512;
186
+ function orderByParam(order) {
187
+ if (order === void 0) return void 0;
188
+ const field = typeof order === "string" ? order : order?.field;
189
+ const direction = typeof order === "string" ? "asc" : order.direction ?? "asc";
190
+ if (!ORDER_FIELDS.includes(field))
191
+ throw new RangeError(`Authyon: orderBy must be one of ${ORDER_FIELDS.join(", ")}.`);
192
+ if (direction !== "asc" && direction !== "desc")
193
+ throw new RangeError('Authyon: orderBy direction must be "asc" or "desc".');
194
+ return `${field}:${direction}`;
195
+ }
196
+ function subTenantQuery(options = {}) {
197
+ const { filter, orderBy, ...page } = options;
198
+ const query = { ...memberQuery(page) };
199
+ if (filter !== void 0) {
200
+ if (!Array.isArray(filter)) throw new RangeError("Authyon: filter must be an array.");
201
+ const present = filter.filter((f) => typeof f === "string" && f.trim().length > 0);
202
+ if (present.length !== filter.length)
203
+ throw new RangeError("Authyon: a filter may not be empty \u2014 build it with tenantFilter.");
204
+ if (present.length > MAX_FILTERS)
205
+ throw new RangeError(`Authyon: at most ${MAX_FILTERS} filters per request.`);
206
+ for (const f of present) {
207
+ if (f.length > MAX_FILTER_LENGTH)
208
+ throw new RangeError(`Authyon: a filter may hold at most ${MAX_FILTER_LENGTH} characters.`);
209
+ if (!f.startsWith("public."))
210
+ throw new RangeError(
211
+ `Authyon: sub-tenant listings only filter on the public scope (got "${f.split(":")[0]}").`
212
+ );
213
+ }
214
+ if (present.length > 0) query.filter = present;
215
+ }
216
+ const order = orderByParam(orderBy);
217
+ if (order !== void 0) query.orderBy = order;
218
+ return query;
219
+ }
220
+
221
+ // ../../internal/core/security/approvals.ts
222
+ function path(id, suffix = "") {
223
+ if (typeof id !== "string" || !id.trim())
224
+ throw new TypeError("Authyon: an approval id is required.");
225
+ return `/auth/authorizations/${encodeURIComponent(id)}${suffix}`;
226
+ }
227
+ var NO_METHODS = {
228
+ password: false,
229
+ authenticator: false,
230
+ emailCode: false,
231
+ passkey: false,
232
+ passkeyCount: 0,
233
+ recoveryCodes: 0,
234
+ sso: [],
235
+ twoFactor: false
236
+ };
237
+ function subjectSecurity(request) {
238
+ return {
239
+ methods: async () => {
240
+ const me = await request("/auth/me");
241
+ return me.security ?? NO_METHODS;
242
+ },
243
+ approvals: {
244
+ get: (id) => request(path(id)),
245
+ webauthnOptions: (id) => request(path(id, "/webauthn/options"), { method: "POST" }),
246
+ confirm: (id, input) => request(path(id, "/confirm"), { method: "POST", body: input }),
247
+ reject: (id) => request(path(id, "/reject"), { method: "POST" })
248
+ }
249
+ };
250
+ }
251
+
124
252
  // src/client/scopedManagementClient.ts
125
253
  function scopedRequest(request, source) {
126
- return async (path, options = {}) => {
254
+ return async (path2, options = {}) => {
127
255
  const token = typeof source === "function" ? await source() : source;
128
256
  if (typeof token !== "string" || !token.trim() || /\s/u.test(token))
129
257
  throw new TypeError("Authyon: a valid access token is required.");
130
- return request(path, {
258
+ return request(path2, {
131
259
  ...options,
132
260
  headers: { ...options.headers, Authorization: `Bearer ${token}` }
133
261
  });
134
262
  };
135
263
  }
136
- function environmentPath(scope) {
137
- return `/platform/workspaces/${segment(scope.workspaceId)}/environments/${segment(scope.environmentId)}`;
138
- }
139
- function tenantPath(scope) {
140
- return `${environmentPath(scope)}/tenants/${segment(scope.tenantId)}`;
141
- }
142
- function credentialPath(scope) {
143
- return `${scope.tenantId === void 0 ? environmentPath(scope) : tenantPath(scope)}/credentials`;
144
- }
145
- function workspacePath(id) {
146
- return `/platform/workspaces/${segment(id)}`;
147
- }
148
- function workspaceRole(role) {
149
- if (role !== "admin" && role !== "auditor")
150
- throw new TypeError("Authyon: workspace role must be admin or auditor.");
151
- return role;
152
- }
153
264
  var _request;
154
- var PlatformScopedClient = class {
265
+ var UserScopedClient = class {
155
266
  /** @hidden */
156
267
  constructor(request, token) {
157
268
  __privateAdd(this, _request);
158
- this.credentials = {
159
- list: (scope, options = {}) => credentialPage(__privateGet(this, _request), credentialPath(scope), options),
160
- get: async (scope, credentialId) => credentialDetail(await __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}`)),
161
- create: (scope, input) => __privateGet(this, _request).call(this, credentialPath(scope), {
162
- method: "POST",
163
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
164
- }),
165
- updatePermissions: (scope, credentialId, input) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}/permissions`, {
166
- method: "PUT",
167
- body: permissionsBody(input)
168
- }),
169
- updateScopes: (scope, credentialId, scopes) => this.credentials.updatePermissions(scope, credentialId, { scopes }),
170
- /** Returns a new secret once. API may require an explicit step-up first. */
171
- rotate: (scope, credentialId) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}/rotate`, { method: "POST" }),
172
- revoke: (scope, credentialId) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}`, { method: "DELETE" })
173
- };
174
- this.workspaces = {
175
- team: (workspaceId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/team`),
269
+ this.tenants = {
270
+ /**
271
+ * The direct, active sub-tenants of a tenant, acting as the user. One level
272
+ * per call: each row's `childCount` says where the next call is worth
273
+ * making. Needs `subtenants:tree:read` on the tenant or on one above it —
274
+ * even on the user's own tenant, since listing the children is reading
275
+ * below it.
276
+ *
277
+ * Paged like every other `skip`/`take` listing, with `search`, `filter`
278
+ * (public scope only — build them with `tenantFilter`) and `orderBy`; see
279
+ * `SubTenantListOptions`. A bad option raises `RangeError` before any
280
+ * request. Requires the Authyon API of 2026-11-26 or newer.
281
+ */
282
+ subTenants: {
283
+ /** GET /auth/tenants/{tenantId}/subtenants. */
284
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/subtenants`, {
285
+ query: subTenantQuery(options)
286
+ }),
287
+ /**
288
+ * GET /auth/tenants/subtenants — the same, for the tenant the user's token
289
+ * is scoped to (its `tenant_id`). Same permission rule. Answers
290
+ * `tenant.no_active_tenant` when the session never switched into one.
291
+ */
292
+ listCurrent: (options = {}) => __privateGet(this, _request).call(this, "/auth/tenants/subtenants", { query: subTenantQuery(options) })
293
+ },
176
294
  members: {
177
- invite: (workspaceId, input) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/invites`, {
295
+ /** Newest first; `search` matches email, username or name (at most 100 characters). */
296
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
297
+ query: memberQuery(options)
298
+ }),
299
+ /** Adds an existing environment user by email; does not send an invitation email. */
300
+ invite: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
178
301
  method: "POST",
179
- body: { email: input.email, role: workspaceRole(input.role) }
302
+ body: { email: input.email, roles: input.roles }
180
303
  }),
181
- /** memberId comes from team.members; it is not the platform userId. */
182
- remove: (workspaceId, memberId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/members/${segment(memberId)}`, {
304
+ remove: (tenantId, userId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
183
305
  method: "DELETE"
184
- }),
185
- changeRole: (workspaceId, memberId, role) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/members/${segment(memberId)}`, {
186
- method: "PATCH",
187
- body: { role: workspaceRole(role) }
188
306
  })
189
307
  },
308
+ /**
309
+ * Invites by e-mail or by link, acting as the user. Requires the
310
+ * `tenants:members:invite` permission on the tenant.
311
+ */
190
312
  invites: {
191
- create: (workspaceId, input) => this.workspaces.members.invite(workspaceId, input),
192
- revoke: (workspaceId, inviteId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/invites/${segment(inviteId)}`, {
193
- method: "DELETE"
194
- })
195
- }
196
- };
197
- this.tenants = {
198
- members: {
199
- list: (scope, options = {}) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members`, { query: options }),
200
- add: (scope, userId, roles) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members`, { method: "POST", body: { userId, roles } }),
201
- remove: (scope, userId) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members/${segment(userId)}`, { method: "DELETE" })
202
- }
203
- };
204
- this.auth = {
205
- /** Explicitly confirms the current platform session; passwords are not retained. */
206
- stepUp: (currentPassword) => __privateGet(this, _request).call(this, "/platform/auth/step-up", { method: "POST", body: { currentPassword } })
207
- };
208
- __privateSet(this, _request, scopedRequest(request, token));
209
- }
210
- };
211
- _request = new WeakMap();
212
- var _request2;
213
- var UserScopedClient = class {
214
- /** @hidden */
215
- constructor(request, token) {
216
- __privateAdd(this, _request2);
217
- this.tenants = {
218
- members: {
219
- list: (tenantId, options = {}) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members`, { query: options }),
220
- /** Adds an existing environment user by email; does not send an invitation email. */
221
- invite: (tenantId, input) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
313
+ list: (tenantId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`),
314
+ /** Always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
315
+ create: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`, {
222
316
  method: "POST",
223
- body: { email: input.email, roles: input.roles }
317
+ body: {
318
+ email: input.email,
319
+ roles: input.roles,
320
+ sendEmail: input.sendEmail ?? true,
321
+ redirectUri: input.redirectUri
322
+ }
323
+ }),
324
+ /** New link (the previous one stops working), mailed unless `sendEmail` is `false`. */
325
+ resend: (tenantId, inviteId, input = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}/resend`, {
326
+ method: "POST",
327
+ body: { sendEmail: input.sendEmail ?? true }
224
328
  }),
225
- remove: (tenantId, userId) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
329
+ revoke: (tenantId, inviteId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}`, {
226
330
  method: "DELETE"
227
331
  })
228
332
  }
229
333
  };
230
- __privateSet(this, _request2, scopedRequest(request, token));
231
- }
232
- };
233
- _request2 = new WeakMap();
234
- var _request3;
235
- var WorkspaceInvitesClient = class {
236
- /** @hidden */
237
- constructor(request) {
238
- __privateAdd(this, _request3);
239
- __privateSet(this, _request3, request);
240
- }
241
- preview(token) {
242
- return __privateGet(this, _request3).call(this, `/platform/workspace-invites/${segment(token)}`);
243
- }
244
- accept(token, input = {}) {
245
- return __privateGet(this, _request3).call(this, `/platform/workspace-invites/${segment(token)}/accept`, {
246
- method: "POST",
247
- body: { name: input.name, password: input.password }
248
- });
334
+ __privateSet(this, _request, scopedRequest(request, token));
335
+ this.security = subjectSecurity(__privateGet(this, _request));
249
336
  }
250
337
  };
251
- _request3 = new WeakMap();
338
+ _request = new WeakMap();
252
339
 
253
- // ../../internal/core/config/defaults.ts
254
- var DEFAULT_BASE_URL = "https://api.authyon.com";
255
- var DEFAULT_EXPIRY_SKEW_MS = 3e4;
340
+ // src/client/inviteQuery.ts
341
+ var STATUSES = /* @__PURE__ */ new Set([
342
+ "pending",
343
+ "accepted",
344
+ "revoked",
345
+ "expired"
346
+ ]);
347
+ function inviteQuery(options = {}) {
348
+ const { skip, take, search, status } = options;
349
+ if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
350
+ throw new RangeError("Authyon: invalid skip.");
351
+ if (take !== void 0 && (!Number.isInteger(take) || take < 1 || take > 100))
352
+ throw new RangeError("Authyon: take must be between 1 and 100.");
353
+ if (search !== void 0 && (typeof search !== "string" || search.trim().length > 254))
354
+ throw new RangeError("Authyon: search must contain at most 254 characters.");
355
+ let statuses;
356
+ if (status !== void 0) {
357
+ if (!Array.isArray(status)) throw new TypeError("Authyon: status must be an array.");
358
+ const normalized = status.map((s) => String(s).trim().toLowerCase()).filter((s) => s.length > 0);
359
+ const unknown = normalized.find((s) => !STATUSES.has(s));
360
+ if (unknown) throw new RangeError(`Authyon: unknown invite status "${unknown}".`);
361
+ statuses = [...new Set(normalized)];
362
+ if (statuses.length === 0) statuses = void 0;
363
+ }
364
+ return { search: search?.trim() || void 0, skip, take, status: statuses };
365
+ }
256
366
 
257
367
  // ../../internal/core/auth/expiringTokenProvider.ts
258
368
  var _token, _inFlight;
@@ -283,477 +393,20 @@ var ExpiringTokenProvider = class {
283
393
  _token = new WeakMap();
284
394
  _inFlight = new WeakMap();
285
395
 
286
- // ../../internal/core/errors/authyonError.ts
287
- var ErrorCodes = {
288
- Unknown: "unknown",
289
- NetworkError: "request.network_error",
290
- Timeout: "request.timeout",
291
- SessionMalformed: "session.malformed",
292
- NotAuthenticated: "auth.not_authenticated",
293
- InvalidToken: "auth.invalid_token",
294
- MissingToken: "auth.missing_token",
295
- EmailTaken: "user.email_taken",
296
- PasswordWeak: "user.password_weak",
297
- PasswordPwned: "user.password_pwned",
298
- RateLimited: "rate_limited"
299
- };
300
- var AuthyonError = class extends Error {
301
- constructor(status, body, options = {}) {
302
- super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
303
- this.name = "AuthyonError";
304
- this.status = status;
305
- this.code = body.code ?? "unknown";
306
- this.title = body.title ?? "Error";
307
- this.detail = body.detail;
308
- this.requestId = options.requestId;
309
- this.retryAfter = options.retryAfter;
310
- this.cause = options.cause;
311
- }
312
- is(code) {
313
- return this.code === code;
314
- }
315
- isAny(...codes) {
316
- return codes.includes(this.code);
317
- }
318
- hasPrefix(prefix) {
319
- return this.code.startsWith(prefix);
320
- }
321
- isStatus(...statuses) {
322
- return statuses.includes(this.status);
323
- }
324
- /** Stable interpretation for UI decisions, retries, telemetry and support flows. */
325
- interpret() {
326
- const category = classifyError(this.status, this.code);
327
- return {
328
- category,
329
- action: actionFor(category),
330
- retryable: isRetryable(category),
331
- ...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
332
- ...this.requestId !== void 0 ? { requestId: this.requestId } : {}
333
- };
334
- }
335
- get category() {
336
- return this.interpret().category;
337
- }
338
- get retryable() {
339
- return this.interpret().retryable;
340
- }
341
- toJSON() {
342
- return {
343
- name: this.name,
344
- message: this.message,
345
- status: this.status,
346
- code: this.code,
347
- title: this.title,
348
- detail: this.detail,
349
- requestId: this.requestId,
350
- retryAfter: this.retryAfter,
351
- ...this.interpret()
352
- };
353
- }
354
- };
355
- function classifyError(status, code) {
356
- if (code === ErrorCodes.NetworkError) return "network";
357
- if (code === ErrorCodes.Timeout || status === 408) return "timeout";
358
- if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
359
- if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
360
- if (code === ErrorCodes.PasswordWeak || code === ErrorCodes.PasswordPwned) return "validation";
361
- if (code === ErrorCodes.SessionMalformed) return "server";
362
- if (code.startsWith("auth.") || status === 401) return "authentication";
363
- if (status === 403) return "authorization";
364
- if (status === 404) return "not_found";
365
- if (status === 400 || status === 422) return "validation";
366
- if (status >= 500) return "server";
367
- return "unknown";
368
- }
369
- function actionFor(category) {
370
- switch (category) {
371
- case "network":
372
- case "timeout":
373
- case "rate_limit":
374
- case "server":
375
- return "retry";
376
- case "authentication":
377
- return "reauthenticate";
378
- case "authorization":
379
- return "request_access";
380
- case "validation":
381
- return "fix_input";
382
- case "not_found":
383
- return "not_found";
384
- case "conflict":
385
- return "resolve_conflict";
386
- case "unknown":
387
- return "contact_support";
388
- }
389
- }
390
- function isRetryable(category) {
391
- return category === "network" || category === "timeout" || category === "rate_limit" || category === "server";
392
- }
393
-
394
- // ../../internal/core/http/query.ts
395
- function appendQuery(path, params) {
396
- if (!params) return path;
397
- const query = new URLSearchParams();
398
- for (const [key, value2] of Object.entries(params)) {
399
- if (value2 !== void 0) query.set(key, String(value2));
400
- }
401
- const value = query.toString();
402
- return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
403
- }
404
-
405
- // ../../internal/core/http/httpAdapter.ts
406
- var FetchHttpAdapter = class {
407
- constructor(fetchImpl = fetch.bind(globalThis)) {
408
- this.fetchImpl = fetchImpl;
409
- }
410
- request(request) {
411
- return this.fetchImpl(request.url, {
412
- method: request.method,
413
- headers: request.headers,
414
- body: request.body,
415
- signal: request.signal,
416
- redirect: "error"
417
- });
418
- }
419
- };
420
- var LoggingHttpAdapter = class {
421
- constructor(adapter, options) {
422
- this.adapter = adapter;
423
- this.options = options;
424
- }
425
- async request(request) {
426
- const startedAt = Date.now();
427
- const eventBase = {
428
- method: request.method,
429
- url: sanitizeUrl(request.url)
430
- };
431
- this.log({ type: "request", ...eventBase, timestamp: startedAt });
432
- try {
433
- const response = await this.adapter.request(request);
434
- this.log({
435
- type: "response",
436
- ...eventBase,
437
- status: response.status,
438
- durationMs: Date.now() - startedAt,
439
- requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
440
- timestamp: Date.now()
441
- });
442
- return response;
443
- } catch (error) {
444
- this.log({
445
- type: "error",
446
- ...eventBase,
447
- errorName: error instanceof Error ? error.name : "UnknownError",
448
- durationMs: Date.now() - startedAt,
449
- timestamp: Date.now()
450
- });
451
- throw error;
452
- }
453
- }
454
- log(event) {
455
- if (!this.options.enabled) return;
456
- const logger = this.options.logger ?? defaultHttpLogger;
457
- try {
458
- logger(event);
459
- } catch {
460
- }
461
- }
462
- };
463
- function defaultHttpLogger(event) {
464
- console.debug("[Authyon HTTP]", event);
465
- }
466
- function sanitizeUrl(value) {
467
- const url = new URL(value);
468
- url.username = "";
469
- url.password = "";
470
- url.hash = "";
471
- url.pathname = url.pathname.replace(/(\/platform\/workspace-invites\/)[^/]+/u, "$1REDACTED");
472
- const queryKeys = /* @__PURE__ */ new Set();
473
- url.searchParams.forEach((_value, key) => queryKeys.add(key));
474
- url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
475
- return url.toString();
476
- }
477
-
478
- // ../../internal/core/http/transport.ts
479
- var DEFAULT_TIMEOUT_MS = 15e3;
480
- var SharedTransportError = class extends Error {
481
- constructor(code, cause) {
482
- super(code === "request.timeout" ? "Request timed out" : "Network request failed");
483
- this.name = "SharedTransportError";
484
- this.code = code;
485
- this.cause = cause;
486
- }
487
- };
488
- function createSharedTransport(options) {
489
- const baseUrl = normalizeBaseUrl(options.baseUrl, options.allowInsecureHttp ?? false);
490
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
491
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
492
- throw new Error("Authyon: `timeoutMs` must be a non-negative finite number");
493
- }
494
- if (options.httpAdapter && options.fetch) {
495
- throw new Error("Authyon: use either `httpAdapter` or `fetch`, not both");
496
- }
497
- const baseAdapter = options.httpAdapter ?? new FetchHttpAdapter(options.fetch);
498
- const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
499
- return {
500
- baseUrl,
501
- async request(path, init) {
502
- const controller = new AbortController();
503
- const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
504
- try {
505
- return await httpAdapter.request({
506
- url: `${baseUrl}${path}`,
507
- method: init.method ?? "GET",
508
- headers: normalizeHeaders(init.headers),
509
- body: init.body,
510
- signal: controller.signal
511
- });
512
- } catch (cause) {
513
- throw new SharedTransportError(
514
- controller.signal.aborted ? ErrorCodes.Timeout : ErrorCodes.NetworkError,
515
- cause
516
- );
517
- } finally {
518
- if (timeout !== void 0) clearTimeout(timeout);
519
- }
520
- }
521
- };
522
- }
523
- function normalizeHeaders(headers) {
524
- const normalized = {};
525
- new Headers(headers).forEach((value, key) => {
526
- normalized[key] = value;
527
- });
528
- return normalized;
529
- }
530
- function responseMetadata(response) {
531
- const retryAfterHeader = response.headers.get("retry-after");
532
- const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : void 0;
533
- return {
534
- requestId: response.headers.get("x-request-id") ?? response.headers.get("trace-id") ?? void 0,
535
- retryAfter: Number.isFinite(retryAfter) ? retryAfter : void 0
536
- };
537
- }
538
- function normalizeBaseUrl(value, allowInsecureHttp) {
539
- let url;
540
- try {
541
- url = new URL(value);
542
- } catch {
543
- throw new Error("Authyon: `baseUrl` must be an absolute URL");
544
- }
545
- const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
546
- if (url.protocol !== "https:" && !(url.protocol === "http:" && (loopback || allowInsecureHttp))) {
547
- throw new Error(
548
- "Authyon: `baseUrl` must use HTTPS (HTTP is allowed only for loopback or with `allowInsecureHttp`)"
549
- );
550
- }
551
- if (url.username || url.password || url.search || url.hash) {
552
- throw new Error(
553
- "Authyon: `baseUrl` cannot contain credentials, query parameters, or fragments"
554
- );
555
- }
556
- return url.toString().replace(/\/+$/, "");
557
- }
558
-
559
- // ../../internal/core/http/jsonHttpClient.ts
560
- var JsonHttpClient = class {
561
- constructor(transport) {
562
- this.transport = transport;
563
- }
564
- async send(path, options = {}) {
565
- const headers = { ...options.headers };
566
- if (options.body !== void 0) headers["Content-Type"] = "application/json";
567
- try {
568
- return await this.transport.request(appendQuery(path, options.query), {
569
- method: options.method ?? "GET",
570
- headers,
571
- body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
572
- });
573
- } catch (cause) {
574
- if (!(cause instanceof SharedTransportError)) throw cause;
575
- throw new AuthyonError(0, { code: cause.code, title: cause.message }, { cause: cause.cause });
576
- }
577
- }
578
- async parse(response) {
579
- if (!response.ok) {
580
- let body = {};
581
- try {
582
- body = await response.json();
583
- } catch {
584
- }
585
- throw new AuthyonError(response.status, body, responseMetadata(response));
586
- }
587
- if (response.status === 204) return void 0;
588
- return await response.json();
589
- }
590
- async request(path, options = {}) {
591
- return this.parse(await this.send(path, options));
592
- }
593
- };
594
-
595
- // ../../internal/core/http/clientIp.ts
596
- function clientIpHeaders(context) {
597
- if (!context?.clientIp) return {};
598
- return { "X-Forwarded-For": normalizeClientIp(context.clientIp) };
599
- }
600
- function normalizeClientIp(value) {
601
- let ip = value.trim();
602
- if (ip.startsWith("[") && ip.endsWith("]")) ip = ip.slice(1, -1);
603
- if (!ip || ip.length > 45 || ip.includes(",") || /[\r\n\s]/.test(ip) || !/^[0-9a-f:.]+$/i.test(ip) || !ip.includes(".") && !ip.includes(":")) {
604
- throw invalidClientIp();
605
- }
606
- try {
607
- new URL(ip.includes(":") ? `http://[${ip}]` : `http://${ip}`);
608
- } catch {
609
- throw invalidClientIp();
610
- }
611
- return ip;
612
- }
613
- function invalidClientIp() {
614
- return new Error("Authyon: `clientIp` must be a single valid IPv4 or IPv6 address");
615
- }
616
-
617
- // src/security/jwksTokenVerifier.ts
618
- import {
619
- createLocalJWKSet,
620
- createRemoteJWKSet,
621
- jwtVerify
622
- } from "jose";
623
- var SAFE_ASYMMETRIC_ALGORITHMS = [
624
- "RS256",
625
- "PS256",
626
- "ES256",
627
- "EdDSA"
628
- ];
629
- var TokenVerificationError = class extends Error {
630
- constructor(code, options = {}) {
631
- super(messageForCode(code));
632
- this.code = code;
633
- this.name = "TokenVerificationError";
634
- if (options.cause !== void 0) Object.defineProperty(this, "cause", { value: options.cause });
635
- }
636
- };
637
- var JwksTokenVerifier = class {
638
- constructor(options) {
639
- this.options = options;
640
- validateOptions(options);
641
- this.algorithms = [...options.algorithms ?? ["RS256"]];
642
- this.acceptedTokenTypes = new Set(options.acceptedTokenTypes ?? ["JWT", "at+jwt"]);
643
- this.verifyKey = options.jwks ? createLocalJWKSet(options.jwks) : createRemoteJWKSet(new URL(options.jwksUri), {
644
- timeoutDuration: options.jwksTimeoutMs ?? 5e3,
645
- cacheMaxAge: options.jwksCacheMs ?? 6e5,
646
- cooldownDuration: options.jwksCooldownMs ?? 3e4
647
- });
648
- }
649
- async verifyAccessToken(token) {
650
- if (!token || token.length > 16384) {
651
- throw new TokenVerificationError("token.invalid");
652
- }
653
- try {
654
- const result = await jwtVerify(token, this.verifyKey, {
655
- algorithms: this.algorithms,
656
- issuer: this.options.issuer,
657
- audience: this.options.audience,
658
- clockTolerance: this.options.clockToleranceSeconds ?? 5,
659
- maxTokenAge: this.options.maxTokenAgeSeconds ?? 3600,
660
- requiredClaims: ["iss", "aud", "sub", "exp", "iat"]
661
- });
662
- validateTokenType(result, this.acceptedTokenTypes);
663
- validateClaims(result.payload);
664
- return { claims: result.payload, protectedHeader: result.protectedHeader };
665
- } catch (cause) {
666
- if (cause instanceof TokenVerificationError) throw cause;
667
- throw new TokenVerificationError(errorCode(cause), { cause });
668
- }
669
- }
670
- };
671
- function validateTokenType(result, acceptedTokenTypes) {
672
- const type = result.protectedHeader.typ;
673
- if (!type || !acceptedTokenTypes.has(type)) {
674
- throw new TokenVerificationError("token.invalid_claims");
675
- }
676
- }
677
- function validateClaims(claims) {
678
- if (typeof claims.sub !== "string" || !claims.sub) invalidClaims();
679
- if (claims.permissions !== void 0 && !isStringArray(claims.permissions)) invalidClaims();
680
- if (claims.roles !== void 0 && !isStringArray(claims.roles)) invalidClaims();
681
- if (claims.scope !== void 0 && typeof claims.scope !== "string") invalidClaims();
682
- }
683
- function validateOptions(options) {
684
- const issuer = secureUrl(options.issuer, "issuer");
685
- if (Boolean(options.jwksUri) === Boolean(options.jwks)) {
686
- throw new Error("Authyon: configure exactly one of `jwksUri` or `jwks`");
687
- }
688
- const jwks = options.jwksUri ? secureUrl(options.jwksUri, "jwksUri") : void 0;
689
- if (!options.audience || Array.isArray(options.audience) && options.audience.length === 0) {
690
- throw new Error("Authyon: JWT `audience` is required");
691
- }
692
- if (jwks && issuer.origin !== jwks.origin) {
693
- throw new Error("Authyon: `issuer` and `jwksUri` must use the same trusted origin");
694
- }
695
- const algorithms = options.algorithms ?? ["RS256"];
696
- if (algorithms.length === 0 || algorithms.some((algorithm) => !SAFE_ASYMMETRIC_ALGORITHMS.includes(algorithm))) {
697
- throw new Error("Authyon: only approved asymmetric JWT algorithms are accepted");
698
- }
699
- if (options.acceptedTokenTypes?.length === 0 || options.acceptedTokenTypes?.some((type) => !type.trim())) {
700
- throw new Error("Authyon: `acceptedTokenTypes` must contain non-empty values");
701
- }
702
- for (const [name, value] of [
703
- ["clockToleranceSeconds", options.clockToleranceSeconds],
704
- ["maxTokenAgeSeconds", options.maxTokenAgeSeconds],
705
- ["jwksTimeoutMs", options.jwksTimeoutMs],
706
- ["jwksCacheMs", options.jwksCacheMs],
707
- ["jwksCooldownMs", options.jwksCooldownMs]
708
- ]) {
709
- if (value !== void 0 && (!Number.isFinite(value) || value < 0)) {
710
- throw new Error(`Authyon: \`${name}\` must be a non-negative finite number`);
711
- }
712
- }
713
- }
714
- function secureUrl(value, name) {
715
- let url;
716
- try {
717
- url = new URL(value);
718
- } catch {
719
- throw new Error(`Authyon: JWT \`${name}\` must be an absolute URL`);
720
- }
721
- if (url.protocol !== "https:" || url.username || url.password || url.hash) {
722
- throw new Error(`Authyon: JWT \`${name}\` must be a credential-free HTTPS URL`);
723
- }
724
- return url;
725
- }
726
- function errorCode(error) {
727
- const code = isRecord(error) && typeof error.code === "string" ? error.code : "";
728
- if (code === "ERR_JWT_EXPIRED") return "token.expired";
729
- if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "token.invalid_signature";
730
- if (code === "ERR_JWKS_TIMEOUT") {
731
- return "token.key_unavailable";
732
- }
733
- if (code === "ERR_JWKS_NO_MATCHING_KEY") return "token.invalid_signature";
734
- if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
735
- const claim = isRecord(error) && typeof error.claim === "string" ? error.claim : "";
736
- return claim === "nbf" ? "token.not_active" : "token.invalid_claims";
737
- }
738
- return "token.invalid";
739
- }
740
- function messageForCode(code) {
741
- if (code === "token.key_unavailable") return "Token verification key is unavailable";
742
- if (code === "token.expired") return "Token has expired";
743
- if (code === "token.not_active") return "Token is not active yet";
744
- return "Token verification failed";
745
- }
746
- function invalidClaims() {
747
- throw new TokenVerificationError("token.invalid_claims");
748
- }
749
- function isStringArray(value) {
750
- return Array.isArray(value) && value.every((item) => typeof item === "string");
751
- }
752
- function isRecord(value) {
753
- return typeof value === "object" && value !== null;
754
- }
755
-
756
396
  // src/client/authyonServerClient.ts
397
+ var ROOT_PARENT_ID = "00000000-0000-0000-0000-000000000000";
398
+ function tenantListQuery({
399
+ parentId,
400
+ orderBy,
401
+ ...rest
402
+ }) {
403
+ const query = { ...rest };
404
+ if (parentId !== void 0) query.parentId = parentId === null ? ROOT_PARENT_ID : parentId;
405
+ if (orderBy !== void 0) {
406
+ query.orderBy = typeof orderBy === "string" ? orderBy : `${orderBy.field}:${orderBy.direction ?? "asc"}`;
407
+ }
408
+ return query;
409
+ }
757
410
  var _clientSecret;
758
411
  var AuthyonServerClient = class {
759
412
  constructor(options = {}) {
@@ -791,11 +444,16 @@ var AuthyonServerClient = class {
791
444
  client_id: credentials.clientId,
792
445
  client_secret: credentials.clientSecret
793
446
  }
447
+ }),
448
+ /** POST /tenant/auth/validate — validates an already-minted tenant-client bearer token. */
449
+ validate: (accessToken, context) => this.request("/tenant/auth/validate", {
450
+ method: "POST",
451
+ headers: {
452
+ ...clientIpHeaders(context),
453
+ Authorization: `Bearer ${accessToken}`
454
+ }
794
455
  })
795
456
  };
796
- this.workspaceInvites = new WorkspaceInvitesClient(
797
- (path, options) => this.http.request(path, options)
798
- );
799
457
  // ── Environment management (users, tenants, roles, permissions, audit) ───
800
458
  this.environment = {
801
459
  users: {
@@ -839,6 +497,39 @@ var AuthyonServerClient = class {
839
497
  envBearer: true,
840
498
  body: { newPassword, reason }
841
499
  }),
500
+ /**
501
+ * POST /env/password-resets — issues a password-reset token for the
502
+ * account with this address and returns it, so your application can
503
+ * deliver it in its own e-mail instead of Authyon's. Needs the
504
+ * `authyon:users:password` scope. Unlike the public forgot-password
505
+ * request, an unknown address rejects with `user.not_found` (404).
506
+ * A previous live token for the same account stops working.
507
+ */
508
+ issuePasswordReset: (input) => this.request("/env/password-resets", {
509
+ method: "POST",
510
+ envBearer: true,
511
+ body: { ...input, sendEmail: input.sendEmail ?? false }
512
+ }),
513
+ /**
514
+ * POST /auth/password-reset/validate — for a backend hosting the reset
515
+ * page: checks a token without spending it. Public, needs only the
516
+ * `envKey`. Rejects with `user.password_reset.invalid` (401) when the
517
+ * token is unknown, used or expired.
518
+ */
519
+ validatePasswordReset: (token) => this.request("/auth/password-reset/validate", { method: "POST", body: { token } }),
520
+ /**
521
+ * POST /auth/password-reset/confirm — redeems the token and sets the new
522
+ * password (every session of the account is signed out). Public, needs
523
+ * only the `envKey`. Resolves with the `redirectUri` the reset was issued
524
+ * with, or `null`.
525
+ */
526
+ confirmPasswordReset: async (token, newPassword) => {
527
+ const done = await this.request(
528
+ "/auth/password-reset/confirm",
529
+ { method: "POST", body: { token, newPassword } }
530
+ );
531
+ return { redirectUri: done?.redirectUri ?? null };
532
+ },
842
533
  /** POST /env/users/{userId}/sessions/revoke-all — revokes every session the user has. */
843
534
  revokeSessions: (userId, reason) => this.request(`/env/users/${encodeURIComponent(userId)}/sessions/revoke-all`, {
844
535
  method: "POST",
@@ -890,12 +581,12 @@ var AuthyonServerClient = class {
890
581
  credentials: {
891
582
  /** GET /env/tenants/{tenantId}/credentials. Returns metadata only, including revoked credentials. */
892
583
  list: (tenantId) => allCredentials(
893
- (path, options) => this.request(path, { ...options, envBearer: true }),
584
+ (path2, options) => this.request(path2, { ...options, envBearer: true }),
894
585
  `/env/tenants/${segment(tenantId)}/credentials`
895
586
  ),
896
587
  /** Paginated searchable listing. Prefer this over loading every credential. */
897
588
  listPage: (tenantId, options = {}) => credentialPage(
898
- (path, requestOptions) => this.request(path, { ...requestOptions, envBearer: true }),
589
+ (path2, requestOptions) => this.request(path2, { ...requestOptions, envBearer: true }),
899
590
  `/env/tenants/${segment(tenantId)}/credentials`,
900
591
  options
901
592
  ),
@@ -909,7 +600,11 @@ var AuthyonServerClient = class {
909
600
  create: (tenantId, input) => this.request(`/env/tenants/${segment(tenantId)}/credentials`, {
910
601
  method: "POST",
911
602
  envBearer: true,
912
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
603
+ body: {
604
+ description: input.description,
605
+ ...lifetimeBody(input),
606
+ ...permissionsBody(input)
607
+ }
913
608
  }),
914
609
  /** Returns a new secret once while keeping the same client id. */
915
610
  rotate: (tenantId, credentialId) => this.request(
@@ -928,11 +623,85 @@ var AuthyonServerClient = class {
928
623
  envBearer: true
929
624
  })
930
625
  },
931
- /** GET /env/tenants — paginated, searchable list of tenants in the environment. */
932
- list: (params = {}) => this.request("/env/tenants", { envBearer: true, query: params }),
933
- /** POST /env/tenants — create a tenant in the environment. */
626
+ /**
627
+ * GET /env/tenants — one page of the environment's tenants.
628
+ *
629
+ * `search` matches, case-insensitively and anywhere in the value, the
630
+ * name, the slug, the description and the raw text of both metadata
631
+ * documents — so a tenant filed with `{"cnpj":"00.000.000/0001-00"}`
632
+ * is found by the number, and `cnpj` alone finds every tenant carrying
633
+ * that key. `take` defaults to 25 and is capped at 100.
634
+ *
635
+ * `filter` is the structured half, and the one to reach for when more
636
+ * than one condition has to hold: each entry is a condition on a JSON
637
+ * document, they are ANDed with each other and with `search`, and they
638
+ * run inside the statement — so the envelope keeps describing the
639
+ * filtered set and you can page through it. Build them with
640
+ * `tenantFilter`:
641
+ *
642
+ * ```ts
643
+ * const page = await authyon.environment.tenants.list({
644
+ * filter: [
645
+ * tenantFilter.in("public.kind", ["reseller", "partner"]),
646
+ * tenantFilter.in("custom.cnpj", [a, b]),
647
+ * ],
648
+ * take: 100,
649
+ * });
650
+ * ```
651
+ *
652
+ * `parentId` narrows the page to one level of the tree — `children()`
653
+ * and `roots()` below are the same call with that one option set.
654
+ *
655
+ * Against an Authyon API older than 2026-10-21 this route ignored
656
+ * skip/take/search and answered with a bare array; one older than
657
+ * 2026-10-22 ignores `filter` and one older than 2026-10-31 ignores
658
+ * `parentId`, which read as a page that is too wide rather than an error.
659
+ */
660
+ list: (params = {}) => this.request("/env/tenants", { envBearer: true, query: tenantListQuery(params) }),
661
+ /**
662
+ * One page of a tenant's direct sub-tenants — `list()` with `parentId`.
663
+ *
664
+ * Only one level: a node's own children carry `childCount`, so a tree
665
+ * view asks again where that is above zero instead of reading the whole
666
+ * subtree to draw the first level of it.
667
+ */
668
+ children: (parentTenantId, params = {}) => this.environment.tenants.list({ ...params, parentId: parentTenantId }),
669
+ /**
670
+ * One page of the environment's root tenants — `list()` with no parent.
671
+ *
672
+ * This is the first level of the tree, and the difference from `list()`
673
+ * is worth keeping straight: `list()` returns every tenant at every
674
+ * depth, which is what a flat picker wants and what a tree view must not
675
+ * start from.
676
+ */
677
+ roots: (params = {}) => this.environment.tenants.list({ ...params, parentId: null }),
678
+ /**
679
+ * Every sub-tenant in the environment, at any depth and under any
680
+ * parent — `list()` with `minDepth: 1`. This is the one page
681
+ * `children()` cannot produce, since it names a single parent, and the
682
+ * one a flat "all sub-companies" screen wants: the envelope describes
683
+ * the sub-tenants alone, so the pager stops where they do, and nobody
684
+ * has to read the whole environment and drop the roots.
685
+ *
686
+ * Against an Authyon API older than 2026-10-31 the floor is ignored and
687
+ * the roots come back too.
688
+ */
689
+ subTenants: (params = {}) => this.environment.tenants.list({ ...params, minDepth: 1 }),
690
+ /**
691
+ * POST /env/tenants — create a tenant in the environment.
692
+ *
693
+ * `parentTenantId` nests it under an existing tenant. The environment's
694
+ * `maxTenantDepth` has to allow the level — it ships as `1`, roots only,
695
+ * so this answers `tenant.depth.not_allowed` until an operator raises it
696
+ * in the console.
697
+ */
934
698
  create: (input) => this.request("/env/tenants", { method: "POST", envBearer: true, body: input }),
935
- /** GET /env/tenants/{tenantId} — fetch a tenant by id. */
699
+ /**
700
+ * GET /env/tenants/{tenantId} — fetch a tenant by id.
701
+ *
702
+ * Returns `ancestors` as well, the chain above it root first, so a
703
+ * breadcrumb costs this one call rather than one per level.
704
+ */
936
705
  get: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, { envBearer: true }),
937
706
  /** PUT /env/tenants/{tenantId} — update a tenant. */
938
707
  update: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
@@ -940,22 +709,84 @@ var AuthyonServerClient = class {
940
709
  envBearer: true,
941
710
  body: input
942
711
  }),
943
- /** DELETE /env/tenants/{tenantId} — delete a tenant. */
712
+ /** PUT /env/tenants/{tenantId}/metadata - replace public and private metadata. */
713
+ updateMetadata: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/metadata`, {
714
+ method: "PUT",
715
+ envBearer: true,
716
+ body: input
717
+ }),
718
+ /**
719
+ * POST /env/tenants/{tenantId}/disable — disable without removing tenant
720
+ * data.
721
+ *
722
+ * Disables the branch below it too. A sub-tenant left live under a
723
+ * disabled parent would go on authenticating its users, which is the one
724
+ * thing switching a tenant off is there to stop — so check `childCount`
725
+ * before calling this on a node with children.
726
+ */
727
+ disable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/disable`, {
728
+ method: "POST",
729
+ envBearer: true
730
+ }),
731
+ /**
732
+ * DELETE /env/tenants/{tenantId} — logically delete (disable) a tenant,
733
+ * and the branch below it. Same handler as `disable()`.
734
+ */
944
735
  delete: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
945
736
  method: "DELETE",
946
737
  envBearer: true
947
738
  }),
739
+ /**
740
+ * POST /env/tenants/{tenantId}/enable — the way back from `disable()`.
741
+ *
742
+ * Only this tenant comes back: a sub-tenant that went down with the
743
+ * cascade stays off until enabled itself, and a tenant under a disabled
744
+ * parent cannot come back before the parent does
745
+ * (`tenant.ancestor_disabled`).
746
+ *
747
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
748
+ */
749
+ enable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/enable`, {
750
+ method: "POST",
751
+ envBearer: true
752
+ }),
753
+ /**
754
+ * POST /env/tenants/{tenantId}/move — hang the tenant, with everything
755
+ * below it, under another parent, or at the root with `null`.
756
+ *
757
+ * Refused into itself or one of its own descendants
758
+ * (`tenant.parent.cycle`), into a switched-off branch, or where the
759
+ * branch's deepest node would pass the environment's level cap
760
+ * (`tenant.depth.not_allowed`). Every token minted at the old position
761
+ * is retired (`tenant.path_stale`), so sessions inside the branch sign
762
+ * in again.
763
+ *
764
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
765
+ */
766
+ move: (tenantId, parentTenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/move`, {
767
+ method: "POST",
768
+ envBearer: true,
769
+ body: { parentTenantId }
770
+ }),
948
771
  members: {
949
772
  /**
950
773
  * GET /env/tenants/{tenantId}/members — a tenant's members as full
951
- * user records. Confirmed live: a bare array (unlike
952
- * `environment.users.list()`, this one does NOT paginate despite
953
- * accepting `skip`/`take`), with the same shape
954
- * `environment.users.list()` items have.
774
+ * user records, with the same shape `environment.users.list()` items
775
+ * have, plus `tenantRoles` and `tenantPermissions` scoped to this
776
+ * tenant.
777
+ *
778
+ * Paged like every other list: the `Paged<T>` envelope carries
779
+ * `total` and `hasNext`, `take` defaults to 50 and is capped at 100,
780
+ * newest member first. `search` matches email, username or name (at
781
+ * most 100 characters, checked before any request).
782
+ * Up to the Authyon API of 2026-10-21 this one route answered with a
783
+ * bare array, so a caller had to page until a short page came back;
784
+ * against such an API `data` is undefined and the array is the body
785
+ * itself.
955
786
  */
956
787
  list: (tenantId, params = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
957
788
  envBearer: true,
958
- query: params
789
+ query: memberQuery(params)
959
790
  }),
960
791
  /** POST /env/tenants/{tenantId}/members — add a member to a tenant. */
961
792
  add: (tenantId, userId, roles) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
@@ -989,6 +820,69 @@ var AuthyonServerClient = class {
989
820
  { method: "DELETE", envBearer: true }
990
821
  )
991
822
  },
823
+ /**
824
+ * Invites by e-mail or by link — for addresses that may not have an
825
+ * account yet; accepting creates it. Managing them needs the
826
+ * credential's `authyon:users:write` scope (listing, `authyon:tenants:read`).
827
+ */
828
+ invites: {
829
+ /**
830
+ * GET /env/tenants/{tenantId}/invites — one page of the tenant's
831
+ * invites, newest first, optionally narrowed by address (`search`)
832
+ * and by `status`. Up to 0.2.0-beta.26 this returned every invite as
833
+ * a plain array.
834
+ */
835
+ list: (tenantId, options = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
836
+ envBearer: true,
837
+ query: inviteQuery(options)
838
+ }),
839
+ /**
840
+ * POST /env/tenants/{tenantId}/invites — invite an address. Always
841
+ * returns `acceptUrl`; with `sendEmail: false` Authyon does not mail
842
+ * it and you deliver the link yourself. Valid 7 days, single use, and
843
+ * not readable again later.
844
+ */
845
+ create: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
846
+ method: "POST",
847
+ envBearer: true,
848
+ body: {
849
+ email: input.email,
850
+ roles: input.roles,
851
+ sendEmail: input.sendEmail ?? true,
852
+ redirectUri: input.redirectUri
853
+ }
854
+ }),
855
+ /** POST .../invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
856
+ resend: (tenantId, inviteId, input = {}) => this.request(
857
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}/resend`,
858
+ { method: "POST", envBearer: true, body: { sendEmail: input.sendEmail ?? true } }
859
+ ),
860
+ /** DELETE /env/tenants/{tenantId}/invites/{inviteId} — revoke a pending invite. */
861
+ revoke: (tenantId, inviteId) => this.request(
862
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}`,
863
+ { method: "DELETE", envBearer: true }
864
+ ),
865
+ /**
866
+ * POST /auth/tenant-invites/preview — for a backend hosting the accept
867
+ * page. Public: needs only `envKey`, the token is the credential.
868
+ */
869
+ preview: (token) => this.request("/auth/tenant-invites/preview", { method: "POST", body: { token } }),
870
+ /**
871
+ * Joins the tenant; for an address with no account, also creates it
872
+ * (password required) with the e-mail already confirmed. Does not
873
+ * sign the user in.
874
+ *
875
+ * Without metadata: POST /auth/tenant-invites/accept — public, needs
876
+ * only `envKey`. With `publicMetadata`/`privateMetadata`: POST
877
+ * /env/tenant-invites/accept with the environment credential
878
+ * (`authyon:users:write`), since only your backend may set them.
879
+ */
880
+ accept: (input) => input.publicMetadata !== void 0 || input.privateMetadata !== void 0 ? this.request("/env/tenant-invites/accept", {
881
+ method: "POST",
882
+ envBearer: true,
883
+ body: input
884
+ }) : this.request("/auth/tenant-invites/accept", { method: "POST", body: input })
885
+ },
992
886
  roles: {
993
887
  /** GET /env/tenants/{tenantId}/roles — list a tenant's roles. */
994
888
  list: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/roles`, { envBearer: true }),
@@ -1058,6 +952,60 @@ var AuthyonServerClient = class {
1058
952
  loginActivity: (params = {}) => this.request("/env/audit/login-activity", { envBearer: true, query: params })
1059
953
  }
1060
954
  };
955
+ // ── Security: one-time codes and approvals ───────────────────────────────
956
+ //
957
+ // Everything here runs with the environment credential: `otp` needs the
958
+ // `authyon:otp:verify` scope, `approvals` needs `authyon:financial:authorize`.
959
+ // Keep those credentials on the server.
960
+ this.security = {
961
+ otp: {
962
+ /**
963
+ * POST /env/users/{userId}/otp/verify — checks the user's authenticator
964
+ * app (TOTP) code. A wrong code returns `{ valid: false }` instead of
965
+ * throwing. Each code is accepted once; 3 wrong codes in a row sign the
966
+ * user out everywhere (`sessionsRevoked: true`); 5 lock the check for 15
967
+ * minutes (`rate_limited`). More than 50 wrong codes in 10 minutes from the
968
+ * same credential pause it (`credential_throttled`). Needs `authyon:otp:verify`.
969
+ */
970
+ check: (userId, code) => this.request(`/env/users/${segment(userId)}/otp/verify`, {
971
+ method: "POST",
972
+ envBearer: true,
973
+ body: { code }
974
+ })
975
+ },
976
+ /**
977
+ * The customer approves a payload with their authenticator code or
978
+ * passkey, once.
979
+ *
980
+ * 1. `create()` the approval with the payload and the customer.
981
+ * 2. The customer confirms it (`@authyon/auth` → `security.approvals.confirm`).
982
+ * 3. `consume()` it right before executing, and execute the returned payload.
983
+ */
984
+ approvals: {
985
+ /** POST /env/authorizations — registers a payload awaiting the customer's approval. */
986
+ create: (input) => {
987
+ const { idempotencyKey, ...body } = input;
988
+ return this.request("/env/authorizations", {
989
+ method: "POST",
990
+ envBearer: true,
991
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : void 0,
992
+ body
993
+ });
994
+ },
995
+ /** GET /env/authorizations/{id} — current status and, once approved, the assurance evidence. */
996
+ get: (id) => this.request(`/env/authorizations/${segment(id)}`, { envBearer: true }),
997
+ /**
998
+ * POST /env/authorizations/{id}/consume — redeems an approved approval
999
+ * exactly once and returns the approved payload. Pass `payload` to have
1000
+ * the API check it matches (`payload_mismatch` otherwise).
1001
+ */
1002
+ consume: (id, payload) => this.request(`/env/authorizations/${segment(id)}/consume`, {
1003
+ method: "POST",
1004
+ envBearer: true,
1005
+ body: payload === void 0 ? void 0 : { payload }
1006
+ })
1007
+ }
1008
+ };
1061
1009
  // ── Generic permission grants ─────────────────────────────────────────────
1062
1010
  this.permissions = {
1063
1011
  /** POST /users/{userId}/permissions — grant a permission directly to a user. */
@@ -1075,6 +1023,7 @@ var AuthyonServerClient = class {
1075
1023
  this.envKey = options.envKey;
1076
1024
  this.clientId = options.clientId;
1077
1025
  __privateSet(this, _clientSecret, options.clientSecret);
1026
+ this.clientIp = options.clientIp;
1078
1027
  this.transport = createSharedTransport({
1079
1028
  baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1080
1029
  allowInsecureHttp: options.allowInsecureHttp,
@@ -1100,13 +1049,16 @@ var AuthyonServerClient = class {
1100
1049
  };
1101
1050
  });
1102
1051
  }
1103
- async request(path, options = {}) {
1104
- const headers = { ...options.headers };
1052
+ async request(path2, options = {}) {
1053
+ const headers = {
1054
+ ...clientIpHeaders({ clientIp: this.clientIp }),
1055
+ ...options.headers
1056
+ };
1105
1057
  if (options.envBearer) {
1106
1058
  headers.Authorization = `Bearer ${await this.getEnvironmentAccessToken()}`;
1107
1059
  }
1108
1060
  if (this.envKey) headers["X-Authyon-Environment"] = this.envKey;
1109
- return this.http.request(path, { ...options, headers });
1061
+ return this.http.request(path2, { ...options, headers });
1110
1062
  }
1111
1063
  /** Mints (and caches) an environment access token from `clientId`/`clientSecret`. */
1112
1064
  async getEnvironmentAccessToken() {
@@ -1161,17 +1113,13 @@ var AuthyonServerClient = class {
1161
1113
  tenant(credentials) {
1162
1114
  return new TenantScopedClient(this, credentials);
1163
1115
  }
1164
- /** Uses only the supplied platform-user access token. */
1165
- platform(token) {
1166
- return new PlatformScopedClient((path, options) => this.http.request(path, options), token);
1167
- }
1168
1116
  /** Uses an end-user token; the configured environment key selects the environment. */
1169
1117
  user(token) {
1170
- return new UserScopedClient((path, options) => this.request(path, options), token);
1118
+ return new UserScopedClient((path2, options) => this.request(path2, options), token);
1171
1119
  }
1172
1120
  /** @internal used by {@link TenantScopedClient} to share the base URL/fetch/error handling. */
1173
- _requestAsTenant(accessToken, path, options = {}) {
1174
- return this.request(path, {
1121
+ _requestAsTenant(accessToken, path2, options = {}) {
1122
+ return this.request(path2, {
1175
1123
  ...options,
1176
1124
  headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
1177
1125
  envBearer: false
@@ -1181,17 +1129,43 @@ var AuthyonServerClient = class {
1181
1129
  _clientSecret = new WeakMap();
1182
1130
  var TenantScopedClient = class {
1183
1131
  constructor(server, credentials) {
1132
+ /** Invites to the token's tenant, by e-mail or by link. */
1133
+ this.invites = {
1134
+ /**
1135
+ * GET /tenant/invites — one page of the tenant's invites, newest first,
1136
+ * optionally narrowed by address (`search`) and by `status`. Up to
1137
+ * 0.2.0-beta.26 this returned every invite as a plain array.
1138
+ */
1139
+ list: (options = {}) => this.request("/tenant/invites", { query: inviteQuery(options) }),
1140
+ /** POST /tenant/invites — always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
1141
+ create: (input) => this.request("/tenant/invites", {
1142
+ method: "POST",
1143
+ body: {
1144
+ email: input.email,
1145
+ roles: input.roles,
1146
+ sendEmail: input.sendEmail ?? true,
1147
+ redirectUri: input.redirectUri
1148
+ }
1149
+ }),
1150
+ /** POST /tenant/invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1151
+ resend: (inviteId, input = {}) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}/resend`, {
1152
+ method: "POST",
1153
+ body: { sendEmail: input.sendEmail ?? true }
1154
+ }),
1155
+ /** DELETE /tenant/invites/{inviteId} — revoke a pending invite. */
1156
+ revoke: (inviteId) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" })
1157
+ };
1184
1158
  this.members = {
1185
1159
  /**
1186
1160
  * GET /tenant/members — members of the token's tenant.
1187
1161
  *
1188
- * ⚠️ Inferred, not confirmed live (no tenant client credentials
1189
- * available to exchange for a scoped token) — assumed to share
1190
- * `/env/tenants/{id}/members`'s confirmed shape (bare array of full
1191
- * user records), since both are the "admin" member listing as opposed
1192
- * to `/auth/tenants/{id}/members`'s paginated, lightweight one.
1162
+ * Same handler as `/env/tenants/{id}/members` (the tenant comes from the
1163
+ * token instead of the path), so the same `Paged<T>` envelope of full
1164
+ * user records, `take` defaulting to 50 and capped at 100 — as opposed
1165
+ * to `/auth/tenants/{id}/members`'s lightweight member shape. `search`
1166
+ * works the same way too.
1193
1167
  */
1194
- list: (params = {}) => this.request("/tenant/members", { query: params }),
1168
+ list: (params = {}) => this.request("/tenant/members", { query: memberQuery(params) }),
1195
1169
  /** POST /tenant/members — add a member to the token's tenant. */
1196
1170
  add: (userId, roles) => this.request("/tenant/members", { method: "POST", body: { userId, roles } }),
1197
1171
  /** DELETE /tenant/members/{userId} — remove a member from the token's tenant. */
@@ -1248,8 +1222,12 @@ var TenantScopedClient = class {
1248
1222
  async getAccessToken() {
1249
1223
  return this.tokenProvider.getAccessToken();
1250
1224
  }
1251
- async request(path, options = {}) {
1252
- return this.server._requestAsTenant(await this.getAccessToken(), path, options);
1225
+ async request(path2, options = {}) {
1226
+ return this.server._requestAsTenant(await this.getAccessToken(), path2, options);
1227
+ }
1228
+ /** POST /tenant/auth/validate — validates this tenant client's current bearer token. */
1229
+ async validate(context) {
1230
+ return this.server.tenantAuth.validate(await this.getAccessToken(), context);
1253
1231
  }
1254
1232
  };
1255
1233
  function createClient(options = {}) {
@@ -1271,6 +1249,10 @@ var AuthyonServerClientBuilder = class {
1271
1249
  __privateGet(this, _options).clientSecret = clientSecret;
1272
1250
  return this;
1273
1251
  }
1252
+ withClientIp(clientIp) {
1253
+ __privateGet(this, _options).clientIp = clientIp;
1254
+ return this;
1255
+ }
1274
1256
  withBaseUrl(baseUrl, allowInsecureHttp = false) {
1275
1257
  __privateGet(this, _options).baseUrl = baseUrl;
1276
1258
  __privateGet(this, _options).allowInsecureHttp = allowInsecureHttp;
@@ -1294,307 +1276,111 @@ var AuthyonServerClientBuilder = class {
1294
1276
  };
1295
1277
  _options = new WeakMap();
1296
1278
 
1297
- // ../../internal/core/authorization/ability.ts
1298
- var AuthyonAbility = class {
1299
- constructor(rules = [], detectSubjectType = defaultSubjectType) {
1300
- this.detectSubjectType = detectSubjectType;
1301
- this.listeners = /* @__PURE__ */ new Set();
1302
- this.currentRules = rules.map(cloneRule);
1303
- }
1304
- get rules() {
1305
- return this.currentRules;
1306
- }
1307
- can(action, subject, field) {
1308
- const subjectType = typeof subject === "string" ? subject : this.detectSubjectType(subject);
1309
- for (let index = this.currentRules.length - 1; index >= 0; index -= 1) {
1310
- const rule = this.currentRules[index];
1311
- if (!matchesToken(rule.action, action, "manage")) continue;
1312
- if (!matchesToken(rule.subject, subjectType, "all")) continue;
1313
- if (field && rule.fields && !rule.fields.some((value) => matchesField(value, field)))
1314
- continue;
1315
- if (rule.conditions) {
1316
- if (typeof subject === "string" || !matchesConditions(subject, rule.conditions)) continue;
1317
- }
1318
- return !rule.inverted;
1319
- }
1320
- return false;
1321
- }
1322
- cannot(action, subject, field) {
1323
- return !this.can(action, subject, field);
1324
- }
1325
- rulesFor(action, subject) {
1326
- return this.currentRules.filter(
1327
- (rule) => matchesToken(rule.action, action, "manage") && matchesToken(rule.subject, subject, "all")
1279
+ // ../../internal/core/http/tenantFilters.ts
1280
+ var TENANT_FILTER_MAX_VALUES = 25;
1281
+ var TENANT_FILTER_MAX_VALUE_LENGTH = 200;
1282
+ var TENANT_FILTER_MAX_DEPTH = 3;
1283
+ var SCOPES = ["public", "private", "custom"];
1284
+ var KEY_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
1285
+ function assertPath(path2) {
1286
+ if (typeof path2 !== "string" || path2.length === 0) {
1287
+ throw new RangeError("Authyon: a filter path is required, e.g. public.kind.");
1288
+ }
1289
+ const [scope, ...keys] = path2.split(".");
1290
+ if (!SCOPES.includes(scope)) {
1291
+ throw new RangeError(
1292
+ `Authyon: unknown filter scope "${scope}" \u2014 use ${SCOPES.join(", ")} (e.g. public.kind).`
1328
1293
  );
1329
1294
  }
1330
- update(rules) {
1331
- this.currentRules = rules.map(cloneRule);
1332
- for (const listener of this.listeners) listener(this.rules);
1295
+ if (keys.length === 0) {
1296
+ throw new RangeError(`Authyon: filter path "${path2}" needs a key after the scope.`);
1333
1297
  }
1334
- on(event, listener) {
1335
- if (event !== "updated") return () => void 0;
1336
- this.listeners.add(listener);
1337
- return () => this.listeners.delete(listener);
1338
- }
1339
- };
1340
- var AuthyonAbilityBuilder = class {
1341
- constructor() {
1342
- this.rules = [];
1343
- }
1344
- can(action, subject, conditions, fields) {
1345
- this.rules.push({ action, subject, conditions, fields });
1346
- return this;
1347
- }
1348
- cannot(action, subject, conditions, fields, reason) {
1349
- this.rules.push({ action, subject, conditions, fields, reason, inverted: true });
1350
- return this;
1298
+ if (keys.length > TENANT_FILTER_MAX_DEPTH) {
1299
+ throw new RangeError(
1300
+ `Authyon: filter path "${path2}" goes deeper than ${TENANT_FILTER_MAX_DEPTH} levels.`
1301
+ );
1351
1302
  }
1352
- build(options = {}) {
1353
- return new AuthyonAbility(this.rules, options.detectSubjectType);
1303
+ for (const key of keys) {
1304
+ if (!KEY_SEGMENT.test(key)) {
1305
+ throw new RangeError(
1306
+ `Authyon: invalid filter key "${key}" \u2014 letters, digits, "_" and "-", up to 64 characters.`
1307
+ );
1308
+ }
1354
1309
  }
1355
- };
1356
- function createAuthyonAbility(source = {}, options = {}) {
1357
- return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
1310
+ return path2;
1358
1311
  }
1359
- function hasPermission(source, requiredPermission) {
1360
- const requirement = permissionToRule(requiredPermission);
1361
- if (!requirement || typeof requirement.action !== "string" || typeof requirement.subject !== "string") {
1362
- return false;
1312
+ function assertValue(value, forIn) {
1313
+ if (value === void 0 || value === null) {
1314
+ throw new RangeError("Authyon: a filter value is required.");
1363
1315
  }
1364
- const permissionSource = isPermissionList(source) ? { permissions: source } : source;
1365
- return createAuthyonAbility(permissionSource).can(requirement.action, requirement.subject);
1366
- }
1367
- function isPermissionList(source) {
1368
- return Array.isArray(source);
1369
- }
1370
- function createAuthyonRules(source = {}, options = {}) {
1371
- const permissions = /* @__PURE__ */ new Set([
1372
- ...source.permissions ?? [],
1373
- ...source.scope?.split(/\s+/).filter(Boolean) ?? []
1374
- ]);
1375
- const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
1376
- for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
1377
- rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
1316
+ const text = String(value);
1317
+ if (text.length === 0) {
1318
+ throw new RangeError("Authyon: a filter value may not be empty.");
1378
1319
  }
1379
- rules.push(...(options.rules ?? []).map(cloneRule));
1380
- return rules;
1381
- }
1382
- function permissionToRule(permission) {
1383
- const normalized = permission.trim();
1384
- if (!normalized) return null;
1385
- if (normalized === "*" || normalized === "*:*" || normalized === "all:manage") {
1386
- return { action: "manage", subject: "all" };
1320
+ if (text.length > TENANT_FILTER_MAX_VALUE_LENGTH) {
1321
+ throw new RangeError(
1322
+ `Authyon: a filter value may hold at most ${TENANT_FILTER_MAX_VALUE_LENGTH} characters.`
1323
+ );
1387
1324
  }
1388
- const separator = normalized.lastIndexOf(":");
1389
- if (separator <= 0 || separator === normalized.length - 1) return null;
1390
- const subject = normalized.slice(0, separator);
1391
- const action = normalized.slice(separator + 1);
1392
- return {
1393
- action: action === "*" ? "manage" : action,
1394
- subject: subject === "*" ? "all" : subject
1395
- };
1396
- }
1397
- function matchesToken(value, expected, wildcard) {
1398
- return (Array.isArray(value) ? value : [value]).some(
1399
- (candidate) => candidate === expected || candidate === wildcard || candidate === "*" || matchesSegments(candidate, expected)
1400
- );
1401
- }
1402
- function matchesSegments(pattern, value) {
1403
- const patternSegments = pattern.split(":");
1404
- const valueSegments = value.split(":");
1405
- return patternSegments.length === valueSegments.length && patternSegments.every((segment2, index) => segment2 === "*" || segment2 === valueSegments[index]);
1406
- }
1407
- function matchesField(pattern, field) {
1408
- if (pattern === "*" || pattern === field) return true;
1409
- return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
1325
+ if (text.includes(",")) {
1326
+ throw new RangeError(
1327
+ forIn ? "Authyon: an `in` value may not contain a comma \u2014 pass separate values instead." : "Authyon: a filter value may not contain a comma."
1328
+ );
1329
+ }
1330
+ return text;
1410
1331
  }
1411
- function matchesConditions(subject, conditions) {
1412
- return Object.entries(conditions).every(([path, expected]) => {
1413
- if (path === "$and" && Array.isArray(expected)) {
1414
- return expected.every(
1415
- (condition) => matchesConditions(subject, condition)
1416
- );
1332
+ var tenantFilter = {
1333
+ /** `public.kind:eq:reseller` — the key equals this value. */
1334
+ eq(path2, value) {
1335
+ return `${assertPath(path2)}:eq:${assertValue(value, false)}`;
1336
+ },
1337
+ /** `public.kind:in:reseller,partner` — the key equals any of these (SQL IN). */
1338
+ in(path2, values) {
1339
+ if (!Array.isArray(values) || values.length === 0) {
1340
+ throw new RangeError("Authyon: `in` needs at least one value.");
1417
1341
  }
1418
- if (path === "$or" && Array.isArray(expected)) {
1419
- return expected.some(
1420
- (condition) => matchesConditions(subject, condition)
1421
- );
1342
+ if (values.length > TENANT_FILTER_MAX_VALUES) {
1343
+ throw new RangeError(`Authyon: \`in\` takes at most ${TENANT_FILTER_MAX_VALUES} values.`);
1422
1344
  }
1423
- return matchesValue(readPath(subject, path), expected);
1424
- });
1425
- }
1426
- function matchesValue(actual, expected) {
1427
- if (!isRecord2(expected) || !Object.keys(expected).some((key) => key.startsWith("$"))) {
1428
- return isRecord2(expected) && isRecord2(actual) ? matchesConditions(actual, expected) : Object.is(actual, expected);
1345
+ const unique = [...new Set(values.map((value) => assertValue(value, true)))];
1346
+ return `${assertPath(path2)}:in:${unique.join(",")}`;
1347
+ },
1348
+ /** `public.notes:like:nacional` — the key contains this text, case-insensitive.
1349
+ * The server escapes the LIKE metacharacters, so `100%` means `100%`. */
1350
+ like(path2, text) {
1351
+ return `${assertPath(path2)}:like:${assertValue(text, false)}`;
1352
+ },
1353
+ /** `custom.cnpj:exists` — the key is present, whatever its value. */
1354
+ exists(path2) {
1355
+ return `${assertPath(path2)}:exists`;
1429
1356
  }
1430
- return Object.entries(expected).every(([operator, operand]) => {
1431
- switch (operator) {
1432
- case "$eq":
1433
- return Object.is(actual, operand);
1434
- case "$ne":
1435
- return !Object.is(actual, operand);
1436
- case "$in":
1437
- return Array.isArray(operand) && operand.some((value) => Object.is(actual, value));
1438
- case "$nin":
1439
- return Array.isArray(operand) && !operand.some((value) => Object.is(actual, value));
1440
- case "$gt":
1441
- return typeof actual === "number" && typeof operand === "number" && actual > operand;
1442
- case "$gte":
1443
- return typeof actual === "number" && typeof operand === "number" && actual >= operand;
1444
- case "$lt":
1445
- return typeof actual === "number" && typeof operand === "number" && actual < operand;
1446
- case "$lte":
1447
- return typeof actual === "number" && typeof operand === "number" && actual <= operand;
1448
- case "$exists":
1449
- return operand ? actual !== void 0 : actual === void 0;
1450
- default:
1451
- return false;
1452
- }
1453
- });
1454
- }
1455
- function readPath(value, path) {
1456
- return path.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
1457
- }
1458
- function defaultSubjectType(subject) {
1459
- const explicit = subject.__type ?? subject.type ?? subject.kind;
1460
- if (typeof explicit === "string") return explicit;
1461
- const constructorName = subject.constructor?.name;
1462
- return typeof constructorName === "string" ? constructorName : "Object";
1463
- }
1464
- function cloneRule(rule) {
1465
- return {
1466
- ...rule,
1467
- action: Array.isArray(rule.action) ? [...rule.action] : rule.action,
1468
- subject: Array.isArray(rule.subject) ? [...rule.subject] : rule.subject,
1469
- fields: rule.fields ? [...rule.fields] : void 0
1470
- };
1471
- }
1472
- function isRecord2(value) {
1473
- return typeof value === "object" && value !== null && !Array.isArray(value);
1474
- }
1475
- function isAbilityRule(value) {
1476
- return value !== null;
1477
- }
1357
+ };
1478
1358
 
1479
- // src/integrations/authorization.ts
1480
- var AuthorizationError = class extends Error {
1481
- constructor(status, code, message) {
1482
- super(message);
1483
- this.status = status;
1484
- this.code = code;
1485
- this.name = "AuthorizationError";
1486
- }
1359
+ // ../../internal/core/authorization/tenantPermissions.ts
1360
+ var TenantPermissions = {
1361
+ /** Rename the tenant and change its settings. */
1362
+ SettingsManage: "tenants:settings:manage",
1363
+ /** Invite an address to the tenant. */
1364
+ MembersInvite: "tenants:members:invite",
1365
+ /** Remove a member from the tenant. */
1366
+ MembersRemove: "tenants:members:remove"
1367
+ };
1368
+ var SubtenantPermissions = {
1369
+ /** Read any tenant below one you belong to. */
1370
+ TreeRead: "subtenants:tree:read",
1371
+ /** Rename a tenant below yours, and add or remove its members. */
1372
+ TreeManage: "subtenants:tree:manage",
1373
+ /** Create a tenant underneath one you belong to. */
1374
+ TreeCreate: "subtenants:tree:create",
1375
+ /**
1376
+ * Make a tenant below yours the ACTIVE tenant of the session — acting inside
1377
+ * it rather than on it from outside. Deliberately not the same permission as
1378
+ * {@link SubtenantPermissions.TreeManage}: administering a sub-tenant through
1379
+ * the management endpoints and operating as that sub-tenant are different
1380
+ * powers, and granting the first should not hand over the second.
1381
+ */
1382
+ TreeSwitch: "subtenants:tree:switch"
1487
1383
  };
1488
- async function authorizeToken(client, token, options = {}) {
1489
- if (!token) throw unauthenticated();
1490
- let userId;
1491
- let permissions = [];
1492
- let roles = [];
1493
- let scope;
1494
- if (options.verification === "jwks") {
1495
- if (!options.jwksVerifier) {
1496
- throw new Error("Authyon: `jwksVerifier` is required for JWKS verification");
1497
- }
1498
- let verified;
1499
- try {
1500
- verified = await options.jwksVerifier.verifyAccessToken(token);
1501
- } catch (error) {
1502
- if (!(error instanceof TokenVerificationError)) throw error;
1503
- if (error.code === "token.key_unavailable") {
1504
- throw new AuthorizationError(
1505
- 503,
1506
- "authorization.unavailable",
1507
- "Token verification is temporarily unavailable"
1508
- );
1509
- }
1510
- throw unauthenticated();
1511
- }
1512
- const { claims } = verified;
1513
- userId = claims.sub;
1514
- permissions = claims.permissions ?? [];
1515
- roles = claims.roles ?? [];
1516
- scope = claims.scope;
1517
- } else if (options.verification === "introspect") {
1518
- const identity = await client.introspect(token, { clientIp: options.clientIp });
1519
- if (!identity.active) throw unauthenticated();
1520
- userId = identity.sub;
1521
- permissions = identity.permissions ?? [];
1522
- roles = identity.roles ?? [];
1523
- scope = identity.scope;
1524
- } else {
1525
- const identity = await client.validate(token, { clientIp: options.clientIp });
1526
- if (!identity.valid || !identity.user) throw unauthenticated();
1527
- userId = identity.user.id;
1528
- permissions = identity.user.permissions ?? [];
1529
- }
1530
- const ability = createAuthyonAbility(
1531
- { permissions, roles, scope },
1532
- {
1533
- rules: options.rules,
1534
- roleRules: options.roleRules,
1535
- roles: options.roles,
1536
- detectSubjectType: options.detectSubjectType
1537
- }
1538
- );
1539
- if (options.requirement && !canAccess(ability, options.requirement)) {
1540
- throw new AuthorizationError(403, "authorization.forbidden", "Permission denied");
1541
- }
1542
- return { token, userId, ability, permissions, roles };
1543
- }
1544
- function authorizeRequest(client, request, options = {}) {
1545
- const clientIp = options.resolveClientIp?.(request) ?? options.clientIp;
1546
- return authorizeToken(client, bearerToken(request.headers.get("authorization")), {
1547
- ...options,
1548
- clientIp
1549
- });
1550
- }
1551
- function createExpressAuthorizationMiddleware(client, options = {}) {
1552
- return async (request, response, next) => {
1553
- try {
1554
- const header = request.headers.authorization;
1555
- const clientIp = resolveExpressClientIp(request, options);
1556
- const context = await authorizeToken(
1557
- client,
1558
- bearerToken(Array.isArray(header) ? header[0] : header),
1559
- { ...options, clientIp }
1560
- );
1561
- request[options.requestProperty ?? "authyon"] = context;
1562
- next();
1563
- } catch (error) {
1564
- if (options.passErrorsToNext || !(error instanceof AuthorizationError)) {
1565
- next(error);
1566
- return;
1567
- }
1568
- response.status(error.status).json({ code: error.code, message: error.message });
1569
- }
1570
- };
1571
- }
1572
- function resolveExpressClientIp(request, options) {
1573
- const resolved = options.resolveClientIp?.(request) ?? (options.trustProxy ? request.ip : request.socket?.remoteAddress);
1574
- return resolved ? normalizeClientIp(stripIpv4Prefix(resolved)) : void 0;
1575
- }
1576
- function stripIpv4Prefix(value) {
1577
- return value.startsWith("::ffff:") ? value.slice(7) : value;
1578
- }
1579
- function createAuthorizationErrorResponse(error) {
1580
- if (!(error instanceof AuthorizationError)) throw error;
1581
- return Response.json({ code: error.code, message: error.message }, { status: error.status });
1582
- }
1583
- function canAccess(ability, requirement) {
1584
- return ability.can(requirement.action, requirement.subject, requirement.field);
1585
- }
1586
- function bearerToken(header) {
1587
- const match = header?.match(/^Bearer\s+(.+)$/i);
1588
- if (!match?.[1]) throw unauthenticated();
1589
- return match[1].trim();
1590
- }
1591
- function unauthenticated() {
1592
- return new AuthorizationError(
1593
- 401,
1594
- "authorization.unauthenticated",
1595
- "A valid bearer token is required"
1596
- );
1597
- }
1598
1384
  export {
1599
1385
  AuthorizationError,
1600
1386
  AuthyonAbility,
@@ -1602,15 +1388,19 @@ export {
1602
1388
  AuthyonError,
1603
1389
  AuthyonServerClient,
1604
1390
  AuthyonServerClientBuilder,
1391
+ CLIENT_IP_HEADER,
1605
1392
  ErrorCodes,
1606
1393
  FetchHttpAdapter,
1607
1394
  JwksTokenVerifier,
1608
1395
  LoggingHttpAdapter,
1609
- PlatformScopedClient,
1396
+ SubtenantPermissions,
1397
+ TENANT_FILTER_MAX_DEPTH,
1398
+ TENANT_FILTER_MAX_VALUES,
1399
+ TENANT_FILTER_MAX_VALUE_LENGTH,
1400
+ TenantPermissions,
1610
1401
  TenantScopedClient,
1611
1402
  TokenVerificationError,
1612
1403
  UserScopedClient,
1613
- WorkspaceInvitesClient,
1614
1404
  authorizeRequest,
1615
1405
  authorizeToken,
1616
1406
  createAuthorizationErrorResponse,
@@ -1619,5 +1409,7 @@ export {
1619
1409
  createClient,
1620
1410
  createExpressAuthorizationMiddleware,
1621
1411
  hasPermission,
1622
- normalizeClientIp
1412
+ hasPermissionGroup,
1413
+ normalizeClientIp,
1414
+ tenantFilter
1623
1415
  };