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