@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.cjs CHANGED
@@ -33,15 +33,19 @@ __export(index_exports, {
33
33
  AuthyonError: () => AuthyonError,
34
34
  AuthyonServerClient: () => AuthyonServerClient,
35
35
  AuthyonServerClientBuilder: () => AuthyonServerClientBuilder,
36
+ CLIENT_IP_HEADER: () => CLIENT_IP_HEADER,
36
37
  ErrorCodes: () => ErrorCodes,
37
38
  FetchHttpAdapter: () => FetchHttpAdapter,
38
39
  JwksTokenVerifier: () => JwksTokenVerifier,
39
40
  LoggingHttpAdapter: () => LoggingHttpAdapter,
40
- PlatformScopedClient: () => PlatformScopedClient,
41
+ SubtenantPermissions: () => SubtenantPermissions,
42
+ TENANT_FILTER_MAX_DEPTH: () => TENANT_FILTER_MAX_DEPTH,
43
+ TENANT_FILTER_MAX_VALUES: () => TENANT_FILTER_MAX_VALUES,
44
+ TENANT_FILTER_MAX_VALUE_LENGTH: () => TENANT_FILTER_MAX_VALUE_LENGTH,
45
+ TenantPermissions: () => TenantPermissions,
41
46
  TenantScopedClient: () => TenantScopedClient,
42
47
  TokenVerificationError: () => TokenVerificationError,
43
48
  UserScopedClient: () => UserScopedClient,
44
- WorkspaceInvitesClient: () => WorkspaceInvitesClient,
45
49
  authorizeRequest: () => authorizeRequest,
46
50
  authorizeToken: () => authorizeToken,
47
51
  createAuthorizationErrorResponse: () => createAuthorizationErrorResponse,
@@ -50,7 +54,9 @@ __export(index_exports, {
50
54
  createClient: () => createClient,
51
55
  createExpressAuthorizationMiddleware: () => createExpressAuthorizationMiddleware,
52
56
  hasPermission: () => hasPermission,
53
- normalizeClientIp: () => normalizeClientIp
57
+ hasPermissionGroup: () => hasPermissionGroup,
58
+ normalizeClientIp: () => normalizeClientIp,
59
+ tenantFilter: () => tenantFilter
54
60
  });
55
61
  module.exports = __toCommonJS(index_exports);
56
62
 
@@ -86,6 +92,25 @@ function lifetimeBody(input) {
86
92
  }
87
93
  return { lifetimeDays: input.lifetimeDays };
88
94
  }
95
+ var MAX_PERMISSION_FILTERS = 20;
96
+ var PERMISSION_FILTER = /^(?:\*|[a-z][a-z0-9_-]*)(?::(?:\*|[a-z][a-z0-9_-]*)){2,4}$/u;
97
+ function permissionFilter(values) {
98
+ if (values === void 0) return void 0;
99
+ if (!Array.isArray(values)) throw new TypeError("Authyon: permissions must be an array.");
100
+ const normalized = values.map((value) => {
101
+ if (typeof value !== "string") throw new TypeError("Authyon: invalid permission.");
102
+ return value.trim().toLowerCase();
103
+ });
104
+ const unique = [...new Set(normalized.filter((value) => value.length > 0))];
105
+ if (unique.length > MAX_PERMISSION_FILTERS)
106
+ throw new RangeError(
107
+ `Authyon: at most ${MAX_PERMISSION_FILTERS} permissions can be filtered at once.`
108
+ );
109
+ for (const value of unique)
110
+ if (!PERMISSION_FILTER.test(value))
111
+ throw new TypeError("Authyon: permissions must have namespace:resource:action format.");
112
+ return unique.length > 0 ? unique : void 0;
113
+ }
89
114
  function credentialQuery(options = {}) {
90
115
  const { skip, take, search } = options;
91
116
  if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
@@ -94,7 +119,8 @@ function credentialQuery(options = {}) {
94
119
  throw new RangeError("Authyon: take must be between 1 and 100.");
95
120
  if (search !== void 0 && (typeof search !== "string" || search.trim().length > 200))
96
121
  throw new RangeError("Authyon: search must contain at most 200 characters.");
97
- return { search: search?.trim() || void 0, skip, take };
122
+ const permission = permissionFilter(options.permissions);
123
+ return { search: search?.trim() || void 0, skip, take, permission };
98
124
  }
99
125
  function credentialSummary(value) {
100
126
  return {
@@ -125,28 +151,28 @@ function credentialDetail(value) {
125
151
  accessTokenLifetimeSeconds: value.accessTokenLifetimeSeconds
126
152
  };
127
153
  }
128
- async function credentialPage(request, path, options = {}) {
154
+ async function credentialPage(request, path2, options = {}) {
129
155
  const query = credentialQuery(options);
130
- const page = await request(path, { query });
156
+ const page = await request(path2, { query });
131
157
  if (!page || !Array.isArray(page.data))
132
158
  throw new TypeError("Authyon: expected a paginated credential response.");
133
159
  return {
134
160
  data: page.data.map(credentialSummary),
135
- ...page.perPage === void 0 ? {} : { perPage: page.perPage },
136
- pageSize: page.pageSize,
161
+ page: page.page,
162
+ perPage: page.perPage,
137
163
  total: page.total,
138
164
  pages: page.pages,
139
165
  hasNext: page.hasNext,
140
166
  hasPrev: page.hasPrev
141
167
  };
142
168
  }
143
- async function allCredentials(request, path) {
169
+ async function allCredentials(request, path2) {
144
170
  const result = [];
145
171
  const seen = /* @__PURE__ */ new Set();
146
172
  let skip = 0;
147
173
  for (let iteration = 0; iteration < 1e3; iteration++) {
148
174
  const page = await request(
149
- path,
175
+ path2,
150
176
  iteration === 0 ? {} : { query: { skip, take: 100 } }
151
177
  );
152
178
  if (Array.isArray(page)) {
@@ -169,134 +195,202 @@ async function allCredentials(request, path) {
169
195
  throw new Error("Authyon: use listPage for more than 1000 credential pages.");
170
196
  }
171
197
 
198
+ // ../../internal/core/http/memberQuery.ts
199
+ function memberQuery(options = {}) {
200
+ const { skip, take, search } = options;
201
+ if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
202
+ throw new RangeError("Authyon: invalid skip.");
203
+ if (take !== void 0 && (!Number.isInteger(take) || take < 1 || take > 100))
204
+ throw new RangeError("Authyon: take must be between 1 and 100.");
205
+ if (search !== void 0 && (typeof search !== "string" || search.trim().length > 100))
206
+ throw new RangeError("Authyon: search must contain at most 100 characters.");
207
+ return { search: search?.trim() || void 0, skip, take };
208
+ }
209
+
210
+ // ../../internal/core/http/subTenantQuery.ts
211
+ var ORDER_FIELDS = ["name", "createdAt", "updatedAt"];
212
+ var MAX_FILTERS = 10;
213
+ var MAX_FILTER_LENGTH = 512;
214
+ function orderByParam(order) {
215
+ if (order === void 0) return void 0;
216
+ const field = typeof order === "string" ? order : order?.field;
217
+ const direction = typeof order === "string" ? "asc" : order.direction ?? "asc";
218
+ if (!ORDER_FIELDS.includes(field))
219
+ throw new RangeError(`Authyon: orderBy must be one of ${ORDER_FIELDS.join(", ")}.`);
220
+ if (direction !== "asc" && direction !== "desc")
221
+ throw new RangeError('Authyon: orderBy direction must be "asc" or "desc".');
222
+ return `${field}:${direction}`;
223
+ }
224
+ function subTenantQuery(options = {}) {
225
+ const { filter, orderBy, ...page } = options;
226
+ const query = { ...memberQuery(page) };
227
+ if (filter !== void 0) {
228
+ if (!Array.isArray(filter)) throw new RangeError("Authyon: filter must be an array.");
229
+ const present = filter.filter((f) => typeof f === "string" && f.trim().length > 0);
230
+ if (present.length !== filter.length)
231
+ throw new RangeError("Authyon: a filter may not be empty \u2014 build it with tenantFilter.");
232
+ if (present.length > MAX_FILTERS)
233
+ throw new RangeError(`Authyon: at most ${MAX_FILTERS} filters per request.`);
234
+ for (const f of present) {
235
+ if (f.length > MAX_FILTER_LENGTH)
236
+ throw new RangeError(`Authyon: a filter may hold at most ${MAX_FILTER_LENGTH} characters.`);
237
+ if (!f.startsWith("public."))
238
+ throw new RangeError(
239
+ `Authyon: sub-tenant listings only filter on the public scope (got "${f.split(":")[0]}").`
240
+ );
241
+ }
242
+ if (present.length > 0) query.filter = present;
243
+ }
244
+ const order = orderByParam(orderBy);
245
+ if (order !== void 0) query.orderBy = order;
246
+ return query;
247
+ }
248
+
249
+ // ../../internal/core/security/approvals.ts
250
+ function path(id, suffix = "") {
251
+ if (typeof id !== "string" || !id.trim())
252
+ throw new TypeError("Authyon: an approval id is required.");
253
+ return `/auth/authorizations/${encodeURIComponent(id)}${suffix}`;
254
+ }
255
+ var NO_METHODS = {
256
+ password: false,
257
+ authenticator: false,
258
+ emailCode: false,
259
+ passkey: false,
260
+ passkeyCount: 0,
261
+ recoveryCodes: 0,
262
+ sso: [],
263
+ twoFactor: false
264
+ };
265
+ function subjectSecurity(request) {
266
+ return {
267
+ methods: async () => {
268
+ const me = await request("/auth/me");
269
+ return me.security ?? NO_METHODS;
270
+ },
271
+ approvals: {
272
+ get: (id) => request(path(id)),
273
+ webauthnOptions: (id) => request(path(id, "/webauthn/options"), { method: "POST" }),
274
+ confirm: (id, input) => request(path(id, "/confirm"), { method: "POST", body: input }),
275
+ reject: (id) => request(path(id, "/reject"), { method: "POST" })
276
+ }
277
+ };
278
+ }
279
+
172
280
  // src/client/scopedManagementClient.ts
173
281
  function scopedRequest(request, source) {
174
- return async (path, options = {}) => {
282
+ return async (path2, options = {}) => {
175
283
  const token = typeof source === "function" ? await source() : source;
176
284
  if (typeof token !== "string" || !token.trim() || /\s/u.test(token))
177
285
  throw new TypeError("Authyon: a valid access token is required.");
178
- return request(path, {
286
+ return request(path2, {
179
287
  ...options,
180
288
  headers: { ...options.headers, Authorization: `Bearer ${token}` }
181
289
  });
182
290
  };
183
291
  }
184
- function environmentPath(scope) {
185
- return `/platform/workspaces/${segment(scope.workspaceId)}/environments/${segment(scope.environmentId)}`;
186
- }
187
- function tenantPath(scope) {
188
- return `${environmentPath(scope)}/tenants/${segment(scope.tenantId)}`;
189
- }
190
- function credentialPath(scope) {
191
- return `${scope.tenantId === void 0 ? environmentPath(scope) : tenantPath(scope)}/credentials`;
192
- }
193
- function workspacePath(id) {
194
- return `/platform/workspaces/${segment(id)}`;
195
- }
196
- function workspaceRole(role) {
197
- if (role !== "admin" && role !== "auditor")
198
- throw new TypeError("Authyon: workspace role must be admin or auditor.");
199
- return role;
200
- }
201
292
  var _request;
202
- var PlatformScopedClient = class {
293
+ var UserScopedClient = class {
203
294
  /** @hidden */
204
295
  constructor(request, token) {
205
296
  __privateAdd(this, _request);
206
- this.credentials = {
207
- list: (scope, options = {}) => credentialPage(__privateGet(this, _request), credentialPath(scope), options),
208
- get: async (scope, credentialId) => credentialDetail(await __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}`)),
209
- create: (scope, input) => __privateGet(this, _request).call(this, credentialPath(scope), {
210
- method: "POST",
211
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
212
- }),
213
- updatePermissions: (scope, credentialId, input) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}/permissions`, {
214
- method: "PUT",
215
- body: permissionsBody(input)
216
- }),
217
- updateScopes: (scope, credentialId, scopes) => this.credentials.updatePermissions(scope, credentialId, { scopes }),
218
- /** Returns a new secret once. API may require an explicit step-up first. */
219
- rotate: (scope, credentialId) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}/rotate`, { method: "POST" }),
220
- revoke: (scope, credentialId) => __privateGet(this, _request).call(this, `${credentialPath(scope)}/${segment(credentialId)}`, { method: "DELETE" })
221
- };
222
- this.workspaces = {
223
- team: (workspaceId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/team`),
297
+ this.tenants = {
298
+ /**
299
+ * The direct, active sub-tenants of a tenant, acting as the user. One level
300
+ * per call: each row's `childCount` says where the next call is worth
301
+ * making. Needs `subtenants:tree:read` on the tenant or on one above it —
302
+ * even on the user's own tenant, since listing the children is reading
303
+ * below it.
304
+ *
305
+ * Paged like every other `skip`/`take` listing, with `search`, `filter`
306
+ * (public scope only — build them with `tenantFilter`) and `orderBy`; see
307
+ * `SubTenantListOptions`. A bad option raises `RangeError` before any
308
+ * request. Requires the Authyon API of 2026-11-26 or newer.
309
+ */
310
+ subTenants: {
311
+ /** GET /auth/tenants/{tenantId}/subtenants. */
312
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/subtenants`, {
313
+ query: subTenantQuery(options)
314
+ }),
315
+ /**
316
+ * GET /auth/tenants/subtenants — the same, for the tenant the user's token
317
+ * is scoped to (its `tenant_id`). Same permission rule. Answers
318
+ * `tenant.no_active_tenant` when the session never switched into one.
319
+ */
320
+ listCurrent: (options = {}) => __privateGet(this, _request).call(this, "/auth/tenants/subtenants", { query: subTenantQuery(options) })
321
+ },
224
322
  members: {
225
- invite: (workspaceId, input) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/invites`, {
323
+ /** Newest first; `search` matches email, username or name (at most 100 characters). */
324
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
325
+ query: memberQuery(options)
326
+ }),
327
+ /** Adds an existing environment user by email; does not send an invitation email. */
328
+ invite: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
226
329
  method: "POST",
227
- body: { email: input.email, role: workspaceRole(input.role) }
330
+ body: { email: input.email, roles: input.roles }
228
331
  }),
229
- /** memberId comes from team.members; it is not the platform userId. */
230
- remove: (workspaceId, memberId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/members/${segment(memberId)}`, {
332
+ remove: (tenantId, userId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
231
333
  method: "DELETE"
232
- }),
233
- changeRole: (workspaceId, memberId, role) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/members/${segment(memberId)}`, {
234
- method: "PATCH",
235
- body: { role: workspaceRole(role) }
236
334
  })
237
335
  },
336
+ /**
337
+ * Invites by e-mail or by link, acting as the user. Requires the
338
+ * `tenants:members:invite` permission on the tenant.
339
+ */
238
340
  invites: {
239
- create: (workspaceId, input) => this.workspaces.members.invite(workspaceId, input),
240
- revoke: (workspaceId, inviteId) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/invites/${segment(inviteId)}`, {
241
- method: "DELETE"
242
- })
243
- }
244
- };
245
- this.tenants = {
246
- members: {
247
- list: (scope, options = {}) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members`, { query: options }),
248
- add: (scope, userId, roles) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members`, { method: "POST", body: { userId, roles } }),
249
- remove: (scope, userId) => __privateGet(this, _request).call(this, `${tenantPath(scope)}/members/${segment(userId)}`, { method: "DELETE" })
250
- }
251
- };
252
- this.auth = {
253
- /** Explicitly confirms the current platform session; passwords are not retained. */
254
- stepUp: (currentPassword) => __privateGet(this, _request).call(this, "/platform/auth/step-up", { method: "POST", body: { currentPassword } })
255
- };
256
- __privateSet(this, _request, scopedRequest(request, token));
257
- }
258
- };
259
- _request = new WeakMap();
260
- var _request2;
261
- var UserScopedClient = class {
262
- /** @hidden */
263
- constructor(request, token) {
264
- __privateAdd(this, _request2);
265
- this.tenants = {
266
- members: {
267
- list: (tenantId, options = {}) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members`, { query: options }),
268
- /** Adds an existing environment user by email; does not send an invitation email. */
269
- invite: (tenantId, input) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
341
+ list: (tenantId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`),
342
+ /** Always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
343
+ create: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`, {
270
344
  method: "POST",
271
- body: { email: input.email, roles: input.roles }
345
+ body: {
346
+ email: input.email,
347
+ roles: input.roles,
348
+ sendEmail: input.sendEmail ?? true,
349
+ redirectUri: input.redirectUri
350
+ }
272
351
  }),
273
- remove: (tenantId, userId) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
352
+ /** New link (the previous one stops working), mailed unless `sendEmail` is `false`. */
353
+ resend: (tenantId, inviteId, input = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}/resend`, {
354
+ method: "POST",
355
+ body: { sendEmail: input.sendEmail ?? true }
356
+ }),
357
+ revoke: (tenantId, inviteId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}`, {
274
358
  method: "DELETE"
275
359
  })
276
360
  }
277
361
  };
278
- __privateSet(this, _request2, scopedRequest(request, token));
279
- }
280
- };
281
- _request2 = new WeakMap();
282
- var _request3;
283
- var WorkspaceInvitesClient = class {
284
- /** @hidden */
285
- constructor(request) {
286
- __privateAdd(this, _request3);
287
- __privateSet(this, _request3, request);
288
- }
289
- preview(token) {
290
- return __privateGet(this, _request3).call(this, `/platform/workspace-invites/${segment(token)}`);
291
- }
292
- accept(token, input = {}) {
293
- return __privateGet(this, _request3).call(this, `/platform/workspace-invites/${segment(token)}/accept`, {
294
- method: "POST",
295
- body: { name: input.name, password: input.password }
296
- });
362
+ __privateSet(this, _request, scopedRequest(request, token));
363
+ this.security = subjectSecurity(__privateGet(this, _request));
297
364
  }
298
365
  };
299
- _request3 = new WeakMap();
366
+ _request = new WeakMap();
367
+
368
+ // src/client/inviteQuery.ts
369
+ var STATUSES = /* @__PURE__ */ new Set([
370
+ "pending",
371
+ "accepted",
372
+ "revoked",
373
+ "expired"
374
+ ]);
375
+ function inviteQuery(options = {}) {
376
+ const { skip, take, search, status } = options;
377
+ if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
378
+ throw new RangeError("Authyon: invalid skip.");
379
+ if (take !== void 0 && (!Number.isInteger(take) || take < 1 || take > 100))
380
+ throw new RangeError("Authyon: take must be between 1 and 100.");
381
+ if (search !== void 0 && (typeof search !== "string" || search.trim().length > 254))
382
+ throw new RangeError("Authyon: search must contain at most 254 characters.");
383
+ let statuses;
384
+ if (status !== void 0) {
385
+ if (!Array.isArray(status)) throw new TypeError("Authyon: status must be an array.");
386
+ const normalized = status.map((s) => String(s).trim().toLowerCase()).filter((s) => s.length > 0);
387
+ const unknown = normalized.find((s) => !STATUSES.has(s));
388
+ if (unknown) throw new RangeError(`Authyon: unknown invite status "${unknown}".`);
389
+ statuses = [...new Set(normalized)];
390
+ if (statuses.length === 0) statuses = void 0;
391
+ }
392
+ return { search: search?.trim() || void 0, skip, take, status: statuses };
393
+ }
300
394
 
301
395
  // ../../internal/core/config/defaults.ts
302
396
  var DEFAULT_BASE_URL = "https://api.authyon.com";
@@ -343,16 +437,45 @@ var ErrorCodes = {
343
437
  EmailTaken: "user.email_taken",
344
438
  PasswordWeak: "user.password_weak",
345
439
  PasswordPwned: "user.password_pwned",
346
- RateLimited: "rate_limited"
440
+ RateLimited: "rate_limited",
441
+ StepUpRequired: "step_up_required",
442
+ InvalidSecondFactorCode: "invalid_code",
443
+ VerificationAttemptsExhausted: "verification_attempts_exhausted",
444
+ MethodNotEnrolled: "method_not_enrolled",
445
+ InvalidApprovalState: "invalid_authorization_state",
446
+ PayloadMismatch: "payload_mismatch",
447
+ ApprovalNotConsumable: "authorization_not_consumable",
448
+ IdempotencyConflict: "idempotency_conflict",
449
+ UserDisabled: "user_disabled",
450
+ UserNotFound: "user_not_found",
451
+ TemporarilyUnavailable: "temporarily_unavailable",
452
+ InsufficientScope: "insufficient_scope",
453
+ CredentialThrottled: "credential_throttled",
454
+ ApprovalNotFound: "authorization_not_found",
455
+ SessionRevoked: "session_revoked",
456
+ TwoFactorTooManyFailures: "user.2fa.too_many_failures"
347
457
  };
458
+ var STANDARD_ERROR_FIELDS = /* @__PURE__ */ new Set([
459
+ "type",
460
+ "status",
461
+ "title",
462
+ "detail",
463
+ "code",
464
+ "error",
465
+ "error_description"
466
+ ]);
348
467
  var AuthyonError = class extends Error {
349
468
  constructor(status, body, options = {}) {
350
- super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
469
+ const detail = body.detail ?? body.error_description;
470
+ super(detail ?? body.title ?? `Authyon request failed with status ${status}`);
351
471
  this.name = "AuthyonError";
352
472
  this.status = status;
353
- this.code = body.code ?? "unknown";
473
+ this.code = body.code ?? body.error ?? "unknown";
354
474
  this.title = body.title ?? "Error";
355
- this.detail = body.detail;
475
+ this.detail = detail;
476
+ this.extensions = Object.fromEntries(
477
+ Object.entries(body).filter(([key]) => !STANDARD_ERROR_FIELDS.has(key))
478
+ );
356
479
  this.requestId = options.requestId;
357
480
  this.retryAfter = options.retryAfter;
358
481
  this.cause = options.cause;
@@ -402,6 +525,7 @@ var AuthyonError = class extends Error {
402
525
  };
403
526
  function classifyError(status, code) {
404
527
  if (code === ErrorCodes.NetworkError) return "network";
528
+ if (code === ErrorCodes.StepUpRequired) return "authentication";
405
529
  if (code === ErrorCodes.Timeout || status === 408) return "timeout";
406
530
  if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
407
531
  if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
@@ -440,14 +564,21 @@ function isRetryable(category) {
440
564
  }
441
565
 
442
566
  // ../../internal/core/http/query.ts
443
- function appendQuery(path, params) {
444
- if (!params) return path;
567
+ function appendQuery(path2, params) {
568
+ if (!params) return path2;
445
569
  const query = new URLSearchParams();
446
570
  for (const [key, value2] of Object.entries(params)) {
447
- if (value2 !== void 0) query.set(key, String(value2));
571
+ if (value2 === void 0) continue;
572
+ if (Array.isArray(value2)) {
573
+ for (const item of value2) {
574
+ if (item !== void 0) query.append(key, String(item));
575
+ }
576
+ continue;
577
+ }
578
+ query.set(key, String(value2));
448
579
  }
449
580
  const value = query.toString();
450
- return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
581
+ return value ? `${path2}${path2.includes("?") ? "&" : "?"}${value}` : path2;
451
582
  }
452
583
 
453
584
  // ../../internal/core/http/httpAdapter.ts
@@ -516,7 +647,6 @@ function sanitizeUrl(value) {
516
647
  url.username = "";
517
648
  url.password = "";
518
649
  url.hash = "";
519
- url.pathname = url.pathname.replace(/(\/platform\/workspace-invites\/)[^/]+/u, "$1REDACTED");
520
650
  const queryKeys = /* @__PURE__ */ new Set();
521
651
  url.searchParams.forEach((_value, key) => queryKeys.add(key));
522
652
  url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
@@ -546,12 +676,12 @@ function createSharedTransport(options) {
546
676
  const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
547
677
  return {
548
678
  baseUrl,
549
- async request(path, init) {
679
+ async request(path2, init) {
550
680
  const controller = new AbortController();
551
681
  const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
552
682
  try {
553
683
  return await httpAdapter.request({
554
- url: `${baseUrl}${path}`,
684
+ url: `${baseUrl}${path2}`,
555
685
  method: init.method ?? "GET",
556
686
  headers: normalizeHeaders(init.headers),
557
687
  body: init.body,
@@ -609,11 +739,11 @@ var JsonHttpClient = class {
609
739
  constructor(transport) {
610
740
  this.transport = transport;
611
741
  }
612
- async send(path, options = {}) {
742
+ async send(path2, options = {}) {
613
743
  const headers = { ...options.headers };
614
744
  if (options.body !== void 0) headers["Content-Type"] = "application/json";
615
745
  try {
616
- return await this.transport.request(appendQuery(path, options.query), {
746
+ return await this.transport.request(appendQuery(path2, options.query), {
617
747
  method: options.method ?? "GET",
618
748
  headers,
619
749
  body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
@@ -627,7 +757,9 @@ var JsonHttpClient = class {
627
757
  if (!response.ok) {
628
758
  let body = {};
629
759
  try {
630
- body = await response.json();
760
+ const parsed = await response.json();
761
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
762
+ body = parsed;
631
763
  } catch {
632
764
  }
633
765
  throw new AuthyonError(response.status, body, responseMetadata(response));
@@ -635,15 +767,17 @@ var JsonHttpClient = class {
635
767
  if (response.status === 204) return void 0;
636
768
  return await response.json();
637
769
  }
638
- async request(path, options = {}) {
639
- return this.parse(await this.send(path, options));
770
+ async request(path2, options = {}) {
771
+ return this.parse(await this.send(path2, options));
640
772
  }
641
773
  };
642
774
 
643
775
  // ../../internal/core/http/clientIp.ts
776
+ var CLIENT_IP_HEADER = "X-Authyon-Client-Ip";
644
777
  function clientIpHeaders(context) {
645
778
  if (!context?.clientIp) return {};
646
- return { "X-Forwarded-For": normalizeClientIp(context.clientIp) };
779
+ const ip = normalizeClientIp(context.clientIp);
780
+ return { "X-Forwarded-For": ip, [CLIENT_IP_HEADER]: ip };
647
781
  }
648
782
  function normalizeClientIp(value) {
649
783
  let ip = value.trim();
@@ -798,6 +932,19 @@ function isRecord(value) {
798
932
  }
799
933
 
800
934
  // src/client/authyonServerClient.ts
935
+ var ROOT_PARENT_ID = "00000000-0000-0000-0000-000000000000";
936
+ function tenantListQuery({
937
+ parentId,
938
+ orderBy,
939
+ ...rest
940
+ }) {
941
+ const query = { ...rest };
942
+ if (parentId !== void 0) query.parentId = parentId === null ? ROOT_PARENT_ID : parentId;
943
+ if (orderBy !== void 0) {
944
+ query.orderBy = typeof orderBy === "string" ? orderBy : `${orderBy.field}:${orderBy.direction ?? "asc"}`;
945
+ }
946
+ return query;
947
+ }
801
948
  var _clientSecret;
802
949
  var AuthyonServerClient = class {
803
950
  constructor(options = {}) {
@@ -835,11 +982,16 @@ var AuthyonServerClient = class {
835
982
  client_id: credentials.clientId,
836
983
  client_secret: credentials.clientSecret
837
984
  }
985
+ }),
986
+ /** POST /tenant/auth/validate — validates an already-minted tenant-client bearer token. */
987
+ validate: (accessToken, context) => this.request("/tenant/auth/validate", {
988
+ method: "POST",
989
+ headers: {
990
+ ...clientIpHeaders(context),
991
+ Authorization: `Bearer ${accessToken}`
992
+ }
838
993
  })
839
994
  };
840
- this.workspaceInvites = new WorkspaceInvitesClient(
841
- (path, options) => this.http.request(path, options)
842
- );
843
995
  // ── Environment management (users, tenants, roles, permissions, audit) ───
844
996
  this.environment = {
845
997
  users: {
@@ -883,6 +1035,39 @@ var AuthyonServerClient = class {
883
1035
  envBearer: true,
884
1036
  body: { newPassword, reason }
885
1037
  }),
1038
+ /**
1039
+ * POST /env/password-resets — issues a password-reset token for the
1040
+ * account with this address and returns it, so your application can
1041
+ * deliver it in its own e-mail instead of Authyon's. Needs the
1042
+ * `authyon:users:password` scope. Unlike the public forgot-password
1043
+ * request, an unknown address rejects with `user.not_found` (404).
1044
+ * A previous live token for the same account stops working.
1045
+ */
1046
+ issuePasswordReset: (input) => this.request("/env/password-resets", {
1047
+ method: "POST",
1048
+ envBearer: true,
1049
+ body: { ...input, sendEmail: input.sendEmail ?? false }
1050
+ }),
1051
+ /**
1052
+ * POST /auth/password-reset/validate — for a backend hosting the reset
1053
+ * page: checks a token without spending it. Public, needs only the
1054
+ * `envKey`. Rejects with `user.password_reset.invalid` (401) when the
1055
+ * token is unknown, used or expired.
1056
+ */
1057
+ validatePasswordReset: (token) => this.request("/auth/password-reset/validate", { method: "POST", body: { token } }),
1058
+ /**
1059
+ * POST /auth/password-reset/confirm — redeems the token and sets the new
1060
+ * password (every session of the account is signed out). Public, needs
1061
+ * only the `envKey`. Resolves with the `redirectUri` the reset was issued
1062
+ * with, or `null`.
1063
+ */
1064
+ confirmPasswordReset: async (token, newPassword) => {
1065
+ const done = await this.request(
1066
+ "/auth/password-reset/confirm",
1067
+ { method: "POST", body: { token, newPassword } }
1068
+ );
1069
+ return { redirectUri: done?.redirectUri ?? null };
1070
+ },
886
1071
  /** POST /env/users/{userId}/sessions/revoke-all — revokes every session the user has. */
887
1072
  revokeSessions: (userId, reason) => this.request(`/env/users/${encodeURIComponent(userId)}/sessions/revoke-all`, {
888
1073
  method: "POST",
@@ -934,12 +1119,12 @@ var AuthyonServerClient = class {
934
1119
  credentials: {
935
1120
  /** GET /env/tenants/{tenantId}/credentials. Returns metadata only, including revoked credentials. */
936
1121
  list: (tenantId) => allCredentials(
937
- (path, options) => this.request(path, { ...options, envBearer: true }),
1122
+ (path2, options) => this.request(path2, { ...options, envBearer: true }),
938
1123
  `/env/tenants/${segment(tenantId)}/credentials`
939
1124
  ),
940
1125
  /** Paginated searchable listing. Prefer this over loading every credential. */
941
1126
  listPage: (tenantId, options = {}) => credentialPage(
942
- (path, requestOptions) => this.request(path, { ...requestOptions, envBearer: true }),
1127
+ (path2, requestOptions) => this.request(path2, { ...requestOptions, envBearer: true }),
943
1128
  `/env/tenants/${segment(tenantId)}/credentials`,
944
1129
  options
945
1130
  ),
@@ -953,7 +1138,11 @@ var AuthyonServerClient = class {
953
1138
  create: (tenantId, input) => this.request(`/env/tenants/${segment(tenantId)}/credentials`, {
954
1139
  method: "POST",
955
1140
  envBearer: true,
956
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
1141
+ body: {
1142
+ description: input.description,
1143
+ ...lifetimeBody(input),
1144
+ ...permissionsBody(input)
1145
+ }
957
1146
  }),
958
1147
  /** Returns a new secret once while keeping the same client id. */
959
1148
  rotate: (tenantId, credentialId) => this.request(
@@ -972,11 +1161,85 @@ var AuthyonServerClient = class {
972
1161
  envBearer: true
973
1162
  })
974
1163
  },
975
- /** GET /env/tenants — paginated, searchable list of tenants in the environment. */
976
- list: (params = {}) => this.request("/env/tenants", { envBearer: true, query: params }),
977
- /** POST /env/tenants — create a tenant in the environment. */
1164
+ /**
1165
+ * GET /env/tenants — one page of the environment's tenants.
1166
+ *
1167
+ * `search` matches, case-insensitively and anywhere in the value, the
1168
+ * name, the slug, the description and the raw text of both metadata
1169
+ * documents — so a tenant filed with `{"cnpj":"00.000.000/0001-00"}`
1170
+ * is found by the number, and `cnpj` alone finds every tenant carrying
1171
+ * that key. `take` defaults to 25 and is capped at 100.
1172
+ *
1173
+ * `filter` is the structured half, and the one to reach for when more
1174
+ * than one condition has to hold: each entry is a condition on a JSON
1175
+ * document, they are ANDed with each other and with `search`, and they
1176
+ * run inside the statement — so the envelope keeps describing the
1177
+ * filtered set and you can page through it. Build them with
1178
+ * `tenantFilter`:
1179
+ *
1180
+ * ```ts
1181
+ * const page = await authyon.environment.tenants.list({
1182
+ * filter: [
1183
+ * tenantFilter.in("public.kind", ["reseller", "partner"]),
1184
+ * tenantFilter.in("custom.cnpj", [a, b]),
1185
+ * ],
1186
+ * take: 100,
1187
+ * });
1188
+ * ```
1189
+ *
1190
+ * `parentId` narrows the page to one level of the tree — `children()`
1191
+ * and `roots()` below are the same call with that one option set.
1192
+ *
1193
+ * Against an Authyon API older than 2026-10-21 this route ignored
1194
+ * skip/take/search and answered with a bare array; one older than
1195
+ * 2026-10-22 ignores `filter` and one older than 2026-10-31 ignores
1196
+ * `parentId`, which read as a page that is too wide rather than an error.
1197
+ */
1198
+ list: (params = {}) => this.request("/env/tenants", { envBearer: true, query: tenantListQuery(params) }),
1199
+ /**
1200
+ * One page of a tenant's direct sub-tenants — `list()` with `parentId`.
1201
+ *
1202
+ * Only one level: a node's own children carry `childCount`, so a tree
1203
+ * view asks again where that is above zero instead of reading the whole
1204
+ * subtree to draw the first level of it.
1205
+ */
1206
+ children: (parentTenantId, params = {}) => this.environment.tenants.list({ ...params, parentId: parentTenantId }),
1207
+ /**
1208
+ * One page of the environment's root tenants — `list()` with no parent.
1209
+ *
1210
+ * This is the first level of the tree, and the difference from `list()`
1211
+ * is worth keeping straight: `list()` returns every tenant at every
1212
+ * depth, which is what a flat picker wants and what a tree view must not
1213
+ * start from.
1214
+ */
1215
+ roots: (params = {}) => this.environment.tenants.list({ ...params, parentId: null }),
1216
+ /**
1217
+ * Every sub-tenant in the environment, at any depth and under any
1218
+ * parent — `list()` with `minDepth: 1`. This is the one page
1219
+ * `children()` cannot produce, since it names a single parent, and the
1220
+ * one a flat "all sub-companies" screen wants: the envelope describes
1221
+ * the sub-tenants alone, so the pager stops where they do, and nobody
1222
+ * has to read the whole environment and drop the roots.
1223
+ *
1224
+ * Against an Authyon API older than 2026-10-31 the floor is ignored and
1225
+ * the roots come back too.
1226
+ */
1227
+ subTenants: (params = {}) => this.environment.tenants.list({ ...params, minDepth: 1 }),
1228
+ /**
1229
+ * POST /env/tenants — create a tenant in the environment.
1230
+ *
1231
+ * `parentTenantId` nests it under an existing tenant. The environment's
1232
+ * `maxTenantDepth` has to allow the level — it ships as `1`, roots only,
1233
+ * so this answers `tenant.depth.not_allowed` until an operator raises it
1234
+ * in the console.
1235
+ */
978
1236
  create: (input) => this.request("/env/tenants", { method: "POST", envBearer: true, body: input }),
979
- /** GET /env/tenants/{tenantId} — fetch a tenant by id. */
1237
+ /**
1238
+ * GET /env/tenants/{tenantId} — fetch a tenant by id.
1239
+ *
1240
+ * Returns `ancestors` as well, the chain above it root first, so a
1241
+ * breadcrumb costs this one call rather than one per level.
1242
+ */
980
1243
  get: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, { envBearer: true }),
981
1244
  /** PUT /env/tenants/{tenantId} — update a tenant. */
982
1245
  update: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
@@ -984,22 +1247,84 @@ var AuthyonServerClient = class {
984
1247
  envBearer: true,
985
1248
  body: input
986
1249
  }),
987
- /** DELETE /env/tenants/{tenantId} — delete a tenant. */
1250
+ /** PUT /env/tenants/{tenantId}/metadata - replace public and private metadata. */
1251
+ updateMetadata: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/metadata`, {
1252
+ method: "PUT",
1253
+ envBearer: true,
1254
+ body: input
1255
+ }),
1256
+ /**
1257
+ * POST /env/tenants/{tenantId}/disable — disable without removing tenant
1258
+ * data.
1259
+ *
1260
+ * Disables the branch below it too. A sub-tenant left live under a
1261
+ * disabled parent would go on authenticating its users, which is the one
1262
+ * thing switching a tenant off is there to stop — so check `childCount`
1263
+ * before calling this on a node with children.
1264
+ */
1265
+ disable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/disable`, {
1266
+ method: "POST",
1267
+ envBearer: true
1268
+ }),
1269
+ /**
1270
+ * DELETE /env/tenants/{tenantId} — logically delete (disable) a tenant,
1271
+ * and the branch below it. Same handler as `disable()`.
1272
+ */
988
1273
  delete: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
989
1274
  method: "DELETE",
990
1275
  envBearer: true
991
1276
  }),
1277
+ /**
1278
+ * POST /env/tenants/{tenantId}/enable — the way back from `disable()`.
1279
+ *
1280
+ * Only this tenant comes back: a sub-tenant that went down with the
1281
+ * cascade stays off until enabled itself, and a tenant under a disabled
1282
+ * parent cannot come back before the parent does
1283
+ * (`tenant.ancestor_disabled`).
1284
+ *
1285
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1286
+ */
1287
+ enable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/enable`, {
1288
+ method: "POST",
1289
+ envBearer: true
1290
+ }),
1291
+ /**
1292
+ * POST /env/tenants/{tenantId}/move — hang the tenant, with everything
1293
+ * below it, under another parent, or at the root with `null`.
1294
+ *
1295
+ * Refused into itself or one of its own descendants
1296
+ * (`tenant.parent.cycle`), into a switched-off branch, or where the
1297
+ * branch's deepest node would pass the environment's level cap
1298
+ * (`tenant.depth.not_allowed`). Every token minted at the old position
1299
+ * is retired (`tenant.path_stale`), so sessions inside the branch sign
1300
+ * in again.
1301
+ *
1302
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1303
+ */
1304
+ move: (tenantId, parentTenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/move`, {
1305
+ method: "POST",
1306
+ envBearer: true,
1307
+ body: { parentTenantId }
1308
+ }),
992
1309
  members: {
993
1310
  /**
994
1311
  * GET /env/tenants/{tenantId}/members — a tenant's members as full
995
- * user records. Confirmed live: a bare array (unlike
996
- * `environment.users.list()`, this one does NOT paginate despite
997
- * accepting `skip`/`take`), with the same shape
998
- * `environment.users.list()` items have.
1312
+ * user records, with the same shape `environment.users.list()` items
1313
+ * have, plus `tenantRoles` and `tenantPermissions` scoped to this
1314
+ * tenant.
1315
+ *
1316
+ * Paged like every other list: the `Paged<T>` envelope carries
1317
+ * `total` and `hasNext`, `take` defaults to 50 and is capped at 100,
1318
+ * newest member first. `search` matches email, username or name (at
1319
+ * most 100 characters, checked before any request).
1320
+ * Up to the Authyon API of 2026-10-21 this one route answered with a
1321
+ * bare array, so a caller had to page until a short page came back;
1322
+ * against such an API `data` is undefined and the array is the body
1323
+ * itself.
999
1324
  */
1000
1325
  list: (tenantId, params = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
1001
1326
  envBearer: true,
1002
- query: params
1327
+ query: memberQuery(params)
1003
1328
  }),
1004
1329
  /** POST /env/tenants/{tenantId}/members — add a member to a tenant. */
1005
1330
  add: (tenantId, userId, roles) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
@@ -1033,6 +1358,69 @@ var AuthyonServerClient = class {
1033
1358
  { method: "DELETE", envBearer: true }
1034
1359
  )
1035
1360
  },
1361
+ /**
1362
+ * Invites by e-mail or by link — for addresses that may not have an
1363
+ * account yet; accepting creates it. Managing them needs the
1364
+ * credential's `authyon:users:write` scope (listing, `authyon:tenants:read`).
1365
+ */
1366
+ invites: {
1367
+ /**
1368
+ * GET /env/tenants/{tenantId}/invites — one page of the tenant's
1369
+ * invites, newest first, optionally narrowed by address (`search`)
1370
+ * and by `status`. Up to 0.2.0-beta.26 this returned every invite as
1371
+ * a plain array.
1372
+ */
1373
+ list: (tenantId, options = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
1374
+ envBearer: true,
1375
+ query: inviteQuery(options)
1376
+ }),
1377
+ /**
1378
+ * POST /env/tenants/{tenantId}/invites — invite an address. Always
1379
+ * returns `acceptUrl`; with `sendEmail: false` Authyon does not mail
1380
+ * it and you deliver the link yourself. Valid 7 days, single use, and
1381
+ * not readable again later.
1382
+ */
1383
+ create: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
1384
+ method: "POST",
1385
+ envBearer: true,
1386
+ body: {
1387
+ email: input.email,
1388
+ roles: input.roles,
1389
+ sendEmail: input.sendEmail ?? true,
1390
+ redirectUri: input.redirectUri
1391
+ }
1392
+ }),
1393
+ /** POST .../invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1394
+ resend: (tenantId, inviteId, input = {}) => this.request(
1395
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}/resend`,
1396
+ { method: "POST", envBearer: true, body: { sendEmail: input.sendEmail ?? true } }
1397
+ ),
1398
+ /** DELETE /env/tenants/{tenantId}/invites/{inviteId} — revoke a pending invite. */
1399
+ revoke: (tenantId, inviteId) => this.request(
1400
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}`,
1401
+ { method: "DELETE", envBearer: true }
1402
+ ),
1403
+ /**
1404
+ * POST /auth/tenant-invites/preview — for a backend hosting the accept
1405
+ * page. Public: needs only `envKey`, the token is the credential.
1406
+ */
1407
+ preview: (token) => this.request("/auth/tenant-invites/preview", { method: "POST", body: { token } }),
1408
+ /**
1409
+ * Joins the tenant; for an address with no account, also creates it
1410
+ * (password required) with the e-mail already confirmed. Does not
1411
+ * sign the user in.
1412
+ *
1413
+ * Without metadata: POST /auth/tenant-invites/accept — public, needs
1414
+ * only `envKey`. With `publicMetadata`/`privateMetadata`: POST
1415
+ * /env/tenant-invites/accept with the environment credential
1416
+ * (`authyon:users:write`), since only your backend may set them.
1417
+ */
1418
+ accept: (input) => input.publicMetadata !== void 0 || input.privateMetadata !== void 0 ? this.request("/env/tenant-invites/accept", {
1419
+ method: "POST",
1420
+ envBearer: true,
1421
+ body: input
1422
+ }) : this.request("/auth/tenant-invites/accept", { method: "POST", body: input })
1423
+ },
1036
1424
  roles: {
1037
1425
  /** GET /env/tenants/{tenantId}/roles — list a tenant's roles. */
1038
1426
  list: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/roles`, { envBearer: true }),
@@ -1102,6 +1490,60 @@ var AuthyonServerClient = class {
1102
1490
  loginActivity: (params = {}) => this.request("/env/audit/login-activity", { envBearer: true, query: params })
1103
1491
  }
1104
1492
  };
1493
+ // ── Security: one-time codes and approvals ───────────────────────────────
1494
+ //
1495
+ // Everything here runs with the environment credential: `otp` needs the
1496
+ // `authyon:otp:verify` scope, `approvals` needs `authyon:financial:authorize`.
1497
+ // Keep those credentials on the server.
1498
+ this.security = {
1499
+ otp: {
1500
+ /**
1501
+ * POST /env/users/{userId}/otp/verify — checks the user's authenticator
1502
+ * app (TOTP) code. A wrong code returns `{ valid: false }` instead of
1503
+ * throwing. Each code is accepted once; 3 wrong codes in a row sign the
1504
+ * user out everywhere (`sessionsRevoked: true`); 5 lock the check for 15
1505
+ * minutes (`rate_limited`). More than 50 wrong codes in 10 minutes from the
1506
+ * same credential pause it (`credential_throttled`). Needs `authyon:otp:verify`.
1507
+ */
1508
+ check: (userId, code) => this.request(`/env/users/${segment(userId)}/otp/verify`, {
1509
+ method: "POST",
1510
+ envBearer: true,
1511
+ body: { code }
1512
+ })
1513
+ },
1514
+ /**
1515
+ * The customer approves a payload with their authenticator code or
1516
+ * passkey, once.
1517
+ *
1518
+ * 1. `create()` the approval with the payload and the customer.
1519
+ * 2. The customer confirms it (`@authyon/auth` → `security.approvals.confirm`).
1520
+ * 3. `consume()` it right before executing, and execute the returned payload.
1521
+ */
1522
+ approvals: {
1523
+ /** POST /env/authorizations — registers a payload awaiting the customer's approval. */
1524
+ create: (input) => {
1525
+ const { idempotencyKey, ...body } = input;
1526
+ return this.request("/env/authorizations", {
1527
+ method: "POST",
1528
+ envBearer: true,
1529
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : void 0,
1530
+ body
1531
+ });
1532
+ },
1533
+ /** GET /env/authorizations/{id} — current status and, once approved, the assurance evidence. */
1534
+ get: (id) => this.request(`/env/authorizations/${segment(id)}`, { envBearer: true }),
1535
+ /**
1536
+ * POST /env/authorizations/{id}/consume — redeems an approved approval
1537
+ * exactly once and returns the approved payload. Pass `payload` to have
1538
+ * the API check it matches (`payload_mismatch` otherwise).
1539
+ */
1540
+ consume: (id, payload) => this.request(`/env/authorizations/${segment(id)}/consume`, {
1541
+ method: "POST",
1542
+ envBearer: true,
1543
+ body: payload === void 0 ? void 0 : { payload }
1544
+ })
1545
+ }
1546
+ };
1105
1547
  // ── Generic permission grants ─────────────────────────────────────────────
1106
1548
  this.permissions = {
1107
1549
  /** POST /users/{userId}/permissions — grant a permission directly to a user. */
@@ -1119,6 +1561,7 @@ var AuthyonServerClient = class {
1119
1561
  this.envKey = options.envKey;
1120
1562
  this.clientId = options.clientId;
1121
1563
  __privateSet(this, _clientSecret, options.clientSecret);
1564
+ this.clientIp = options.clientIp;
1122
1565
  this.transport = createSharedTransport({
1123
1566
  baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1124
1567
  allowInsecureHttp: options.allowInsecureHttp,
@@ -1144,13 +1587,16 @@ var AuthyonServerClient = class {
1144
1587
  };
1145
1588
  });
1146
1589
  }
1147
- async request(path, options = {}) {
1148
- const headers = { ...options.headers };
1590
+ async request(path2, options = {}) {
1591
+ const headers = {
1592
+ ...clientIpHeaders({ clientIp: this.clientIp }),
1593
+ ...options.headers
1594
+ };
1149
1595
  if (options.envBearer) {
1150
1596
  headers.Authorization = `Bearer ${await this.getEnvironmentAccessToken()}`;
1151
1597
  }
1152
1598
  if (this.envKey) headers["X-Authyon-Environment"] = this.envKey;
1153
- return this.http.request(path, { ...options, headers });
1599
+ return this.http.request(path2, { ...options, headers });
1154
1600
  }
1155
1601
  /** Mints (and caches) an environment access token from `clientId`/`clientSecret`. */
1156
1602
  async getEnvironmentAccessToken() {
@@ -1205,17 +1651,13 @@ var AuthyonServerClient = class {
1205
1651
  tenant(credentials) {
1206
1652
  return new TenantScopedClient(this, credentials);
1207
1653
  }
1208
- /** Uses only the supplied platform-user access token. */
1209
- platform(token) {
1210
- return new PlatformScopedClient((path, options) => this.http.request(path, options), token);
1211
- }
1212
1654
  /** Uses an end-user token; the configured environment key selects the environment. */
1213
1655
  user(token) {
1214
- return new UserScopedClient((path, options) => this.request(path, options), token);
1656
+ return new UserScopedClient((path2, options) => this.request(path2, options), token);
1215
1657
  }
1216
1658
  /** @internal used by {@link TenantScopedClient} to share the base URL/fetch/error handling. */
1217
- _requestAsTenant(accessToken, path, options = {}) {
1218
- return this.request(path, {
1659
+ _requestAsTenant(accessToken, path2, options = {}) {
1660
+ return this.request(path2, {
1219
1661
  ...options,
1220
1662
  headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
1221
1663
  envBearer: false
@@ -1225,17 +1667,43 @@ var AuthyonServerClient = class {
1225
1667
  _clientSecret = new WeakMap();
1226
1668
  var TenantScopedClient = class {
1227
1669
  constructor(server, credentials) {
1670
+ /** Invites to the token's tenant, by e-mail or by link. */
1671
+ this.invites = {
1672
+ /**
1673
+ * GET /tenant/invites — one page of the tenant's invites, newest first,
1674
+ * optionally narrowed by address (`search`) and by `status`. Up to
1675
+ * 0.2.0-beta.26 this returned every invite as a plain array.
1676
+ */
1677
+ list: (options = {}) => this.request("/tenant/invites", { query: inviteQuery(options) }),
1678
+ /** POST /tenant/invites — always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
1679
+ create: (input) => this.request("/tenant/invites", {
1680
+ method: "POST",
1681
+ body: {
1682
+ email: input.email,
1683
+ roles: input.roles,
1684
+ sendEmail: input.sendEmail ?? true,
1685
+ redirectUri: input.redirectUri
1686
+ }
1687
+ }),
1688
+ /** POST /tenant/invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1689
+ resend: (inviteId, input = {}) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}/resend`, {
1690
+ method: "POST",
1691
+ body: { sendEmail: input.sendEmail ?? true }
1692
+ }),
1693
+ /** DELETE /tenant/invites/{inviteId} — revoke a pending invite. */
1694
+ revoke: (inviteId) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" })
1695
+ };
1228
1696
  this.members = {
1229
1697
  /**
1230
1698
  * GET /tenant/members — members of the token's tenant.
1231
1699
  *
1232
- * ⚠️ Inferred, not confirmed live (no tenant client credentials
1233
- * available to exchange for a scoped token) — assumed to share
1234
- * `/env/tenants/{id}/members`'s confirmed shape (bare array of full
1235
- * user records), since both are the "admin" member listing as opposed
1236
- * to `/auth/tenants/{id}/members`'s paginated, lightweight one.
1700
+ * Same handler as `/env/tenants/{id}/members` (the tenant comes from the
1701
+ * token instead of the path), so the same `Paged<T>` envelope of full
1702
+ * user records, `take` defaulting to 50 and capped at 100 — as opposed
1703
+ * to `/auth/tenants/{id}/members`'s lightweight member shape. `search`
1704
+ * works the same way too.
1237
1705
  */
1238
- list: (params = {}) => this.request("/tenant/members", { query: params }),
1706
+ list: (params = {}) => this.request("/tenant/members", { query: memberQuery(params) }),
1239
1707
  /** POST /tenant/members — add a member to the token's tenant. */
1240
1708
  add: (userId, roles) => this.request("/tenant/members", { method: "POST", body: { userId, roles } }),
1241
1709
  /** DELETE /tenant/members/{userId} — remove a member from the token's tenant. */
@@ -1292,8 +1760,12 @@ var TenantScopedClient = class {
1292
1760
  async getAccessToken() {
1293
1761
  return this.tokenProvider.getAccessToken();
1294
1762
  }
1295
- async request(path, options = {}) {
1296
- return this.server._requestAsTenant(await this.getAccessToken(), path, options);
1763
+ async request(path2, options = {}) {
1764
+ return this.server._requestAsTenant(await this.getAccessToken(), path2, options);
1765
+ }
1766
+ /** POST /tenant/auth/validate — validates this tenant client's current bearer token. */
1767
+ async validate(context) {
1768
+ return this.server.tenantAuth.validate(await this.getAccessToken(), context);
1297
1769
  }
1298
1770
  };
1299
1771
  function createClient(options = {}) {
@@ -1315,6 +1787,10 @@ var AuthyonServerClientBuilder = class {
1315
1787
  __privateGet(this, _options).clientSecret = clientSecret;
1316
1788
  return this;
1317
1789
  }
1790
+ withClientIp(clientIp) {
1791
+ __privateGet(this, _options).clientIp = clientIp;
1792
+ return this;
1793
+ }
1318
1794
  withBaseUrl(baseUrl, allowInsecureHttp = false) {
1319
1795
  __privateGet(this, _options).baseUrl = baseUrl;
1320
1796
  __privateGet(this, _options).allowInsecureHttp = allowInsecureHttp;
@@ -1338,6 +1814,86 @@ var AuthyonServerClientBuilder = class {
1338
1814
  };
1339
1815
  _options = new WeakMap();
1340
1816
 
1817
+ // ../../internal/core/http/tenantFilters.ts
1818
+ var TENANT_FILTER_MAX_VALUES = 25;
1819
+ var TENANT_FILTER_MAX_VALUE_LENGTH = 200;
1820
+ var TENANT_FILTER_MAX_DEPTH = 3;
1821
+ var SCOPES = ["public", "private", "custom"];
1822
+ var KEY_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
1823
+ function assertPath(path2) {
1824
+ if (typeof path2 !== "string" || path2.length === 0) {
1825
+ throw new RangeError("Authyon: a filter path is required, e.g. public.kind.");
1826
+ }
1827
+ const [scope, ...keys] = path2.split(".");
1828
+ if (!SCOPES.includes(scope)) {
1829
+ throw new RangeError(
1830
+ `Authyon: unknown filter scope "${scope}" \u2014 use ${SCOPES.join(", ")} (e.g. public.kind).`
1831
+ );
1832
+ }
1833
+ if (keys.length === 0) {
1834
+ throw new RangeError(`Authyon: filter path "${path2}" needs a key after the scope.`);
1835
+ }
1836
+ if (keys.length > TENANT_FILTER_MAX_DEPTH) {
1837
+ throw new RangeError(
1838
+ `Authyon: filter path "${path2}" goes deeper than ${TENANT_FILTER_MAX_DEPTH} levels.`
1839
+ );
1840
+ }
1841
+ for (const key of keys) {
1842
+ if (!KEY_SEGMENT.test(key)) {
1843
+ throw new RangeError(
1844
+ `Authyon: invalid filter key "${key}" \u2014 letters, digits, "_" and "-", up to 64 characters.`
1845
+ );
1846
+ }
1847
+ }
1848
+ return path2;
1849
+ }
1850
+ function assertValue(value, forIn) {
1851
+ if (value === void 0 || value === null) {
1852
+ throw new RangeError("Authyon: a filter value is required.");
1853
+ }
1854
+ const text = String(value);
1855
+ if (text.length === 0) {
1856
+ throw new RangeError("Authyon: a filter value may not be empty.");
1857
+ }
1858
+ if (text.length > TENANT_FILTER_MAX_VALUE_LENGTH) {
1859
+ throw new RangeError(
1860
+ `Authyon: a filter value may hold at most ${TENANT_FILTER_MAX_VALUE_LENGTH} characters.`
1861
+ );
1862
+ }
1863
+ if (text.includes(",")) {
1864
+ throw new RangeError(
1865
+ forIn ? "Authyon: an `in` value may not contain a comma \u2014 pass separate values instead." : "Authyon: a filter value may not contain a comma."
1866
+ );
1867
+ }
1868
+ return text;
1869
+ }
1870
+ var tenantFilter = {
1871
+ /** `public.kind:eq:reseller` — the key equals this value. */
1872
+ eq(path2, value) {
1873
+ return `${assertPath(path2)}:eq:${assertValue(value, false)}`;
1874
+ },
1875
+ /** `public.kind:in:reseller,partner` — the key equals any of these (SQL IN). */
1876
+ in(path2, values) {
1877
+ if (!Array.isArray(values) || values.length === 0) {
1878
+ throw new RangeError("Authyon: `in` needs at least one value.");
1879
+ }
1880
+ if (values.length > TENANT_FILTER_MAX_VALUES) {
1881
+ throw new RangeError(`Authyon: \`in\` takes at most ${TENANT_FILTER_MAX_VALUES} values.`);
1882
+ }
1883
+ const unique = [...new Set(values.map((value) => assertValue(value, true)))];
1884
+ return `${assertPath(path2)}:in:${unique.join(",")}`;
1885
+ },
1886
+ /** `public.notes:like:nacional` — the key contains this text, case-insensitive.
1887
+ * The server escapes the LIKE metacharacters, so `100%` means `100%`. */
1888
+ like(path2, text) {
1889
+ return `${assertPath(path2)}:like:${assertValue(text, false)}`;
1890
+ },
1891
+ /** `custom.cnpj:exists` — the key is present, whatever its value. */
1892
+ exists(path2) {
1893
+ return `${assertPath(path2)}:exists`;
1894
+ }
1895
+ };
1896
+
1341
1897
  // ../../internal/core/authorization/ability.ts
1342
1898
  var AuthyonAbility = class {
1343
1899
  constructor(rules = [], detectSubjectType = defaultSubjectType) {
@@ -1401,12 +1957,53 @@ function createAuthyonAbility(source = {}, options = {}) {
1401
1957
  return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
1402
1958
  }
1403
1959
  function hasPermission(source, requiredPermission) {
1404
- const requirement = permissionToRule(requiredPermission);
1405
- if (!requirement || typeof requirement.action !== "string" || typeof requirement.subject !== "string") {
1406
- return false;
1407
- }
1960
+ const required = requiredPermission?.trim() ?? "";
1961
+ if (!isWellFormedPermission(required)) return false;
1408
1962
  const permissionSource = isPermissionList(source) ? { permissions: source } : source;
1409
- return createAuthyonAbility(permissionSource).can(requirement.action, requirement.subject);
1963
+ const granted = [
1964
+ ...permissionSource.permissions ?? [],
1965
+ ...permissionSource.scope?.split(/\s+/).filter(Boolean) ?? []
1966
+ ];
1967
+ return granted.some((permission) => grants(permission.trim(), required));
1968
+ }
1969
+ function grants(granted, required) {
1970
+ if (!isWellFormedPermission(granted)) return false;
1971
+ if (isFullWildcard(granted)) return true;
1972
+ const grantedSegments = granted.split(":");
1973
+ const requiredSegments = required.split(":");
1974
+ if (isRecursive(grantedSegments) || isRecursive(requiredSegments)) {
1975
+ return grantsRecursive(grantedSegments, requiredSegments);
1976
+ }
1977
+ if (grantedSegments.length !== requiredSegments.length) return false;
1978
+ return grantedSegments.every(
1979
+ (segment2, index) => segment2 === "*" || segment2 === requiredSegments[index]
1980
+ );
1981
+ }
1982
+ var RECURSIVE_WILDCARD = "**";
1983
+ function isRecursive(segments) {
1984
+ return segments[segments.length - 1] === RECURSIVE_WILDCARD;
1985
+ }
1986
+ function grantsRecursive(granted, required) {
1987
+ if (!isRecursive(granted)) return false;
1988
+ if (granted.slice(0, -1).includes(RECURSIVE_WILDCARD)) return false;
1989
+ if (required.slice(0, -1).includes(RECURSIVE_WILDCARD)) return false;
1990
+ const prefix = granted.length - 1;
1991
+ const requiredPinned = isRecursive(required) ? required.length - 1 : required.length;
1992
+ if (isRecursive(required) ? requiredPinned < prefix : requiredPinned <= prefix) return false;
1993
+ for (let index = 0; index < prefix; index++) {
1994
+ if (granted[index] !== "*" && granted[index] !== required[index]) return false;
1995
+ }
1996
+ return true;
1997
+ }
1998
+ function isWellFormedPermission(permission) {
1999
+ if (!permission) return false;
2000
+ const segments = permission.split(":");
2001
+ return segments.length >= 2 && segments.every((segment2) => segment2.length > 0);
2002
+ }
2003
+ function hasPermissionGroup(source, group) {
2004
+ const hasAll = (group.allOf ?? []).every((permission) => hasPermission(source, permission));
2005
+ const hasAny = !group.anyOf?.length || group.anyOf.some((permission) => hasPermission(source, permission));
2006
+ return hasAll && hasAny;
1410
2007
  }
1411
2008
  function isPermissionList(source) {
1412
2009
  return Array.isArray(source);
@@ -1416,13 +2013,23 @@ function createAuthyonRules(source = {}, options = {}) {
1416
2013
  ...source.permissions ?? [],
1417
2014
  ...source.scope?.split(/\s+/).filter(Boolean) ?? []
1418
2015
  ]);
1419
- const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
2016
+ const rules = [...permissions].map(grantToRule).filter(isAbilityRule);
1420
2017
  for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
1421
2018
  rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
1422
2019
  }
1423
2020
  rules.push(...(options.rules ?? []).map(cloneRule));
1424
2021
  return rules;
1425
2022
  }
2023
+ function grantToRule(permission) {
2024
+ const normalized = permission.trim();
2025
+ if (normalized && isFullWildcard(normalized)) {
2026
+ return { action: "manage", subject: "all" };
2027
+ }
2028
+ return permissionToRule(normalized);
2029
+ }
2030
+ function isFullWildcard(permission) {
2031
+ return permission.split(":").every((segment2) => segment2 === "*");
2032
+ }
1426
2033
  function permissionToRule(permission) {
1427
2034
  const normalized = permission.trim();
1428
2035
  if (!normalized) return null;
@@ -1453,18 +2060,18 @@ function matchesField(pattern, field) {
1453
2060
  return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
1454
2061
  }
1455
2062
  function matchesConditions(subject, conditions) {
1456
- return Object.entries(conditions).every(([path, expected]) => {
1457
- if (path === "$and" && Array.isArray(expected)) {
2063
+ return Object.entries(conditions).every(([path2, expected]) => {
2064
+ if (path2 === "$and" && Array.isArray(expected)) {
1458
2065
  return expected.every(
1459
2066
  (condition) => matchesConditions(subject, condition)
1460
2067
  );
1461
2068
  }
1462
- if (path === "$or" && Array.isArray(expected)) {
2069
+ if (path2 === "$or" && Array.isArray(expected)) {
1463
2070
  return expected.some(
1464
2071
  (condition) => matchesConditions(subject, condition)
1465
2072
  );
1466
2073
  }
1467
- return matchesValue(readPath(subject, path), expected);
2074
+ return matchesValue(readPath(subject, path2), expected);
1468
2075
  });
1469
2076
  }
1470
2077
  function matchesValue(actual, expected) {
@@ -1496,8 +2103,8 @@ function matchesValue(actual, expected) {
1496
2103
  }
1497
2104
  });
1498
2105
  }
1499
- function readPath(value, path) {
1500
- return path.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
2106
+ function readPath(value, path2) {
2107
+ return path2.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
1501
2108
  }
1502
2109
  function defaultSubjectType(subject) {
1503
2110
  const explicit = subject.__type ?? subject.type ?? subject.kind;
@@ -1639,6 +2246,32 @@ function unauthenticated() {
1639
2246
  "A valid bearer token is required"
1640
2247
  );
1641
2248
  }
2249
+
2250
+ // ../../internal/core/authorization/tenantPermissions.ts
2251
+ var TenantPermissions = {
2252
+ /** Rename the tenant and change its settings. */
2253
+ SettingsManage: "tenants:settings:manage",
2254
+ /** Invite an address to the tenant. */
2255
+ MembersInvite: "tenants:members:invite",
2256
+ /** Remove a member from the tenant. */
2257
+ MembersRemove: "tenants:members:remove"
2258
+ };
2259
+ var SubtenantPermissions = {
2260
+ /** Read any tenant below one you belong to. */
2261
+ TreeRead: "subtenants:tree:read",
2262
+ /** Rename a tenant below yours, and add or remove its members. */
2263
+ TreeManage: "subtenants:tree:manage",
2264
+ /** Create a tenant underneath one you belong to. */
2265
+ TreeCreate: "subtenants:tree:create",
2266
+ /**
2267
+ * Make a tenant below yours the ACTIVE tenant of the session — acting inside
2268
+ * it rather than on it from outside. Deliberately not the same permission as
2269
+ * {@link SubtenantPermissions.TreeManage}: administering a sub-tenant through
2270
+ * the management endpoints and operating as that sub-tenant are different
2271
+ * powers, and granting the first should not hand over the second.
2272
+ */
2273
+ TreeSwitch: "subtenants:tree:switch"
2274
+ };
1642
2275
  // Annotate the CommonJS export names for ESM import in node:
1643
2276
  0 && (module.exports = {
1644
2277
  AuthorizationError,
@@ -1647,15 +2280,19 @@ function unauthenticated() {
1647
2280
  AuthyonError,
1648
2281
  AuthyonServerClient,
1649
2282
  AuthyonServerClientBuilder,
2283
+ CLIENT_IP_HEADER,
1650
2284
  ErrorCodes,
1651
2285
  FetchHttpAdapter,
1652
2286
  JwksTokenVerifier,
1653
2287
  LoggingHttpAdapter,
1654
- PlatformScopedClient,
2288
+ SubtenantPermissions,
2289
+ TENANT_FILTER_MAX_DEPTH,
2290
+ TENANT_FILTER_MAX_VALUES,
2291
+ TENANT_FILTER_MAX_VALUE_LENGTH,
2292
+ TenantPermissions,
1655
2293
  TenantScopedClient,
1656
2294
  TokenVerificationError,
1657
2295
  UserScopedClient,
1658
- WorkspaceInvitesClient,
1659
2296
  authorizeRequest,
1660
2297
  authorizeToken,
1661
2298
  createAuthorizationErrorResponse,
@@ -1664,5 +2301,7 @@ function unauthenticated() {
1664
2301
  createClient,
1665
2302
  createExpressAuthorizationMiddleware,
1666
2303
  hasPermission,
1667
- normalizeClientIp
2304
+ hasPermissionGroup,
2305
+ normalizeClientIp,
2306
+ tenantFilter
1668
2307
  });