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

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,224 @@ 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/http/tenantLookup.ts
250
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
251
+ function tenantLookupPath(idOrSlug) {
252
+ const value = typeof idOrSlug === "string" ? idOrSlug.trim() : "";
253
+ if (!value) throw new RangeError("Authyon: a tenant id or slug is required.");
254
+ if (value.length > 64) throw new RangeError("Authyon: a tenant slug has at most 64 characters.");
255
+ return UUID.test(value) ? `/auth/tenants/${encodeURIComponent(value)}` : `/auth/tenants/by-slug/${encodeURIComponent(value.toLowerCase())}`;
256
+ }
257
+
258
+ // ../../internal/core/security/approvals.ts
259
+ function path(id, suffix = "") {
260
+ if (typeof id !== "string" || !id.trim())
261
+ throw new TypeError("Authyon: an approval id is required.");
262
+ return `/auth/authorizations/${encodeURIComponent(id)}${suffix}`;
263
+ }
264
+ var NO_METHODS = {
265
+ password: false,
266
+ authenticator: false,
267
+ emailCode: false,
268
+ passkey: false,
269
+ passkeyCount: 0,
270
+ recoveryCodes: 0,
271
+ sso: [],
272
+ twoFactor: false
273
+ };
274
+ function subjectSecurity(request) {
275
+ return {
276
+ methods: async () => {
277
+ const me = await request("/auth/me");
278
+ return me.security ?? NO_METHODS;
279
+ },
280
+ approvals: {
281
+ get: (id) => request(path(id)),
282
+ webauthnOptions: (id) => request(path(id, "/webauthn/options"), { method: "POST" }),
283
+ confirm: (id, input) => request(path(id, "/confirm"), { method: "POST", body: input }),
284
+ reject: (id) => request(path(id, "/reject"), { method: "POST" })
285
+ }
286
+ };
287
+ }
288
+
172
289
  // src/client/scopedManagementClient.ts
173
290
  function scopedRequest(request, source) {
174
- return async (path, options = {}) => {
291
+ return async (path2, options = {}) => {
175
292
  const token = typeof source === "function" ? await source() : source;
176
293
  if (typeof token !== "string" || !token.trim() || /\s/u.test(token))
177
294
  throw new TypeError("Authyon: a valid access token is required.");
178
- return request(path, {
295
+ return request(path2, {
179
296
  ...options,
180
297
  headers: { ...options.headers, Authorization: `Bearer ${token}` }
181
298
  });
182
299
  };
183
300
  }
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
301
  var _request;
202
- var PlatformScopedClient = class {
302
+ var UserScopedClient = class {
203
303
  /** @hidden */
204
304
  constructor(request, token) {
205
305
  __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`),
306
+ this.tenants = {
307
+ /**
308
+ * GET /auth/tenants/{tenantId} — one tenant, acting as the user: their own,
309
+ * or one below it with `subtenants:tree:read` on an ancestor.
310
+ */
311
+ get: (tenantId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}`),
312
+ /**
313
+ * One tenant by id **or** slug: a UUID goes to `GET /auth/tenants/{id}`,
314
+ * anything else to `GET /auth/tenants/by-slug/{slug}`. Same rule and answer
315
+ * as `get`; by slug every refusal is `tenant.not_found`. An empty value
316
+ * raises `RangeError` before any request. The slug route needs the Authyon
317
+ * API of 2026-11-26 or newer.
318
+ */
319
+ find: (idOrSlug) => __privateGet(this, _request).call(this, tenantLookupPath(idOrSlug)),
320
+ /**
321
+ * The direct, active sub-tenants of a tenant, acting as the user. One level
322
+ * per call: each row's `childCount` says where the next call is worth
323
+ * making. Needs `subtenants:tree:read` on the tenant or on one above it —
324
+ * even on the user's own tenant, since listing the children is reading
325
+ * below it.
326
+ *
327
+ * Paged like every other `skip`/`take` listing, with `search`, `filter`
328
+ * (public scope only — build them with `tenantFilter`) and `orderBy`; see
329
+ * `SubTenantListOptions`. A bad option raises `RangeError` before any
330
+ * request. Requires the Authyon API of 2026-11-26 or newer.
331
+ */
332
+ subTenants: {
333
+ /** GET /auth/tenants/{tenantId}/subtenants. */
334
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/subtenants`, {
335
+ query: subTenantQuery(options)
336
+ }),
337
+ /**
338
+ * GET /auth/tenants/subtenants — the same, for the tenant the user's token
339
+ * is scoped to (its `tenant_id`). Same permission rule. Answers
340
+ * `tenant.no_active_tenant` when the session never switched into one.
341
+ */
342
+ listCurrent: (options = {}) => __privateGet(this, _request).call(this, "/auth/tenants/subtenants", { query: subTenantQuery(options) })
343
+ },
224
344
  members: {
225
- invite: (workspaceId, input) => __privateGet(this, _request).call(this, `${workspacePath(workspaceId)}/invites`, {
345
+ /** Newest first; `search` matches email, username or name (at most 100 characters). */
346
+ list: (tenantId, options = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
347
+ query: memberQuery(options)
348
+ }),
349
+ /** Adds an existing environment user by email; does not send an invitation email. */
350
+ invite: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members`, {
226
351
  method: "POST",
227
- body: { email: input.email, role: workspaceRole(input.role) }
352
+ body: { email: input.email, roles: input.roles }
228
353
  }),
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)}`, {
354
+ remove: (tenantId, userId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
231
355
  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
356
  })
237
357
  },
358
+ /**
359
+ * Invites by e-mail or by link, acting as the user. Requires the
360
+ * `tenants:members:invite` permission on the tenant.
361
+ */
238
362
  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`, {
363
+ list: (tenantId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`),
364
+ /** Always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
365
+ create: (tenantId, input) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites`, {
270
366
  method: "POST",
271
- body: { email: input.email, roles: input.roles }
367
+ body: {
368
+ email: input.email,
369
+ roles: input.roles,
370
+ sendEmail: input.sendEmail ?? true,
371
+ redirectUri: input.redirectUri
372
+ }
373
+ }),
374
+ /** New link (the previous one stops working), mailed unless `sendEmail` is `false`. */
375
+ resend: (tenantId, inviteId, input = {}) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}/resend`, {
376
+ method: "POST",
377
+ body: { sendEmail: input.sendEmail ?? true }
272
378
  }),
273
- remove: (tenantId, userId) => __privateGet(this, _request2).call(this, `/auth/tenants/${segment(tenantId)}/members/${segment(userId)}`, {
379
+ revoke: (tenantId, inviteId) => __privateGet(this, _request).call(this, `/auth/tenants/${segment(tenantId)}/invites/${segment(inviteId)}`, {
274
380
  method: "DELETE"
275
381
  })
276
382
  }
277
383
  };
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
- });
384
+ __privateSet(this, _request, scopedRequest(request, token));
385
+ this.security = subjectSecurity(__privateGet(this, _request));
297
386
  }
298
387
  };
299
- _request3 = new WeakMap();
388
+ _request = new WeakMap();
389
+
390
+ // src/client/inviteQuery.ts
391
+ var STATUSES = /* @__PURE__ */ new Set([
392
+ "pending",
393
+ "accepted",
394
+ "revoked",
395
+ "expired"
396
+ ]);
397
+ function inviteQuery(options = {}) {
398
+ const { skip, take, search, status } = options;
399
+ if (skip !== void 0 && (!Number.isInteger(skip) || skip < 0 || skip > 2147483647))
400
+ throw new RangeError("Authyon: invalid skip.");
401
+ if (take !== void 0 && (!Number.isInteger(take) || take < 1 || take > 100))
402
+ throw new RangeError("Authyon: take must be between 1 and 100.");
403
+ if (search !== void 0 && (typeof search !== "string" || search.trim().length > 254))
404
+ throw new RangeError("Authyon: search must contain at most 254 characters.");
405
+ let statuses;
406
+ if (status !== void 0) {
407
+ if (!Array.isArray(status)) throw new TypeError("Authyon: status must be an array.");
408
+ const normalized = status.map((s) => String(s).trim().toLowerCase()).filter((s) => s.length > 0);
409
+ const unknown = normalized.find((s) => !STATUSES.has(s));
410
+ if (unknown) throw new RangeError(`Authyon: unknown invite status "${unknown}".`);
411
+ statuses = [...new Set(normalized)];
412
+ if (statuses.length === 0) statuses = void 0;
413
+ }
414
+ return { search: search?.trim() || void 0, skip, take, status: statuses };
415
+ }
300
416
 
301
417
  // ../../internal/core/config/defaults.ts
302
418
  var DEFAULT_BASE_URL = "https://api.authyon.com";
@@ -343,16 +459,45 @@ var ErrorCodes = {
343
459
  EmailTaken: "user.email_taken",
344
460
  PasswordWeak: "user.password_weak",
345
461
  PasswordPwned: "user.password_pwned",
346
- RateLimited: "rate_limited"
462
+ RateLimited: "rate_limited",
463
+ StepUpRequired: "step_up_required",
464
+ InvalidSecondFactorCode: "invalid_code",
465
+ VerificationAttemptsExhausted: "verification_attempts_exhausted",
466
+ MethodNotEnrolled: "method_not_enrolled",
467
+ InvalidApprovalState: "invalid_authorization_state",
468
+ PayloadMismatch: "payload_mismatch",
469
+ ApprovalNotConsumable: "authorization_not_consumable",
470
+ IdempotencyConflict: "idempotency_conflict",
471
+ UserDisabled: "user_disabled",
472
+ UserNotFound: "user_not_found",
473
+ TemporarilyUnavailable: "temporarily_unavailable",
474
+ InsufficientScope: "insufficient_scope",
475
+ CredentialThrottled: "credential_throttled",
476
+ ApprovalNotFound: "authorization_not_found",
477
+ SessionRevoked: "session_revoked",
478
+ TwoFactorTooManyFailures: "user.2fa.too_many_failures"
347
479
  };
480
+ var STANDARD_ERROR_FIELDS = /* @__PURE__ */ new Set([
481
+ "type",
482
+ "status",
483
+ "title",
484
+ "detail",
485
+ "code",
486
+ "error",
487
+ "error_description"
488
+ ]);
348
489
  var AuthyonError = class extends Error {
349
490
  constructor(status, body, options = {}) {
350
- super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
491
+ const detail = body.detail ?? body.error_description;
492
+ super(detail ?? body.title ?? `Authyon request failed with status ${status}`);
351
493
  this.name = "AuthyonError";
352
494
  this.status = status;
353
- this.code = body.code ?? "unknown";
495
+ this.code = body.code ?? body.error ?? "unknown";
354
496
  this.title = body.title ?? "Error";
355
- this.detail = body.detail;
497
+ this.detail = detail;
498
+ this.extensions = Object.fromEntries(
499
+ Object.entries(body).filter(([key]) => !STANDARD_ERROR_FIELDS.has(key))
500
+ );
356
501
  this.requestId = options.requestId;
357
502
  this.retryAfter = options.retryAfter;
358
503
  this.cause = options.cause;
@@ -402,6 +547,7 @@ var AuthyonError = class extends Error {
402
547
  };
403
548
  function classifyError(status, code) {
404
549
  if (code === ErrorCodes.NetworkError) return "network";
550
+ if (code === ErrorCodes.StepUpRequired) return "authentication";
405
551
  if (code === ErrorCodes.Timeout || status === 408) return "timeout";
406
552
  if (code === ErrorCodes.RateLimited || status === 429) return "rate_limit";
407
553
  if (code === ErrorCodes.EmailTaken || status === 409) return "conflict";
@@ -440,14 +586,21 @@ function isRetryable(category) {
440
586
  }
441
587
 
442
588
  // ../../internal/core/http/query.ts
443
- function appendQuery(path, params) {
444
- if (!params) return path;
589
+ function appendQuery(path2, params) {
590
+ if (!params) return path2;
445
591
  const query = new URLSearchParams();
446
592
  for (const [key, value2] of Object.entries(params)) {
447
- if (value2 !== void 0) query.set(key, String(value2));
593
+ if (value2 === void 0) continue;
594
+ if (Array.isArray(value2)) {
595
+ for (const item of value2) {
596
+ if (item !== void 0) query.append(key, String(item));
597
+ }
598
+ continue;
599
+ }
600
+ query.set(key, String(value2));
448
601
  }
449
602
  const value = query.toString();
450
- return value ? `${path}${path.includes("?") ? "&" : "?"}${value}` : path;
603
+ return value ? `${path2}${path2.includes("?") ? "&" : "?"}${value}` : path2;
451
604
  }
452
605
 
453
606
  // ../../internal/core/http/httpAdapter.ts
@@ -516,7 +669,6 @@ function sanitizeUrl(value) {
516
669
  url.username = "";
517
670
  url.password = "";
518
671
  url.hash = "";
519
- url.pathname = url.pathname.replace(/(\/platform\/workspace-invites\/)[^/]+/u, "$1REDACTED");
520
672
  const queryKeys = /* @__PURE__ */ new Set();
521
673
  url.searchParams.forEach((_value, key) => queryKeys.add(key));
522
674
  url.search = queryKeys.size > 0 ? [...queryKeys].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&") : "";
@@ -546,12 +698,12 @@ function createSharedTransport(options) {
546
698
  const httpAdapter = options.httpLogger ? new LoggingHttpAdapter(baseAdapter, options.httpLogger) : baseAdapter;
547
699
  return {
548
700
  baseUrl,
549
- async request(path, init) {
701
+ async request(path2, init) {
550
702
  const controller = new AbortController();
551
703
  const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : void 0;
552
704
  try {
553
705
  return await httpAdapter.request({
554
- url: `${baseUrl}${path}`,
706
+ url: `${baseUrl}${path2}`,
555
707
  method: init.method ?? "GET",
556
708
  headers: normalizeHeaders(init.headers),
557
709
  body: init.body,
@@ -609,11 +761,11 @@ var JsonHttpClient = class {
609
761
  constructor(transport) {
610
762
  this.transport = transport;
611
763
  }
612
- async send(path, options = {}) {
764
+ async send(path2, options = {}) {
613
765
  const headers = { ...options.headers };
614
766
  if (options.body !== void 0) headers["Content-Type"] = "application/json";
615
767
  try {
616
- return await this.transport.request(appendQuery(path, options.query), {
768
+ return await this.transport.request(appendQuery(path2, options.query), {
617
769
  method: options.method ?? "GET",
618
770
  headers,
619
771
  body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
@@ -627,7 +779,9 @@ var JsonHttpClient = class {
627
779
  if (!response.ok) {
628
780
  let body = {};
629
781
  try {
630
- body = await response.json();
782
+ const parsed = await response.json();
783
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
784
+ body = parsed;
631
785
  } catch {
632
786
  }
633
787
  throw new AuthyonError(response.status, body, responseMetadata(response));
@@ -635,15 +789,17 @@ var JsonHttpClient = class {
635
789
  if (response.status === 204) return void 0;
636
790
  return await response.json();
637
791
  }
638
- async request(path, options = {}) {
639
- return this.parse(await this.send(path, options));
792
+ async request(path2, options = {}) {
793
+ return this.parse(await this.send(path2, options));
640
794
  }
641
795
  };
642
796
 
643
797
  // ../../internal/core/http/clientIp.ts
798
+ var CLIENT_IP_HEADER = "X-Authyon-Client-Ip";
644
799
  function clientIpHeaders(context) {
645
800
  if (!context?.clientIp) return {};
646
- return { "X-Forwarded-For": normalizeClientIp(context.clientIp) };
801
+ const ip = normalizeClientIp(context.clientIp);
802
+ return { "X-Forwarded-For": ip, [CLIENT_IP_HEADER]: ip };
647
803
  }
648
804
  function normalizeClientIp(value) {
649
805
  let ip = value.trim();
@@ -798,6 +954,19 @@ function isRecord(value) {
798
954
  }
799
955
 
800
956
  // src/client/authyonServerClient.ts
957
+ var ROOT_PARENT_ID = "00000000-0000-0000-0000-000000000000";
958
+ function tenantListQuery({
959
+ parentId,
960
+ orderBy,
961
+ ...rest
962
+ }) {
963
+ const query = { ...rest };
964
+ if (parentId !== void 0) query.parentId = parentId === null ? ROOT_PARENT_ID : parentId;
965
+ if (orderBy !== void 0) {
966
+ query.orderBy = typeof orderBy === "string" ? orderBy : `${orderBy.field}:${orderBy.direction ?? "asc"}`;
967
+ }
968
+ return query;
969
+ }
801
970
  var _clientSecret;
802
971
  var AuthyonServerClient = class {
803
972
  constructor(options = {}) {
@@ -835,11 +1004,16 @@ var AuthyonServerClient = class {
835
1004
  client_id: credentials.clientId,
836
1005
  client_secret: credentials.clientSecret
837
1006
  }
1007
+ }),
1008
+ /** POST /tenant/auth/validate — validates an already-minted tenant-client bearer token. */
1009
+ validate: (accessToken, context) => this.request("/tenant/auth/validate", {
1010
+ method: "POST",
1011
+ headers: {
1012
+ ...clientIpHeaders(context),
1013
+ Authorization: `Bearer ${accessToken}`
1014
+ }
838
1015
  })
839
1016
  };
840
- this.workspaceInvites = new WorkspaceInvitesClient(
841
- (path, options) => this.http.request(path, options)
842
- );
843
1017
  // ── Environment management (users, tenants, roles, permissions, audit) ───
844
1018
  this.environment = {
845
1019
  users: {
@@ -883,6 +1057,39 @@ var AuthyonServerClient = class {
883
1057
  envBearer: true,
884
1058
  body: { newPassword, reason }
885
1059
  }),
1060
+ /**
1061
+ * POST /env/password-resets — issues a password-reset token for the
1062
+ * account with this address and returns it, so your application can
1063
+ * deliver it in its own e-mail instead of Authyon's. Needs the
1064
+ * `authyon:users:password` scope. Unlike the public forgot-password
1065
+ * request, an unknown address rejects with `user.not_found` (404).
1066
+ * A previous live token for the same account stops working.
1067
+ */
1068
+ issuePasswordReset: (input) => this.request("/env/password-resets", {
1069
+ method: "POST",
1070
+ envBearer: true,
1071
+ body: { ...input, sendEmail: input.sendEmail ?? false }
1072
+ }),
1073
+ /**
1074
+ * POST /auth/password-reset/validate — for a backend hosting the reset
1075
+ * page: checks a token without spending it. Public, needs only the
1076
+ * `envKey`. Rejects with `user.password_reset.invalid` (401) when the
1077
+ * token is unknown, used or expired.
1078
+ */
1079
+ validatePasswordReset: (token) => this.request("/auth/password-reset/validate", { method: "POST", body: { token } }),
1080
+ /**
1081
+ * POST /auth/password-reset/confirm — redeems the token and sets the new
1082
+ * password (every session of the account is signed out). Public, needs
1083
+ * only the `envKey`. Resolves with the `redirectUri` the reset was issued
1084
+ * with, or `null`.
1085
+ */
1086
+ confirmPasswordReset: async (token, newPassword) => {
1087
+ const done = await this.request(
1088
+ "/auth/password-reset/confirm",
1089
+ { method: "POST", body: { token, newPassword } }
1090
+ );
1091
+ return { redirectUri: done?.redirectUri ?? null };
1092
+ },
886
1093
  /** POST /env/users/{userId}/sessions/revoke-all — revokes every session the user has. */
887
1094
  revokeSessions: (userId, reason) => this.request(`/env/users/${encodeURIComponent(userId)}/sessions/revoke-all`, {
888
1095
  method: "POST",
@@ -934,12 +1141,12 @@ var AuthyonServerClient = class {
934
1141
  credentials: {
935
1142
  /** GET /env/tenants/{tenantId}/credentials. Returns metadata only, including revoked credentials. */
936
1143
  list: (tenantId) => allCredentials(
937
- (path, options) => this.request(path, { ...options, envBearer: true }),
1144
+ (path2, options) => this.request(path2, { ...options, envBearer: true }),
938
1145
  `/env/tenants/${segment(tenantId)}/credentials`
939
1146
  ),
940
1147
  /** Paginated searchable listing. Prefer this over loading every credential. */
941
1148
  listPage: (tenantId, options = {}) => credentialPage(
942
- (path, requestOptions) => this.request(path, { ...requestOptions, envBearer: true }),
1149
+ (path2, requestOptions) => this.request(path2, { ...requestOptions, envBearer: true }),
943
1150
  `/env/tenants/${segment(tenantId)}/credentials`,
944
1151
  options
945
1152
  ),
@@ -953,7 +1160,11 @@ var AuthyonServerClient = class {
953
1160
  create: (tenantId, input) => this.request(`/env/tenants/${segment(tenantId)}/credentials`, {
954
1161
  method: "POST",
955
1162
  envBearer: true,
956
- body: { description: input.description, ...lifetimeBody(input), ...permissionsBody(input) }
1163
+ body: {
1164
+ description: input.description,
1165
+ ...lifetimeBody(input),
1166
+ ...permissionsBody(input)
1167
+ }
957
1168
  }),
958
1169
  /** Returns a new secret once while keeping the same client id. */
959
1170
  rotate: (tenantId, credentialId) => this.request(
@@ -972,11 +1183,85 @@ var AuthyonServerClient = class {
972
1183
  envBearer: true
973
1184
  })
974
1185
  },
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. */
1186
+ /**
1187
+ * GET /env/tenants — one page of the environment's tenants.
1188
+ *
1189
+ * `search` matches, case-insensitively and anywhere in the value, the
1190
+ * name, the slug, the description and the raw text of both metadata
1191
+ * documents — so a tenant filed with `{"cnpj":"00.000.000/0001-00"}`
1192
+ * is found by the number, and `cnpj` alone finds every tenant carrying
1193
+ * that key. `take` defaults to 25 and is capped at 100.
1194
+ *
1195
+ * `filter` is the structured half, and the one to reach for when more
1196
+ * than one condition has to hold: each entry is a condition on a JSON
1197
+ * document, they are ANDed with each other and with `search`, and they
1198
+ * run inside the statement — so the envelope keeps describing the
1199
+ * filtered set and you can page through it. Build them with
1200
+ * `tenantFilter`:
1201
+ *
1202
+ * ```ts
1203
+ * const page = await authyon.environment.tenants.list({
1204
+ * filter: [
1205
+ * tenantFilter.in("public.kind", ["reseller", "partner"]),
1206
+ * tenantFilter.in("custom.cnpj", [a, b]),
1207
+ * ],
1208
+ * take: 100,
1209
+ * });
1210
+ * ```
1211
+ *
1212
+ * `parentId` narrows the page to one level of the tree — `children()`
1213
+ * and `roots()` below are the same call with that one option set.
1214
+ *
1215
+ * Against an Authyon API older than 2026-10-21 this route ignored
1216
+ * skip/take/search and answered with a bare array; one older than
1217
+ * 2026-10-22 ignores `filter` and one older than 2026-10-31 ignores
1218
+ * `parentId`, which read as a page that is too wide rather than an error.
1219
+ */
1220
+ list: (params = {}) => this.request("/env/tenants", { envBearer: true, query: tenantListQuery(params) }),
1221
+ /**
1222
+ * One page of a tenant's direct sub-tenants — `list()` with `parentId`.
1223
+ *
1224
+ * Only one level: a node's own children carry `childCount`, so a tree
1225
+ * view asks again where that is above zero instead of reading the whole
1226
+ * subtree to draw the first level of it.
1227
+ */
1228
+ children: (parentTenantId, params = {}) => this.environment.tenants.list({ ...params, parentId: parentTenantId }),
1229
+ /**
1230
+ * One page of the environment's root tenants — `list()` with no parent.
1231
+ *
1232
+ * This is the first level of the tree, and the difference from `list()`
1233
+ * is worth keeping straight: `list()` returns every tenant at every
1234
+ * depth, which is what a flat picker wants and what a tree view must not
1235
+ * start from.
1236
+ */
1237
+ roots: (params = {}) => this.environment.tenants.list({ ...params, parentId: null }),
1238
+ /**
1239
+ * Every sub-tenant in the environment, at any depth and under any
1240
+ * parent — `list()` with `minDepth: 1`. This is the one page
1241
+ * `children()` cannot produce, since it names a single parent, and the
1242
+ * one a flat "all sub-companies" screen wants: the envelope describes
1243
+ * the sub-tenants alone, so the pager stops where they do, and nobody
1244
+ * has to read the whole environment and drop the roots.
1245
+ *
1246
+ * Against an Authyon API older than 2026-10-31 the floor is ignored and
1247
+ * the roots come back too.
1248
+ */
1249
+ subTenants: (params = {}) => this.environment.tenants.list({ ...params, minDepth: 1 }),
1250
+ /**
1251
+ * POST /env/tenants — create a tenant in the environment.
1252
+ *
1253
+ * `parentTenantId` nests it under an existing tenant. The environment's
1254
+ * `maxTenantDepth` has to allow the level — it ships as `1`, roots only,
1255
+ * so this answers `tenant.depth.not_allowed` until an operator raises it
1256
+ * in the console.
1257
+ */
978
1258
  create: (input) => this.request("/env/tenants", { method: "POST", envBearer: true, body: input }),
979
- /** GET /env/tenants/{tenantId} — fetch a tenant by id. */
1259
+ /**
1260
+ * GET /env/tenants/{tenantId} — fetch a tenant by id.
1261
+ *
1262
+ * Returns `ancestors` as well, the chain above it root first, so a
1263
+ * breadcrumb costs this one call rather than one per level.
1264
+ */
980
1265
  get: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, { envBearer: true }),
981
1266
  /** PUT /env/tenants/{tenantId} — update a tenant. */
982
1267
  update: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
@@ -984,22 +1269,84 @@ var AuthyonServerClient = class {
984
1269
  envBearer: true,
985
1270
  body: input
986
1271
  }),
987
- /** DELETE /env/tenants/{tenantId} — delete a tenant. */
1272
+ /** PUT /env/tenants/{tenantId}/metadata - replace public and private metadata. */
1273
+ updateMetadata: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/metadata`, {
1274
+ method: "PUT",
1275
+ envBearer: true,
1276
+ body: input
1277
+ }),
1278
+ /**
1279
+ * POST /env/tenants/{tenantId}/disable — disable without removing tenant
1280
+ * data.
1281
+ *
1282
+ * Disables the branch below it too. A sub-tenant left live under a
1283
+ * disabled parent would go on authenticating its users, which is the one
1284
+ * thing switching a tenant off is there to stop — so check `childCount`
1285
+ * before calling this on a node with children.
1286
+ */
1287
+ disable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/disable`, {
1288
+ method: "POST",
1289
+ envBearer: true
1290
+ }),
1291
+ /**
1292
+ * DELETE /env/tenants/{tenantId} — logically delete (disable) a tenant,
1293
+ * and the branch below it. Same handler as `disable()`.
1294
+ */
988
1295
  delete: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}`, {
989
1296
  method: "DELETE",
990
1297
  envBearer: true
991
1298
  }),
1299
+ /**
1300
+ * POST /env/tenants/{tenantId}/enable — the way back from `disable()`.
1301
+ *
1302
+ * Only this tenant comes back: a sub-tenant that went down with the
1303
+ * cascade stays off until enabled itself, and a tenant under a disabled
1304
+ * parent cannot come back before the parent does
1305
+ * (`tenant.ancestor_disabled`).
1306
+ *
1307
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1308
+ */
1309
+ enable: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/enable`, {
1310
+ method: "POST",
1311
+ envBearer: true
1312
+ }),
1313
+ /**
1314
+ * POST /env/tenants/{tenantId}/move — hang the tenant, with everything
1315
+ * below it, under another parent, or at the root with `null`.
1316
+ *
1317
+ * Refused into itself or one of its own descendants
1318
+ * (`tenant.parent.cycle`), into a switched-off branch, or where the
1319
+ * branch's deepest node would pass the environment's level cap
1320
+ * (`tenant.depth.not_allowed`). Every token minted at the old position
1321
+ * is retired (`tenant.path_stale`), so sessions inside the branch sign
1322
+ * in again.
1323
+ *
1324
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1325
+ */
1326
+ move: (tenantId, parentTenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/move`, {
1327
+ method: "POST",
1328
+ envBearer: true,
1329
+ body: { parentTenantId }
1330
+ }),
992
1331
  members: {
993
1332
  /**
994
1333
  * 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.
1334
+ * user records, with the same shape `environment.users.list()` items
1335
+ * have, plus `tenantRoles` and `tenantPermissions` scoped to this
1336
+ * tenant.
1337
+ *
1338
+ * Paged like every other list: the `Paged<T>` envelope carries
1339
+ * `total` and `hasNext`, `take` defaults to 50 and is capped at 100,
1340
+ * newest member first. `search` matches email, username or name (at
1341
+ * most 100 characters, checked before any request).
1342
+ * Up to the Authyon API of 2026-10-21 this one route answered with a
1343
+ * bare array, so a caller had to page until a short page came back;
1344
+ * against such an API `data` is undefined and the array is the body
1345
+ * itself.
999
1346
  */
1000
1347
  list: (tenantId, params = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
1001
1348
  envBearer: true,
1002
- query: params
1349
+ query: memberQuery(params)
1003
1350
  }),
1004
1351
  /** POST /env/tenants/{tenantId}/members — add a member to a tenant. */
1005
1352
  add: (tenantId, userId, roles) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/members`, {
@@ -1033,6 +1380,69 @@ var AuthyonServerClient = class {
1033
1380
  { method: "DELETE", envBearer: true }
1034
1381
  )
1035
1382
  },
1383
+ /**
1384
+ * Invites by e-mail or by link — for addresses that may not have an
1385
+ * account yet; accepting creates it. Managing them needs the
1386
+ * credential's `authyon:users:write` scope (listing, `authyon:tenants:read`).
1387
+ */
1388
+ invites: {
1389
+ /**
1390
+ * GET /env/tenants/{tenantId}/invites — one page of the tenant's
1391
+ * invites, newest first, optionally narrowed by address (`search`)
1392
+ * and by `status`. Up to 0.2.0-beta.26 this returned every invite as
1393
+ * a plain array.
1394
+ */
1395
+ list: (tenantId, options = {}) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
1396
+ envBearer: true,
1397
+ query: inviteQuery(options)
1398
+ }),
1399
+ /**
1400
+ * POST /env/tenants/{tenantId}/invites — invite an address. Always
1401
+ * returns `acceptUrl`; with `sendEmail: false` Authyon does not mail
1402
+ * it and you deliver the link yourself. Valid 7 days, single use, and
1403
+ * not readable again later.
1404
+ */
1405
+ create: (tenantId, input) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/invites`, {
1406
+ method: "POST",
1407
+ envBearer: true,
1408
+ body: {
1409
+ email: input.email,
1410
+ roles: input.roles,
1411
+ sendEmail: input.sendEmail ?? true,
1412
+ redirectUri: input.redirectUri
1413
+ }
1414
+ }),
1415
+ /** POST .../invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1416
+ resend: (tenantId, inviteId, input = {}) => this.request(
1417
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}/resend`,
1418
+ { method: "POST", envBearer: true, body: { sendEmail: input.sendEmail ?? true } }
1419
+ ),
1420
+ /** DELETE /env/tenants/{tenantId}/invites/{inviteId} — revoke a pending invite. */
1421
+ revoke: (tenantId, inviteId) => this.request(
1422
+ `/env/tenants/${encodeURIComponent(tenantId)}/invites/${encodeURIComponent(inviteId)}`,
1423
+ { method: "DELETE", envBearer: true }
1424
+ ),
1425
+ /**
1426
+ * POST /auth/tenant-invites/preview — for a backend hosting the accept
1427
+ * page. Public: needs only `envKey`, the token is the credential.
1428
+ */
1429
+ preview: (token) => this.request("/auth/tenant-invites/preview", { method: "POST", body: { token } }),
1430
+ /**
1431
+ * Joins the tenant; for an address with no account, also creates it
1432
+ * (password required) with the e-mail already confirmed. Does not
1433
+ * sign the user in.
1434
+ *
1435
+ * Without metadata: POST /auth/tenant-invites/accept — public, needs
1436
+ * only `envKey`. With `publicMetadata`/`privateMetadata`: POST
1437
+ * /env/tenant-invites/accept with the environment credential
1438
+ * (`authyon:users:write`), since only your backend may set them.
1439
+ */
1440
+ accept: (input) => input.publicMetadata !== void 0 || input.privateMetadata !== void 0 ? this.request("/env/tenant-invites/accept", {
1441
+ method: "POST",
1442
+ envBearer: true,
1443
+ body: input
1444
+ }) : this.request("/auth/tenant-invites/accept", { method: "POST", body: input })
1445
+ },
1036
1446
  roles: {
1037
1447
  /** GET /env/tenants/{tenantId}/roles — list a tenant's roles. */
1038
1448
  list: (tenantId) => this.request(`/env/tenants/${encodeURIComponent(tenantId)}/roles`, { envBearer: true }),
@@ -1102,6 +1512,60 @@ var AuthyonServerClient = class {
1102
1512
  loginActivity: (params = {}) => this.request("/env/audit/login-activity", { envBearer: true, query: params })
1103
1513
  }
1104
1514
  };
1515
+ // ── Security: one-time codes and approvals ───────────────────────────────
1516
+ //
1517
+ // Everything here runs with the environment credential: `otp` needs the
1518
+ // `authyon:otp:verify` scope, `approvals` needs `authyon:financial:authorize`.
1519
+ // Keep those credentials on the server.
1520
+ this.security = {
1521
+ otp: {
1522
+ /**
1523
+ * POST /env/users/{userId}/otp/verify — checks the user's authenticator
1524
+ * app (TOTP) code. A wrong code returns `{ valid: false }` instead of
1525
+ * throwing. Each code is accepted once; 3 wrong codes in a row sign the
1526
+ * user out everywhere (`sessionsRevoked: true`); 5 lock the check for 15
1527
+ * minutes (`rate_limited`). More than 50 wrong codes in 10 minutes from the
1528
+ * same credential pause it (`credential_throttled`). Needs `authyon:otp:verify`.
1529
+ */
1530
+ check: (userId, code) => this.request(`/env/users/${segment(userId)}/otp/verify`, {
1531
+ method: "POST",
1532
+ envBearer: true,
1533
+ body: { code }
1534
+ })
1535
+ },
1536
+ /**
1537
+ * The customer approves a payload with their authenticator code or
1538
+ * passkey, once.
1539
+ *
1540
+ * 1. `create()` the approval with the payload and the customer.
1541
+ * 2. The customer confirms it (`@authyon/auth` → `security.approvals.confirm`).
1542
+ * 3. `consume()` it right before executing, and execute the returned payload.
1543
+ */
1544
+ approvals: {
1545
+ /** POST /env/authorizations — registers a payload awaiting the customer's approval. */
1546
+ create: (input) => {
1547
+ const { idempotencyKey, ...body } = input;
1548
+ return this.request("/env/authorizations", {
1549
+ method: "POST",
1550
+ envBearer: true,
1551
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : void 0,
1552
+ body
1553
+ });
1554
+ },
1555
+ /** GET /env/authorizations/{id} — current status and, once approved, the assurance evidence. */
1556
+ get: (id) => this.request(`/env/authorizations/${segment(id)}`, { envBearer: true }),
1557
+ /**
1558
+ * POST /env/authorizations/{id}/consume — redeems an approved approval
1559
+ * exactly once and returns the approved payload. Pass `payload` to have
1560
+ * the API check it matches (`payload_mismatch` otherwise).
1561
+ */
1562
+ consume: (id, payload) => this.request(`/env/authorizations/${segment(id)}/consume`, {
1563
+ method: "POST",
1564
+ envBearer: true,
1565
+ body: payload === void 0 ? void 0 : { payload }
1566
+ })
1567
+ }
1568
+ };
1105
1569
  // ── Generic permission grants ─────────────────────────────────────────────
1106
1570
  this.permissions = {
1107
1571
  /** POST /users/{userId}/permissions — grant a permission directly to a user. */
@@ -1119,6 +1583,7 @@ var AuthyonServerClient = class {
1119
1583
  this.envKey = options.envKey;
1120
1584
  this.clientId = options.clientId;
1121
1585
  __privateSet(this, _clientSecret, options.clientSecret);
1586
+ this.clientIp = options.clientIp;
1122
1587
  this.transport = createSharedTransport({
1123
1588
  baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1124
1589
  allowInsecureHttp: options.allowInsecureHttp,
@@ -1144,13 +1609,16 @@ var AuthyonServerClient = class {
1144
1609
  };
1145
1610
  });
1146
1611
  }
1147
- async request(path, options = {}) {
1148
- const headers = { ...options.headers };
1612
+ async request(path2, options = {}) {
1613
+ const headers = {
1614
+ ...clientIpHeaders({ clientIp: this.clientIp }),
1615
+ ...options.headers
1616
+ };
1149
1617
  if (options.envBearer) {
1150
1618
  headers.Authorization = `Bearer ${await this.getEnvironmentAccessToken()}`;
1151
1619
  }
1152
1620
  if (this.envKey) headers["X-Authyon-Environment"] = this.envKey;
1153
- return this.http.request(path, { ...options, headers });
1621
+ return this.http.request(path2, { ...options, headers });
1154
1622
  }
1155
1623
  /** Mints (and caches) an environment access token from `clientId`/`clientSecret`. */
1156
1624
  async getEnvironmentAccessToken() {
@@ -1205,17 +1673,13 @@ var AuthyonServerClient = class {
1205
1673
  tenant(credentials) {
1206
1674
  return new TenantScopedClient(this, credentials);
1207
1675
  }
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
1676
  /** Uses an end-user token; the configured environment key selects the environment. */
1213
1677
  user(token) {
1214
- return new UserScopedClient((path, options) => this.request(path, options), token);
1678
+ return new UserScopedClient((path2, options) => this.request(path2, options), token);
1215
1679
  }
1216
1680
  /** @internal used by {@link TenantScopedClient} to share the base URL/fetch/error handling. */
1217
- _requestAsTenant(accessToken, path, options = {}) {
1218
- return this.request(path, {
1681
+ _requestAsTenant(accessToken, path2, options = {}) {
1682
+ return this.request(path2, {
1219
1683
  ...options,
1220
1684
  headers: { ...options.headers, Authorization: `Bearer ${accessToken}` },
1221
1685
  envBearer: false
@@ -1225,17 +1689,43 @@ var AuthyonServerClient = class {
1225
1689
  _clientSecret = new WeakMap();
1226
1690
  var TenantScopedClient = class {
1227
1691
  constructor(server, credentials) {
1692
+ /** Invites to the token's tenant, by e-mail or by link. */
1693
+ this.invites = {
1694
+ /**
1695
+ * GET /tenant/invites — one page of the tenant's invites, newest first,
1696
+ * optionally narrowed by address (`search`) and by `status`. Up to
1697
+ * 0.2.0-beta.26 this returned every invite as a plain array.
1698
+ */
1699
+ list: (options = {}) => this.request("/tenant/invites", { query: inviteQuery(options) }),
1700
+ /** POST /tenant/invites — always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
1701
+ create: (input) => this.request("/tenant/invites", {
1702
+ method: "POST",
1703
+ body: {
1704
+ email: input.email,
1705
+ roles: input.roles,
1706
+ sendEmail: input.sendEmail ?? true,
1707
+ redirectUri: input.redirectUri
1708
+ }
1709
+ }),
1710
+ /** POST /tenant/invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1711
+ resend: (inviteId, input = {}) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}/resend`, {
1712
+ method: "POST",
1713
+ body: { sendEmail: input.sendEmail ?? true }
1714
+ }),
1715
+ /** DELETE /tenant/invites/{inviteId} — revoke a pending invite. */
1716
+ revoke: (inviteId) => this.request(`/tenant/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" })
1717
+ };
1228
1718
  this.members = {
1229
1719
  /**
1230
1720
  * GET /tenant/members — members of the token's tenant.
1231
1721
  *
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.
1722
+ * Same handler as `/env/tenants/{id}/members` (the tenant comes from the
1723
+ * token instead of the path), so the same `Paged<T>` envelope of full
1724
+ * user records, `take` defaulting to 50 and capped at 100 — as opposed
1725
+ * to `/auth/tenants/{id}/members`'s lightweight member shape. `search`
1726
+ * works the same way too.
1237
1727
  */
1238
- list: (params = {}) => this.request("/tenant/members", { query: params }),
1728
+ list: (params = {}) => this.request("/tenant/members", { query: memberQuery(params) }),
1239
1729
  /** POST /tenant/members — add a member to the token's tenant. */
1240
1730
  add: (userId, roles) => this.request("/tenant/members", { method: "POST", body: { userId, roles } }),
1241
1731
  /** DELETE /tenant/members/{userId} — remove a member from the token's tenant. */
@@ -1292,8 +1782,12 @@ var TenantScopedClient = class {
1292
1782
  async getAccessToken() {
1293
1783
  return this.tokenProvider.getAccessToken();
1294
1784
  }
1295
- async request(path, options = {}) {
1296
- return this.server._requestAsTenant(await this.getAccessToken(), path, options);
1785
+ async request(path2, options = {}) {
1786
+ return this.server._requestAsTenant(await this.getAccessToken(), path2, options);
1787
+ }
1788
+ /** POST /tenant/auth/validate — validates this tenant client's current bearer token. */
1789
+ async validate(context) {
1790
+ return this.server.tenantAuth.validate(await this.getAccessToken(), context);
1297
1791
  }
1298
1792
  };
1299
1793
  function createClient(options = {}) {
@@ -1315,6 +1809,10 @@ var AuthyonServerClientBuilder = class {
1315
1809
  __privateGet(this, _options).clientSecret = clientSecret;
1316
1810
  return this;
1317
1811
  }
1812
+ withClientIp(clientIp) {
1813
+ __privateGet(this, _options).clientIp = clientIp;
1814
+ return this;
1815
+ }
1318
1816
  withBaseUrl(baseUrl, allowInsecureHttp = false) {
1319
1817
  __privateGet(this, _options).baseUrl = baseUrl;
1320
1818
  __privateGet(this, _options).allowInsecureHttp = allowInsecureHttp;
@@ -1338,6 +1836,86 @@ var AuthyonServerClientBuilder = class {
1338
1836
  };
1339
1837
  _options = new WeakMap();
1340
1838
 
1839
+ // ../../internal/core/http/tenantFilters.ts
1840
+ var TENANT_FILTER_MAX_VALUES = 25;
1841
+ var TENANT_FILTER_MAX_VALUE_LENGTH = 200;
1842
+ var TENANT_FILTER_MAX_DEPTH = 3;
1843
+ var SCOPES = ["public", "private", "custom"];
1844
+ var KEY_SEGMENT = /^[A-Za-z0-9_-]{1,64}$/;
1845
+ function assertPath(path2) {
1846
+ if (typeof path2 !== "string" || path2.length === 0) {
1847
+ throw new RangeError("Authyon: a filter path is required, e.g. public.kind.");
1848
+ }
1849
+ const [scope, ...keys] = path2.split(".");
1850
+ if (!SCOPES.includes(scope)) {
1851
+ throw new RangeError(
1852
+ `Authyon: unknown filter scope "${scope}" \u2014 use ${SCOPES.join(", ")} (e.g. public.kind).`
1853
+ );
1854
+ }
1855
+ if (keys.length === 0) {
1856
+ throw new RangeError(`Authyon: filter path "${path2}" needs a key after the scope.`);
1857
+ }
1858
+ if (keys.length > TENANT_FILTER_MAX_DEPTH) {
1859
+ throw new RangeError(
1860
+ `Authyon: filter path "${path2}" goes deeper than ${TENANT_FILTER_MAX_DEPTH} levels.`
1861
+ );
1862
+ }
1863
+ for (const key of keys) {
1864
+ if (!KEY_SEGMENT.test(key)) {
1865
+ throw new RangeError(
1866
+ `Authyon: invalid filter key "${key}" \u2014 letters, digits, "_" and "-", up to 64 characters.`
1867
+ );
1868
+ }
1869
+ }
1870
+ return path2;
1871
+ }
1872
+ function assertValue(value, forIn) {
1873
+ if (value === void 0 || value === null) {
1874
+ throw new RangeError("Authyon: a filter value is required.");
1875
+ }
1876
+ const text = String(value);
1877
+ if (text.length === 0) {
1878
+ throw new RangeError("Authyon: a filter value may not be empty.");
1879
+ }
1880
+ if (text.length > TENANT_FILTER_MAX_VALUE_LENGTH) {
1881
+ throw new RangeError(
1882
+ `Authyon: a filter value may hold at most ${TENANT_FILTER_MAX_VALUE_LENGTH} characters.`
1883
+ );
1884
+ }
1885
+ if (text.includes(",")) {
1886
+ throw new RangeError(
1887
+ forIn ? "Authyon: an `in` value may not contain a comma \u2014 pass separate values instead." : "Authyon: a filter value may not contain a comma."
1888
+ );
1889
+ }
1890
+ return text;
1891
+ }
1892
+ var tenantFilter = {
1893
+ /** `public.kind:eq:reseller` — the key equals this value. */
1894
+ eq(path2, value) {
1895
+ return `${assertPath(path2)}:eq:${assertValue(value, false)}`;
1896
+ },
1897
+ /** `public.kind:in:reseller,partner` — the key equals any of these (SQL IN). */
1898
+ in(path2, values) {
1899
+ if (!Array.isArray(values) || values.length === 0) {
1900
+ throw new RangeError("Authyon: `in` needs at least one value.");
1901
+ }
1902
+ if (values.length > TENANT_FILTER_MAX_VALUES) {
1903
+ throw new RangeError(`Authyon: \`in\` takes at most ${TENANT_FILTER_MAX_VALUES} values.`);
1904
+ }
1905
+ const unique = [...new Set(values.map((value) => assertValue(value, true)))];
1906
+ return `${assertPath(path2)}:in:${unique.join(",")}`;
1907
+ },
1908
+ /** `public.notes:like:nacional` — the key contains this text, case-insensitive.
1909
+ * The server escapes the LIKE metacharacters, so `100%` means `100%`. */
1910
+ like(path2, text) {
1911
+ return `${assertPath(path2)}:like:${assertValue(text, false)}`;
1912
+ },
1913
+ /** `custom.cnpj:exists` — the key is present, whatever its value. */
1914
+ exists(path2) {
1915
+ return `${assertPath(path2)}:exists`;
1916
+ }
1917
+ };
1918
+
1341
1919
  // ../../internal/core/authorization/ability.ts
1342
1920
  var AuthyonAbility = class {
1343
1921
  constructor(rules = [], detectSubjectType = defaultSubjectType) {
@@ -1401,12 +1979,53 @@ function createAuthyonAbility(source = {}, options = {}) {
1401
1979
  return new AuthyonAbility(createAuthyonRules(source, options), options.detectSubjectType);
1402
1980
  }
1403
1981
  function hasPermission(source, requiredPermission) {
1404
- const requirement = permissionToRule(requiredPermission);
1405
- if (!requirement || typeof requirement.action !== "string" || typeof requirement.subject !== "string") {
1406
- return false;
1407
- }
1982
+ const required = requiredPermission?.trim() ?? "";
1983
+ if (!isWellFormedPermission(required)) return false;
1408
1984
  const permissionSource = isPermissionList(source) ? { permissions: source } : source;
1409
- return createAuthyonAbility(permissionSource).can(requirement.action, requirement.subject);
1985
+ const granted = [
1986
+ ...permissionSource.permissions ?? [],
1987
+ ...permissionSource.scope?.split(/\s+/).filter(Boolean) ?? []
1988
+ ];
1989
+ return granted.some((permission) => grants(permission.trim(), required));
1990
+ }
1991
+ function grants(granted, required) {
1992
+ if (!isWellFormedPermission(granted)) return false;
1993
+ if (isFullWildcard(granted)) return true;
1994
+ const grantedSegments = granted.split(":");
1995
+ const requiredSegments = required.split(":");
1996
+ if (isRecursive(grantedSegments) || isRecursive(requiredSegments)) {
1997
+ return grantsRecursive(grantedSegments, requiredSegments);
1998
+ }
1999
+ if (grantedSegments.length !== requiredSegments.length) return false;
2000
+ return grantedSegments.every(
2001
+ (segment2, index) => segment2 === "*" || segment2 === requiredSegments[index]
2002
+ );
2003
+ }
2004
+ var RECURSIVE_WILDCARD = "**";
2005
+ function isRecursive(segments) {
2006
+ return segments[segments.length - 1] === RECURSIVE_WILDCARD;
2007
+ }
2008
+ function grantsRecursive(granted, required) {
2009
+ if (!isRecursive(granted)) return false;
2010
+ if (granted.slice(0, -1).includes(RECURSIVE_WILDCARD)) return false;
2011
+ if (required.slice(0, -1).includes(RECURSIVE_WILDCARD)) return false;
2012
+ const prefix = granted.length - 1;
2013
+ const requiredPinned = isRecursive(required) ? required.length - 1 : required.length;
2014
+ if (isRecursive(required) ? requiredPinned < prefix : requiredPinned <= prefix) return false;
2015
+ for (let index = 0; index < prefix; index++) {
2016
+ if (granted[index] !== "*" && granted[index] !== required[index]) return false;
2017
+ }
2018
+ return true;
2019
+ }
2020
+ function isWellFormedPermission(permission) {
2021
+ if (!permission) return false;
2022
+ const segments = permission.split(":");
2023
+ return segments.length >= 2 && segments.every((segment2) => segment2.length > 0);
2024
+ }
2025
+ function hasPermissionGroup(source, group) {
2026
+ const hasAll = (group.allOf ?? []).every((permission) => hasPermission(source, permission));
2027
+ const hasAny = !group.anyOf?.length || group.anyOf.some((permission) => hasPermission(source, permission));
2028
+ return hasAll && hasAny;
1410
2029
  }
1411
2030
  function isPermissionList(source) {
1412
2031
  return Array.isArray(source);
@@ -1416,13 +2035,23 @@ function createAuthyonRules(source = {}, options = {}) {
1416
2035
  ...source.permissions ?? [],
1417
2036
  ...source.scope?.split(/\s+/).filter(Boolean) ?? []
1418
2037
  ]);
1419
- const rules = [...permissions].map(permissionToRule).filter(isAbilityRule);
2038
+ const rules = [...permissions].map(grantToRule).filter(isAbilityRule);
1420
2039
  for (const role of /* @__PURE__ */ new Set([...source.roles ?? [], ...options.roles ?? []])) {
1421
2040
  rules.push(...(options.roleRules?.[role] ?? []).map(cloneRule));
1422
2041
  }
1423
2042
  rules.push(...(options.rules ?? []).map(cloneRule));
1424
2043
  return rules;
1425
2044
  }
2045
+ function grantToRule(permission) {
2046
+ const normalized = permission.trim();
2047
+ if (normalized && isFullWildcard(normalized)) {
2048
+ return { action: "manage", subject: "all" };
2049
+ }
2050
+ return permissionToRule(normalized);
2051
+ }
2052
+ function isFullWildcard(permission) {
2053
+ return permission.split(":").every((segment2) => segment2 === "*");
2054
+ }
1426
2055
  function permissionToRule(permission) {
1427
2056
  const normalized = permission.trim();
1428
2057
  if (!normalized) return null;
@@ -1453,18 +2082,18 @@ function matchesField(pattern, field) {
1453
2082
  return pattern.endsWith(".*") && field.startsWith(pattern.slice(0, -1));
1454
2083
  }
1455
2084
  function matchesConditions(subject, conditions) {
1456
- return Object.entries(conditions).every(([path, expected]) => {
1457
- if (path === "$and" && Array.isArray(expected)) {
2085
+ return Object.entries(conditions).every(([path2, expected]) => {
2086
+ if (path2 === "$and" && Array.isArray(expected)) {
1458
2087
  return expected.every(
1459
2088
  (condition) => matchesConditions(subject, condition)
1460
2089
  );
1461
2090
  }
1462
- if (path === "$or" && Array.isArray(expected)) {
2091
+ if (path2 === "$or" && Array.isArray(expected)) {
1463
2092
  return expected.some(
1464
2093
  (condition) => matchesConditions(subject, condition)
1465
2094
  );
1466
2095
  }
1467
- return matchesValue(readPath(subject, path), expected);
2096
+ return matchesValue(readPath(subject, path2), expected);
1468
2097
  });
1469
2098
  }
1470
2099
  function matchesValue(actual, expected) {
@@ -1496,8 +2125,8 @@ function matchesValue(actual, expected) {
1496
2125
  }
1497
2126
  });
1498
2127
  }
1499
- function readPath(value, path) {
1500
- return path.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
2128
+ function readPath(value, path2) {
2129
+ return path2.split(".").reduce((current, part) => isRecord2(current) ? current[part] : void 0, value);
1501
2130
  }
1502
2131
  function defaultSubjectType(subject) {
1503
2132
  const explicit = subject.__type ?? subject.type ?? subject.kind;
@@ -1639,6 +2268,32 @@ function unauthenticated() {
1639
2268
  "A valid bearer token is required"
1640
2269
  );
1641
2270
  }
2271
+
2272
+ // ../../internal/core/authorization/tenantPermissions.ts
2273
+ var TenantPermissions = {
2274
+ /** Rename the tenant and change its settings. */
2275
+ SettingsManage: "tenants:settings:manage",
2276
+ /** Invite an address to the tenant. */
2277
+ MembersInvite: "tenants:members:invite",
2278
+ /** Remove a member from the tenant. */
2279
+ MembersRemove: "tenants:members:remove"
2280
+ };
2281
+ var SubtenantPermissions = {
2282
+ /** Read any tenant below one you belong to. */
2283
+ TreeRead: "subtenants:tree:read",
2284
+ /** Rename a tenant below yours, and add or remove its members. */
2285
+ TreeManage: "subtenants:tree:manage",
2286
+ /** Create a tenant underneath one you belong to. */
2287
+ TreeCreate: "subtenants:tree:create",
2288
+ /**
2289
+ * Make a tenant below yours the ACTIVE tenant of the session — acting inside
2290
+ * it rather than on it from outside. Deliberately not the same permission as
2291
+ * {@link SubtenantPermissions.TreeManage}: administering a sub-tenant through
2292
+ * the management endpoints and operating as that sub-tenant are different
2293
+ * powers, and granting the first should not hand over the second.
2294
+ */
2295
+ TreeSwitch: "subtenants:tree:switch"
2296
+ };
1642
2297
  // Annotate the CommonJS export names for ESM import in node:
1643
2298
  0 && (module.exports = {
1644
2299
  AuthorizationError,
@@ -1647,15 +2302,19 @@ function unauthenticated() {
1647
2302
  AuthyonError,
1648
2303
  AuthyonServerClient,
1649
2304
  AuthyonServerClientBuilder,
2305
+ CLIENT_IP_HEADER,
1650
2306
  ErrorCodes,
1651
2307
  FetchHttpAdapter,
1652
2308
  JwksTokenVerifier,
1653
2309
  LoggingHttpAdapter,
1654
- PlatformScopedClient,
2310
+ SubtenantPermissions,
2311
+ TENANT_FILTER_MAX_DEPTH,
2312
+ TENANT_FILTER_MAX_VALUES,
2313
+ TENANT_FILTER_MAX_VALUE_LENGTH,
2314
+ TenantPermissions,
1655
2315
  TenantScopedClient,
1656
2316
  TokenVerificationError,
1657
2317
  UserScopedClient,
1658
- WorkspaceInvitesClient,
1659
2318
  authorizeRequest,
1660
2319
  authorizeToken,
1661
2320
  createAuthorizationErrorResponse,
@@ -1664,5 +2323,7 @@ function unauthenticated() {
1664
2323
  createClient,
1665
2324
  createExpressAuthorizationMiddleware,
1666
2325
  hasPermission,
1667
- normalizeClientIp
2326
+ hasPermissionGroup,
2327
+ normalizeClientIp,
2328
+ tenantFilter
1668
2329
  });