@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.
@@ -0,0 +1,1709 @@
1
+ import { JSONWebKeySet, JWTPayload, JWSHeaderParameters } from 'jose';
2
+
3
+ interface HttpAdapterRequest {
4
+ url: string;
5
+ method: string;
6
+ headers: Record<string, string>;
7
+ body?: BodyInit | null;
8
+ signal: AbortSignal;
9
+ }
10
+ /** Transport contract accepted by both Authyon clients. */
11
+ interface HttpAdapter {
12
+ request(request: HttpAdapterRequest): Promise<Response>;
13
+ }
14
+ type HttpLogEvent = {
15
+ type: "request";
16
+ method: string;
17
+ url: string;
18
+ timestamp: number;
19
+ } | {
20
+ type: "response";
21
+ method: string;
22
+ url: string;
23
+ status: number;
24
+ durationMs: number;
25
+ requestId?: string;
26
+ timestamp: number;
27
+ } | {
28
+ type: "error";
29
+ method: string;
30
+ url: string;
31
+ errorName: string;
32
+ durationMs: number;
33
+ timestamp: number;
34
+ };
35
+ /** Receives sanitized HTTP lifecycle events. Headers, bodies and query values are never exposed. */
36
+ type HttpLogger = (event: HttpLogEvent) => void;
37
+ /**
38
+ * Mutable logging configuration. Change `enabled` at runtime to enable or disable logging
39
+ * without recreating the Authyon client.
40
+ */
41
+ interface HttpLoggerOptions {
42
+ enabled: boolean;
43
+ logger?: HttpLogger;
44
+ }
45
+ /** Default adapter backed by the platform's Fetch API. */
46
+ declare class FetchHttpAdapter implements HttpAdapter {
47
+ private readonly fetchImpl;
48
+ constructor(fetchImpl?: typeof fetch);
49
+ request(request: HttpAdapterRequest): Promise<Response>;
50
+ }
51
+ /** Adds safe, configurable lifecycle logging to any HTTP adapter. */
52
+ declare class LoggingHttpAdapter implements HttpAdapter {
53
+ private readonly adapter;
54
+ private readonly options;
55
+ constructor(adapter: HttpAdapter, options: HttpLoggerOptions);
56
+ request(request: HttpAdapterRequest): Promise<Response>;
57
+ private log;
58
+ }
59
+
60
+ /**
61
+ * Security methods active on the user's account, as returned in the
62
+ * `security` field of `GET /auth/me` and `POST /auth/validate`.
63
+ */
64
+ interface SecurityMethods {
65
+ /** A password is set (false for accounts created only through SSO or magic link). */
66
+ password: boolean;
67
+ /** Authenticator app (TOTP one-time codes). */
68
+ authenticator: boolean;
69
+ /** One-time codes sent by email. */
70
+ emailCode: boolean;
71
+ /** At least one passkey registered. */
72
+ passkey: boolean;
73
+ passkeyCount: number;
74
+ /** Unused recovery codes left. */
75
+ recoveryCodes: number;
76
+ /** SSO providers linked to the account, e.g. `["google", "github"]`. */
77
+ sso: string[];
78
+ /** Any second factor is active (authenticator, email code or passkey). */
79
+ twoFactor: boolean;
80
+ }
81
+ /** Lifecycle of an approval. */
82
+ type ApprovalStatus = "pending" | "approved" | "denied" | "consumed" | "expired";
83
+ /**
84
+ * Free-form JSON object describing what the customer approves (up to 16 KiB).
85
+ * The API stores it, shows it back to the customer and binds its canonical
86
+ * hash (keys sorted) to the approval.
87
+ */
88
+ type ApprovalPayload = Record<string, unknown>;
89
+ /** Evidence of how the customer proved their identity when approving. */
90
+ interface ApprovalAssurance {
91
+ /** `urn:authyon:loa:3` (passkey) or `urn:authyon:loa:2` (authenticator code). */
92
+ acr: string;
93
+ /** Authentication methods, e.g. `["pwd", "otp"]` or `["pwd", "webauthn"]`. */
94
+ amr: string[];
95
+ /** When the second factor was verified (ISO 8601). */
96
+ authTime: string;
97
+ }
98
+ /** A request for the customer to approve something with a second factor. */
99
+ interface Approval {
100
+ id: string;
101
+ status: ApprovalStatus;
102
+ subjectId: string;
103
+ tenantId?: string | null;
104
+ /** The payload given to `create()`, with keys in canonical order. */
105
+ payload: ApprovalPayload;
106
+ /** SHA-256 (hex) of the canonical payload. */
107
+ payloadHash: string;
108
+ createdAt: string;
109
+ expiresAt: string;
110
+ decidedAt?: string | null;
111
+ consumedAt?: string | null;
112
+ /** Present once approved. */
113
+ assurance?: ApprovalAssurance | null;
114
+ }
115
+ /** Second factor sent with `confirm()`. */
116
+ type ConfirmApprovalInput = {
117
+ method: "authenticator";
118
+ /** Six-digit code from the customer's authenticator app. */
119
+ code: string;
120
+ } | {
121
+ method: "webauthn";
122
+ /** Assertion for the options returned by `webauthnOptions()`. */
123
+ webAuthn: {
124
+ ceremonyToken: string;
125
+ /** JSON-serialized `PublicKeyCredential` from `navigator.credentials.get()`. */
126
+ assertionJson: string;
127
+ };
128
+ };
129
+ /** Passkey assertion options for approving one approval. */
130
+ interface ApprovalWebAuthnOptions {
131
+ ceremonyToken: string;
132
+ /** JSON `PublicKeyCredentialRequestOptions` to pass to `navigator.credentials.get()`. */
133
+ optionsJson: string;
134
+ }
135
+
136
+ interface PaginationOptions {
137
+ skip?: number;
138
+ take?: number;
139
+ }
140
+ /**
141
+ * Options for a member listing. Always newest member first.
142
+ * `search` keeps members whose email, username or name ("first last")
143
+ * contains it, case-insensitively; `%` and `_` count as text. At most 100
144
+ * characters; blank lists everyone.
145
+ */
146
+ interface MemberListOptions extends PaginationOptions {
147
+ search?: string;
148
+ }
149
+ /**
150
+ * The envelope every paged endpoint answers with.
151
+ *
152
+ * `page` is the 1-based current page and `perPage` is how many items a page
153
+ * holds — the same sense `take` has on the way in. Up to Authyon API
154
+ * 2026-10-21 the two were named `perPage` (holding the page number) and
155
+ * `pageSize` (holding the limit), so reading them by their names gave the
156
+ * wrong value without failing. Clients on the older API see `page` undefined
157
+ * and `perPage` holding a page number.
158
+ */
159
+ interface Paged<T> {
160
+ data: T[];
161
+ page: number;
162
+ perPage: number;
163
+ total: number;
164
+ pages: number;
165
+ hasNext: boolean;
166
+ hasPrev: boolean;
167
+ }
168
+ interface IntrospectResult {
169
+ active: boolean;
170
+ sub?: string;
171
+ username?: string | null;
172
+ email?: string | null;
173
+ roles?: string[] | null;
174
+ permissions?: string[];
175
+ client_id?: string;
176
+ scope?: string;
177
+ exp?: number;
178
+ iat?: number;
179
+ jti?: string;
180
+ token_type?: string;
181
+ }
182
+ /** Fields a tenant listing can order by. */
183
+ type TenantOrderField = "name" | "createdAt" | "updatedAt";
184
+ /**
185
+ * A server-side order: a field as a bare name (ascending) or with a direction.
186
+ * Ties always break on the id, so a row cannot move across a page boundary
187
+ * between two calls.
188
+ */
189
+ type TenantOrder = TenantOrderField | {
190
+ field: TenantOrderField;
191
+ direction?: "asc" | "desc";
192
+ };
193
+ /**
194
+ * Options for a sub-tenant listing on the end-user routes
195
+ * (`/auth/tenants/{id}/subtenants` and `/auth/tenants/subtenants`).
196
+ *
197
+ * The same knobs as the environment's tenant list, cut down to what a member
198
+ * is shown:
199
+ *
200
+ * - `search`: one substring, case-insensitive, over the name, the slug, the
201
+ * description and the public metadata. Never the private metadata. At most
202
+ * 100 characters; blank lists everything.
203
+ * - `filter`: structured conditions, ANDed, at most 10 — build them with
204
+ * `tenantFilter`. Only the `public` scope: a `private.*` or `custom.*`
205
+ * filter would let a member test values they cannot read, so it raises
206
+ * `RangeError` here (and is a 400 `tenant.filter.invalid` on the API).
207
+ * - `orderBy`: `name` (the default, ascending), `createdAt` or `updatedAt`.
208
+ *
209
+ * There is no `status`: only active sub-tenants are listed, since everything
210
+ * below a disabled one is closed to reads from above.
211
+ */
212
+ interface SubTenantListOptions extends PaginationOptions {
213
+ search?: string;
214
+ filter?: string[];
215
+ orderBy?: TenantOrder;
216
+ }
217
+ /** The tenant another one hangs from: enough to name it in a breadcrumb. */
218
+ interface TenantParent {
219
+ id: string;
220
+ slug: string;
221
+ name: string;
222
+ }
223
+ /** One direct sub-tenant, as the end-user sub-tenant listings return it. */
224
+ interface SubTenant {
225
+ id: string;
226
+ slug: string;
227
+ name: string;
228
+ description: string | null;
229
+ /** Distance from the root: `1` for a child of a root. */
230
+ depth: number;
231
+ /** Its own direct sub-tenants. Ask for the next level only where this is above zero. */
232
+ childCount: number;
233
+ /** Whether the user also belongs to it directly. */
234
+ isMember: boolean;
235
+ createdAt: string;
236
+ updatedAt: string;
237
+ /** JSON-encoded metadata visible to members. */
238
+ publicMetadata: string;
239
+ /** The tenant it hangs from — the same on every row of a page, carried so a row stands on its own. */
240
+ parent: TenantParent;
241
+ }
242
+ /**
243
+ * One tenant as the end-user routes return it (`GET /auth/tenants/{id}` and
244
+ * `/auth/tenants/by-slug/{slug}`): the user's own, or one below it read with
245
+ * `subtenants:tree:read` from an ancestor.
246
+ */
247
+ interface MyTenant {
248
+ id: string;
249
+ slug: string;
250
+ name: string;
251
+ description?: string | null;
252
+ createdAt: string;
253
+ updatedAt?: string | null;
254
+ memberCount: number;
255
+ /** Roles the user holds in it; empty when they reach it from an ancestor. */
256
+ myRoles: string[];
257
+ /**
258
+ * The end-user-route permissions the user can use on it, as concrete values.
259
+ * This, not `myRoles`, is what decides which actions to offer.
260
+ */
261
+ myPermissions?: string[];
262
+ /** JSON-encoded metadata visible to members. */
263
+ publicMetadata: string;
264
+ isDisabled: boolean;
265
+ /** Distance from the root: `0` at a root tenant. */
266
+ depth: number;
267
+ /** `true` when the user reaches it from an ancestor rather than as a member. */
268
+ inherited: boolean;
269
+ /** The tenant it hangs from, `null` for a root. */
270
+ parent: TenantParent | null;
271
+ }
272
+
273
+ /**
274
+ * Builders for the tenant list's structured filters.
275
+ *
276
+ * The wire form of one filter is `<scope>.<key>:<op>[:<value>]`, repeated once
277
+ * per condition: `?filter=public.kind:in:reseller,partner&filter=custom.cnpj:eq:000`.
278
+ * Repeating the parameter ANDs the conditions and the comma inside `in` is the
279
+ * OR, which is the whole reason to filter server-side — the conditions are part
280
+ * of the SQL statement, so `total`, `pages` and `hasNext` describe the filtered
281
+ * set. A filter applied to a page after it arrives cannot do that.
282
+ *
283
+ * Scopes map to the three JSON documents a tenant carries: `public` →
284
+ * `publicMetadata`, `private` → `privateMetadata`, `custom` → `customFields`
285
+ * (the one the free-text `search` never covered).
286
+ *
287
+ * The rules below mirror the server's parser, so a typo raises `RangeError`
288
+ * here instead of coming back as a 400 `tenant.filter.invalid`.
289
+ */
290
+ /** One `filter` parameter, ready to send. */
291
+ type TenantFilterExpression = string;
292
+ /** Values the filters accept; numbers and booleans are compared as text, the
293
+ * way `jsonb ->> key` returns them. */
294
+ type TenantFilterValue = string | number | boolean;
295
+ declare const TENANT_FILTER_MAX_VALUES = 25;
296
+ declare const TENANT_FILTER_MAX_VALUE_LENGTH = 200;
297
+ declare const TENANT_FILTER_MAX_DEPTH = 3;
298
+ declare const tenantFilter: {
299
+ /** `public.kind:eq:reseller` — the key equals this value. */
300
+ eq(path: string, value: TenantFilterValue): TenantFilterExpression;
301
+ /** `public.kind:in:reseller,partner` — the key equals any of these (SQL IN). */
302
+ in(path: string, values: readonly TenantFilterValue[]): TenantFilterExpression;
303
+ /** `public.notes:like:nacional` — the key contains this text, case-insensitive.
304
+ * The server escapes the LIKE metacharacters, so `100%` means `100%`. */
305
+ like(path: string, text: string): TenantFilterExpression;
306
+ /** `custom.cnpj:exists` — the key is present, whatever its value. */
307
+ exists(path: string): TenantFilterExpression;
308
+ };
309
+
310
+ /** GET/POST /env/tenants — confirmed against the live API. */
311
+ interface Tenant {
312
+ id: string;
313
+ slug: string;
314
+ name?: string;
315
+ description?: string | null;
316
+ environmentId?: string;
317
+ workspaceId?: string;
318
+ isDisabled?: boolean;
319
+ memberCount?: number;
320
+ createdAt?: string;
321
+ updatedAt?: string;
322
+ /** JSON-encoded values for the tenant's configured custom fields. */
323
+ customFields?: string;
324
+ /** JSON-encoded metadata that may be exposed to tenant members. */
325
+ publicMetadata?: string;
326
+ /** JSON-encoded metadata available only through administrative APIs. */
327
+ privateMetadata?: string;
328
+ /**
329
+ * The tenant this one sits under, or `null` for a root tenant. With `depth`
330
+ * it is what lets a flat page be rendered as the tree it describes.
331
+ *
332
+ * Absent on an API older than 2026-10-31, where every tenant was a root.
333
+ */
334
+ parentTenantId?: string | null;
335
+ /** Distance from the root: `0` for a root tenant. */
336
+ depth?: number;
337
+ /**
338
+ * Direct sub-tenants. A tree view expands only where this is above zero,
339
+ * instead of fetching every node to find out it has no children.
340
+ */
341
+ childCount?: number;
342
+ /** Custom roles defined inside the tenant. Only `get()` returns it. */
343
+ roleCount?: number;
344
+ /**
345
+ * The chain above this tenant, root first, excluding itself — a breadcrumb
346
+ * without a request per level. Empty for a root tenant, and only `get()`
347
+ * returns it.
348
+ */
349
+ ancestors?: TenantAncestor[];
350
+ }
351
+ /** One step of the chain above a tenant, as `Tenant.ancestors` carries it. */
352
+ interface TenantAncestor {
353
+ id: string;
354
+ name: string;
355
+ slug: string;
356
+ isDisabled: boolean;
357
+ }
358
+
359
+ interface TenantListOptions extends PaginationOptions {
360
+ search?: string;
361
+ filter?: TenantFilterExpression[];
362
+ /**
363
+ * Narrows the page to one level of the tree: a tenant id lists that tenant's
364
+ * direct sub-tenants, and `null` lists the roots. Omitted lists the
365
+ * environment's tenants regardless of depth — the behaviour from before the
366
+ * hierarchy existed, and still the right one for a flat picker.
367
+ *
368
+ * `search` and `filter` keep applying inside the level, so the envelope goes
369
+ * on describing what you asked for.
370
+ */
371
+ parentId?: string | null;
372
+ /**
373
+ * Inclusive floor on how deep a tenant sits, roots being 0. `1` is every
374
+ * sub-tenant in the environment, at any depth and under any parent — which
375
+ * `parentId` cannot ask for, since it names one parent. `subTenants()` is
376
+ * this option set for you. Capped at 4, the API's hard ceiling.
377
+ */
378
+ minDepth?: number;
379
+ /**
380
+ * Inclusive ceiling. Equal bounds pin one generation (`minDepth: 1,
381
+ * maxDepth: 1` is the first generation across the whole environment). A
382
+ * floor deeper than the ceiling, or a bound outside 0..4, is a 400 rather
383
+ * than an empty page.
384
+ */
385
+ maxDepth?: number;
386
+ /** Keeps one side of the status. Omitted lists both. */
387
+ status?: "active" | "disabled";
388
+ /**
389
+ * Server-side order: a field, as a bare name (ascending) or with a
390
+ * direction. The default is the name, ascending. Ties always break on the
391
+ * id, so a row cannot move across a page boundary between two calls.
392
+ *
393
+ * Against an Authyon API older than 2026-11-03 both `status` and `orderBy`
394
+ * are ignored, which reads as a page that is too wide rather than an error.
395
+ */
396
+ orderBy?: TenantOrderField | {
397
+ field: TenantOrderField;
398
+ direction?: "asc" | "desc";
399
+ };
400
+ }
401
+ /** One of a user's tenant memberships, as embedded in `EnvironmentUser.tenantMemberships`. */
402
+ interface TenantMembership {
403
+ tenantId: string;
404
+ tenantSlug: string;
405
+ tenantName: string;
406
+ tenantDisabled: boolean;
407
+ roles: string[];
408
+ }
409
+ /** Lightweight user shape returned by `introspect()`/`validate()`. */
410
+ interface User {
411
+ id: string;
412
+ email: string;
413
+ username?: string;
414
+ /** Environment-level roles from the database-validated user profile. */
415
+ roles?: string[];
416
+ permissions?: string[];
417
+ /** Security methods active on the account (authenticator, email code, passkey, SSO…). */
418
+ security?: SecurityMethods;
419
+ }
420
+ interface RoleGrant {
421
+ role: string;
422
+ expiresAt?: string | null;
423
+ }
424
+ /**
425
+ * Full user record from the EnvironmentManagement plane
426
+ * (`environment.users.get()` / `.list()`), confirmed against the live API.
427
+ * `get()` returns every field below; `list()` returns a subset (no
428
+ * `failedLoginAttempts`, `lockedOutUntil`, `roleGrants`,
429
+ * `directPermissions`, `effectivePermissions`, `refreshTokens`,
430
+ * `tenantMemberships`, `totpConfirmedAt`, `emailOtpEnabledAt`,
431
+ * `remainingRecoveryCodes`, `disableReason`, `suspension`, `deleteReason`,
432
+ * `customFields` — and `suspendedUntil` instead of `suspension`).
433
+ */
434
+ interface EnvironmentUser {
435
+ id: string;
436
+ email: string;
437
+ username?: string;
438
+ firstName?: string | null;
439
+ lastName?: string | null;
440
+ emailConfirmed: boolean;
441
+ isDisabled: boolean;
442
+ createdAt: string;
443
+ lastLoginAt?: string | null;
444
+ failedLoginAttempts?: number;
445
+ lockedOutUntil?: string | null;
446
+ roles: string[];
447
+ roleGrants?: RoleGrant[];
448
+ directPermissions?: string[];
449
+ effectivePermissions?: string[];
450
+ /** Confirmed shape unknown — empty in every response seen so far. */
451
+ refreshTokens?: unknown[];
452
+ tenantIds: string[];
453
+ tenantMemberships?: TenantMembership[];
454
+ /** Flattened role names across all tenant memberships (list() only).
455
+ * On `tenants.members.list()` it is scoped to that one tenant. */
456
+ tenantRoles?: string[];
457
+ /** Permissions granted to this member directly inside the tenant, beside
458
+ * whatever their tenant roles carry. Only `tenants.members.list()` fills
459
+ * it; absent on an API older than 2026-10-21. */
460
+ tenantPermissions?: string[];
461
+ twoFactorMethods: string[];
462
+ totpConfirmedAt?: string | null;
463
+ emailOtpEnabledAt?: string | null;
464
+ remainingRecoveryCodes?: number;
465
+ disableReason?: string | null;
466
+ suspension?: unknown | null;
467
+ suspendedUntil?: string | null;
468
+ deletedAt?: string | null;
469
+ deleteReason?: string | null;
470
+ /** JSON-encoded string. */
471
+ customFields?: string;
472
+ }
473
+ /**
474
+ * POST /auth/validate — confirmed against the live API. The wire shape is
475
+ * `{ valid, reason, profile }`, not `{ user, organization }` as the
476
+ * OpenAPI schema (which didn't document response bodies) suggested.
477
+ * `profile` is `null` for machine tokens (there's no user behind them) and
478
+ * for tokens that fail validation.
479
+ */
480
+ interface ValidateResult {
481
+ valid: boolean;
482
+ reason?: string | null;
483
+ user: User | null;
484
+ }
485
+ /**
486
+ * A role available within an environment or one of its tenants. Confirmed
487
+ * live: system roles carry no `id`/`description` (only `name` +
488
+ * `permissions`) — both are only populated for custom roles you create.
489
+ */
490
+ interface Role {
491
+ id?: string | null;
492
+ name: string;
493
+ description?: string | null;
494
+ permissions: string[];
495
+ }
496
+ interface RoleInput {
497
+ name: string;
498
+ description?: string;
499
+ permissions?: string[];
500
+ }
501
+ /**
502
+ * GET /env/roles and GET /tenant/roles group results by origin instead of
503
+ * returning a flat array — confirmed live for the environment endpoint.
504
+ */
505
+ interface RoleList {
506
+ custom: Role[];
507
+ system: Role[];
508
+ }
509
+ /** A permission entry as it appears nested under a role in `PermissionsByRole`. */
510
+ interface Permission {
511
+ value: string;
512
+ description?: string | null;
513
+ /** Confirmed live: `null` for the built-in catalog: no separate id per entry. */
514
+ catalogId?: string | null;
515
+ }
516
+ /** A role entry as returned by GET /env/permissions, with its permissions nested. */
517
+ interface RolePermissions {
518
+ roleId: string | null;
519
+ name: string;
520
+ description?: string | null;
521
+ isSystem: boolean;
522
+ permissions: Permission[];
523
+ }
524
+ /** GET /env/permissions — confirmed live: grouped by role, plus any orphaned entries. */
525
+ interface PermissionsByRole {
526
+ roles: RolePermissions[];
527
+ orphans: Permission[];
528
+ /**
529
+ * The permissions Authyon itself checks on the end-user tenant routes
530
+ * (`tenants:settings:manage`, `tenants:members:invite`,
531
+ * `tenants:members:remove` and `subtenants:tree:*`), listed whether or not
532
+ * a role names them. Absent from an API older than 2026-11-25.
533
+ */
534
+ builtIn?: BuiltInPermission[];
535
+ }
536
+ interface BuiltInPermission {
537
+ value: string;
538
+ /** What the API says the permission unlocks. */
539
+ defaultDescription: string;
540
+ /** The environment's own catalog text, when someone wrote one. */
541
+ description?: string | null;
542
+ catalogId?: string | null;
543
+ }
544
+ /** GET /permissions/reserved — confirmed live: wrapped, not a bare string array. */
545
+ interface ReservedPermissions {
546
+ namespace: string;
547
+ items: string[];
548
+ }
549
+ interface CreatePermissionInput {
550
+ value: string;
551
+ description?: string;
552
+ /** Attach the new permission to this role immediately. */
553
+ attachToRoleId?: string;
554
+ }
555
+ interface CreateTenantInput {
556
+ name: string;
557
+ slug: string;
558
+ description?: string;
559
+ customFields?: Record<string, unknown>;
560
+ publicMetadata?: Record<string, unknown>;
561
+ privateMetadata?: Record<string, unknown>;
562
+ /**
563
+ * Creates the tenant underneath an existing one in the same environment.
564
+ * Omitted creates a root tenant.
565
+ *
566
+ * The environment's `maxTenantDepth` has to allow the level — it is `1` by
567
+ * default, which means roots only and refuses this with
568
+ * `tenant.depth.not_allowed` until an operator raises it. The new node counts
569
+ * against the plan's tenant cap like any other, so nesting cannot be used to
570
+ * get around it.
571
+ */
572
+ parentTenantId?: string;
573
+ }
574
+ interface UpdateTenantInput {
575
+ name: string;
576
+ description?: string;
577
+ customFields?: Record<string, unknown>;
578
+ }
579
+ interface CreateUserInput {
580
+ email: string;
581
+ /**
582
+ * Same contract as `/auth/register`: optional only when the environment's
583
+ * username policy is `AutoFromEmail` (derived from the email). Collisions
584
+ * resolve by that policy.
585
+ */
586
+ username?: string;
587
+ password: string;
588
+ firstName?: string;
589
+ lastName?: string;
590
+ /** Values for custom user fields configured in the environment. */
591
+ customFields?: Record<string, unknown>;
592
+ emailConfirmed?: boolean;
593
+ roles?: string[];
594
+ /** Tenants to add the user to on creation. */
595
+ tenantIds?: string[];
596
+ }
597
+ /** GET /env/audit — one audit-trail entry, confirmed against the live API. */
598
+ interface AuditEvent {
599
+ id: string;
600
+ occurredAt: string;
601
+ eventType: string;
602
+ /** JSON-encoded string — `JSON.parse` it for the event-specific payload. */
603
+ payloadJson?: string;
604
+ workspaceId?: string;
605
+ environmentId?: string;
606
+ actorUserId?: string | null;
607
+ actorType?: string;
608
+ /**
609
+ * The address the event is recorded against — the vouched one when a machine
610
+ * credential named it. Where that differs from the socket peer, the peer is
611
+ * kept inside `payloadJson` as `peerIp`: which backend made the call is its
612
+ * own question, and the answer is not the caller's to choose.
613
+ */
614
+ actorIp?: string;
615
+ userAgent?: string;
616
+ tenantId?: string | null;
617
+ }
618
+ /**
619
+ * GET /env/audit/login-activity. Not confirmed with a populated example
620
+ * live (the test environment had none) — assumed to share `AuditEvent`'s
621
+ * shape, since login activity is the same underlying audit-event stream
622
+ * filtered to sign-in events.
623
+ */
624
+ type LoginActivity = AuditEvent;
625
+ /**
626
+ * Envelope every `skip`/`take`-paginated list endpoint returns, confirmed
627
+ * live for `/env/users`, `/env/audit` and `/env/audit/login-activity`.
628
+ * Endpoints without `skip`/`take` params return a bare array instead.
629
+ */
630
+ /** Tenant credential metadata. Listing never returns the secret. */
631
+ interface TenantCredentialSummary {
632
+ id: string;
633
+ clientId: string;
634
+ description: string | null;
635
+ createdAt: string;
636
+ lastUsedAt: string | null;
637
+ revokedAt: string | null;
638
+ expiresAt: string | null;
639
+ isActive: boolean;
640
+ permissions: string[];
641
+ }
642
+ /** Input for a tenant machine credential. Requires at least one explicit permission. */
643
+ interface CreateTenantCredentialInput {
644
+ description: string;
645
+ /** Number of days until the tenant credential expires. Omit for no automatic expiration. */
646
+ lifetimeDays?: number | null;
647
+ permissions: string[];
648
+ }
649
+ /** The plaintext secret is returned only when the credential is issued. */
650
+ interface TenantCredentialIssued {
651
+ credentialId: string;
652
+ clientId: string;
653
+ clientSecret: string;
654
+ createdAt: string;
655
+ expiresAt: string | null;
656
+ permissions: string[];
657
+ }
658
+ /** OAuth 2.0 client-credentials pair minted in the Authyon console. */
659
+ interface ClientCredentials {
660
+ clientId: string;
661
+ clientSecret: string;
662
+ }
663
+ /** Standard OAuth 2.0 client-credentials token response. */
664
+ interface TokenResult {
665
+ access_token: string;
666
+ token_type: string;
667
+ expires_in: number;
668
+ scope?: string;
669
+ }
670
+ /** POST /tenant/auth/validate — validates the current tenant-client bearer. */
671
+ interface TenantClientValidationResult {
672
+ valid: boolean;
673
+ reason?: string | null;
674
+ tenantId: string;
675
+ workspaceId: string;
676
+ environmentId: string;
677
+ credentialId: string;
678
+ clientId: string;
679
+ permissions: string[];
680
+ }
681
+ interface JsonWebKeySet {
682
+ keys: Record<string, unknown>[];
683
+ }
684
+ interface OpenIdConfiguration {
685
+ issuer: string;
686
+ jwks_uri: string;
687
+ authorization_endpoint?: string;
688
+ token_endpoint?: string;
689
+ [key: string]: unknown;
690
+ }
691
+ interface AuthyonServerClientOptions {
692
+ /**
693
+ * Publishable environment key (`pk_live_...` / `pk_test_...`), sent as
694
+ * `X-Authyon-Environment`. Required on **every** call — it selects the
695
+ * environment (Test / Live) that a request applies to, independently of
696
+ * whichever bearer token authenticates it.
697
+ */
698
+ envKey?: string;
699
+ /**
700
+ * Environment-level OAuth client credentials (`ec_...` / secret), minted
701
+ * in the console. Required for everything under `environment.*` and
702
+ * `permissions.*` — the SDK exchanges them for a short-lived access token
703
+ * via `POST /env/oauth/token` and refreshes it transparently.
704
+ */
705
+ clientId?: string;
706
+ clientSecret?: string;
707
+ /**
708
+ * The end user's address, forwarded on every API call as
709
+ * `X-Authyon-Client-Ip` (and `X-Forwarded-For`, for your own proxies).
710
+ *
711
+ * Worth setting: a call from your backend has no browser in it, so without
712
+ * this every audit row Authyon writes for your integration names the
713
+ * container gateway, which identifies nobody. The API believes the header
714
+ * from a machine credential and records the address beside the event, where
715
+ * the console's IP filter can find it. It only ever changes the trail — no
716
+ * IP-keyed gate reads a vouched address.
717
+ *
718
+ * Only set it from infrastructure you trust; the SDK rejects comma-separated
719
+ * or whitespace-containing values to avoid forwarded-header injection.
720
+ */
721
+ clientIp?: string;
722
+ /** API origin. Defaults to `https://api.authyon.com`. */
723
+ baseUrl?: string;
724
+ /** Allow an HTTP `baseUrl`. Intended only for explicitly trusted local development. */
725
+ allowInsecureHttp?: boolean;
726
+ /** Maximum duration of each HTTP request. Defaults to 15 seconds; set to `0` to disable. */
727
+ timeoutMs?: number;
728
+ /** Custom HTTP adapter for tracing, mocks or an alternative HTTP stack. */
729
+ httpAdapter?: HttpAdapter;
730
+ /** Safe HTTP lifecycle logging. Disabled unless this option is provided with `enabled: true`. */
731
+ httpLogger?: HttpLoggerOptions;
732
+ /** @deprecated Prefer `httpAdapter: new FetchHttpAdapter(customFetch)`. */
733
+ fetch?: typeof fetch;
734
+ }
735
+
736
+ /** @deprecated Use `Tenant`. */
737
+ type Organization = Tenant;
738
+ /** @deprecated Use `CreateTenantInput`. */
739
+ type CreateOrganizationInput = CreateTenantInput;
740
+ /** @deprecated Use `UpdateTenantInput`. */
741
+ type UpdateOrganizationInput = UpdateTenantInput;
742
+
743
+ /** A token of the requested authentication plane, or a provider called for each request. */
744
+ type AccessTokenSource = string | (() => string | Promise<string>);
745
+ interface CredentialListOptions extends PaginationOptions {
746
+ search?: string;
747
+ /**
748
+ * Keep only credentials that grant EVERY one of these permissions. Matching is
749
+ * wildcard-aware on the server: a credential holding `authyon:*:*` passes any
750
+ * filter. Up to 20 entries; requires an API of 2026-11-08 or newer, and an
751
+ * older one ignores it.
752
+ */
753
+ permissions?: readonly string[];
754
+ }
755
+ /** scopes is an alias for permissions. Always supply an explicit, nonempty set. */
756
+ type CredentialPermissionsInput = {
757
+ permissions: readonly string[];
758
+ scopes?: never;
759
+ } | {
760
+ scopes: readonly string[];
761
+ permissions?: never;
762
+ };
763
+ type CreateCredentialInput = CredentialPermissionsInput & {
764
+ description?: string;
765
+ lifetimeDays?: number | null;
766
+ };
767
+ interface CredentialCreator {
768
+ id: string | null;
769
+ type: string;
770
+ displayName: string | null;
771
+ }
772
+ interface CredentialDetail extends TenantCredentialSummary {
773
+ createdBy: CredentialCreator | null;
774
+ updatedAt: string | null;
775
+ secretRotatedAt: string | null;
776
+ expiresAt: string | null;
777
+ ageSeconds: number;
778
+ /** Null while active; elapsed lifetime at revocation otherwise. */
779
+ lifetimeSeconds: number | null;
780
+ accessTokenLifetimeSeconds: number;
781
+ }
782
+ interface InviteTenantMemberInput {
783
+ email: string;
784
+ roles?: string[];
785
+ }
786
+ interface TenantMember {
787
+ userId: string;
788
+ email: string;
789
+ username: string;
790
+ /** Null when the person never gave one. Absent from an API older than 2026-11-25. */
791
+ firstName?: string | null;
792
+ lastName?: string | null;
793
+ roles: string[];
794
+ createdAt: string;
795
+ lastLoginAt: string | null;
796
+ /**
797
+ * Account status: `"active"`, `"suspended"` (a temporary hold is in force) or
798
+ * `"disabled"`. Absent from an API older than 2026-11-26.
799
+ */
800
+ status?: "active" | "suspended" | "disabled";
801
+ /** Whether the member confirmed their e-mail. Absent from an API older than 2026-11-26. */
802
+ emailConfirmed?: boolean;
803
+ }
804
+ type TenantMemberPage = Paged<TenantMember>;
805
+ /**
806
+ * Invite an address to a tenant. The address may not have an account in the
807
+ * environment yet — accepting creates it. `sendEmail` defaults to `true`;
808
+ * `false` only returns the link, for delivery through your own channel.
809
+ */
810
+ interface TenantInviteInput {
811
+ email: string;
812
+ roles?: string[];
813
+ sendEmail?: boolean;
814
+ /**
815
+ * Where to send the invitee after they accept. Must be registered exactly in
816
+ * the environment's redirect URIs (the same list SSO and magic link use);
817
+ * otherwise the API rejects the invite. Comes back on `preview` and `accept`.
818
+ */
819
+ redirectUri?: string;
820
+ }
821
+ /** POST /env/password-resets — issue a reset for an account of the environment. */
822
+ interface IssuePasswordResetInput {
823
+ email: string;
824
+ /**
825
+ * Where to send the person after they change the password. Must be
826
+ * registered exactly in the environment's redirect URIs; otherwise the API
827
+ * rejects with `user.password_reset.redirect_uri.not_allowed`.
828
+ */
829
+ redirectUri?: string;
830
+ /**
831
+ * `true` has Authyon mail the link as well. Defaults to `false`: the point
832
+ * of this call is to deliver the token through your own e-mail.
833
+ */
834
+ sendEmail?: boolean;
835
+ }
836
+ /** Returned when a reset is issued. `token` is only ever readable here — the
837
+ * API keeps its hash. Whoever holds it can set the password: send it only to
838
+ * the account's own address and never log it. */
839
+ interface PasswordResetIssued {
840
+ userId: string;
841
+ email: string;
842
+ token: string;
843
+ /** The link Authyon's own e-mail would carry: the environment's reset page
844
+ * when it has one, the hosted page otherwise. */
845
+ resetUrl: string;
846
+ expiresAt: string;
847
+ emailSent: boolean;
848
+ redirectUri: string | null;
849
+ }
850
+ /** What a live reset token is for. */
851
+ interface PasswordResetPreview {
852
+ email: string;
853
+ expiresAt: string;
854
+ redirectUri: string | null;
855
+ }
856
+ /** The password is changed. Following `redirectUri` is up to you. */
857
+ interface PasswordResetCompleted {
858
+ redirectUri: string | null;
859
+ }
860
+ /** Returned when an invite is created or re-issued. `acceptUrl` is only ever
861
+ * readable here — the API keeps a hash of the token, not the token. */
862
+ interface TenantInviteIssued {
863
+ id: string;
864
+ tenantId: string;
865
+ email: string;
866
+ roles: string[];
867
+ acceptUrl: string;
868
+ expiresAt: string;
869
+ emailSent: boolean;
870
+ redirectUri: string | null;
871
+ }
872
+ type TenantInviteStatus = "pending" | "accepted" | "revoked" | "expired";
873
+ /**
874
+ * Options for an invite listing. The API always orders newest first.
875
+ * `status` keeps only invites in any of the given states; omitted, every state.
876
+ */
877
+ interface TenantInviteListOptions extends PaginationOptions {
878
+ /** Case-insensitive substring of the invited address. */
879
+ search?: string;
880
+ status?: TenantInviteStatus[];
881
+ }
882
+ interface TenantInvite {
883
+ id: string;
884
+ tenantId: string;
885
+ email: string;
886
+ roles: string[];
887
+ status: TenantInviteStatus;
888
+ createdAt: string;
889
+ expiresAt: string;
890
+ emailSentAt: string | null;
891
+ acceptedAt: string | null;
892
+ acceptedByUserId: string | null;
893
+ revokedAt: string | null;
894
+ invitedByUserId: string | null;
895
+ redirectUri: string | null;
896
+ }
897
+ /** What an accept page shows before the invitee commits. */
898
+ interface TenantInvitePreview {
899
+ tenantId: string;
900
+ tenantName: string;
901
+ email: string;
902
+ roles: string[];
903
+ expiresAt: string;
904
+ /** True: accepting only needs the token. False: send a password (and a username when `usernameRequired`). */
905
+ accountExists: boolean;
906
+ usernameRequired: boolean;
907
+ /** Where the issuer asked to send the invitee after accepting, or `null`. */
908
+ redirectUri: string | null;
909
+ }
910
+ /**
911
+ * Redeem an invite. For an address that already has an account only `token`
912
+ * and the metadata are used; the rest is for creating the account.
913
+ */
914
+ interface AcceptTenantInviteInput {
915
+ token: string;
916
+ username?: string;
917
+ password?: string;
918
+ firstName?: string;
919
+ lastName?: string;
920
+ /**
921
+ * @deprecated Use `publicMetadata` / `privateMetadata`. Still sent and
922
+ * validated against the environment's user field schema for now.
923
+ */
924
+ customFields?: Record<string, unknown>;
925
+ /**
926
+ * Replaces the user's public metadata (readable by the user). Requires the
927
+ * client credentials (`clientId`/`clientSecret`) with `authyon:users:write`:
928
+ * when this or `privateMetadata` is set, `accept` calls
929
+ * `POST /env/tenant-invites/accept` instead of the public route.
930
+ */
931
+ publicMetadata?: Record<string, unknown>;
932
+ /** Replaces the user's private metadata (server-only). Same requirement as `publicMetadata`. */
933
+ privateMetadata?: Record<string, unknown>;
934
+ }
935
+ interface TenantInviteAccepted {
936
+ tenantId: string;
937
+ tenantName: string;
938
+ userId: string;
939
+ accountCreated: boolean;
940
+ /** Where the issuer asked to send the invitee, or `null`. Redirecting is up to the accept page. */
941
+ redirectUri: string | null;
942
+ }
943
+
944
+ type QueryParams = object;
945
+
946
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
947
+ interface JsonRequestOptions {
948
+ method?: HttpMethod;
949
+ body?: unknown;
950
+ query?: QueryParams;
951
+ headers?: Record<string, string>;
952
+ }
953
+
954
+ type ManagementRequest = <T>(path: string, options?: JsonRequestOptions) => Promise<T>;
955
+
956
+ /** Customer-side operations on an approval (`/auth/authorizations`). */
957
+ interface SubjectApprovals {
958
+ /** GET /auth/authorizations/{id} — the pending payload, to show before asking for the code. */
959
+ get(id: string): Promise<Approval>;
960
+ /** POST /auth/authorizations/{id}/webauthn/options — passkey options for approving it. */
961
+ webauthnOptions(id: string): Promise<ApprovalWebAuthnOptions>;
962
+ /**
963
+ * POST /auth/authorizations/{id}/confirm — approves it.
964
+ *
965
+ * Pass the authenticator code or passkey assertion to verify the second
966
+ * factor inline (recommended). Without `input`, the session itself must
967
+ * have used a passkey or authenticator code within the last 5 minutes,
968
+ * otherwise the API answers `step_up_required`.
969
+ */
970
+ confirm(id: string, input?: ConfirmApprovalInput): Promise<Approval>;
971
+ /** POST /auth/authorizations/{id}/reject — the customer declines it. */
972
+ reject(id: string): Promise<Approval>;
973
+ }
974
+ /** The `security` namespace an end-user client exposes. */
975
+ interface SubjectSecurity {
976
+ /**
977
+ * GET /auth/me — which security methods the signed-in user has active
978
+ * (password, authenticator, email code, passkeys, recovery codes, SSO).
979
+ */
980
+ methods(): Promise<SecurityMethods>;
981
+ /** Approve or reject what your backend asked the customer to confirm. */
982
+ readonly approvals: SubjectApprovals;
983
+ }
984
+
985
+ /** End-user operations require a user token and the environment publishable key. */
986
+ declare class UserScopedClient {
987
+ #private;
988
+ /** @hidden */
989
+ constructor(request: ManagementRequest, token: AccessTokenSource);
990
+ /**
991
+ * The customer's side of `security.approvals`, for backends (BFF) that hold
992
+ * the customer's access token: `get`, `webauthnOptions`, `confirm`, `reject`.
993
+ */
994
+ readonly security: SubjectSecurity;
995
+ readonly tenants: {
996
+ /**
997
+ * GET /auth/tenants/{tenantId} — one tenant, acting as the user: their own,
998
+ * or one below it with `subtenants:tree:read` on an ancestor.
999
+ */
1000
+ get: (tenantId: string) => Promise<MyTenant>;
1001
+ /**
1002
+ * One tenant by id **or** slug: a UUID goes to `GET /auth/tenants/{id}`,
1003
+ * anything else to `GET /auth/tenants/by-slug/{slug}`. Same rule and answer
1004
+ * as `get`; by slug every refusal is `tenant.not_found`. An empty value
1005
+ * raises `RangeError` before any request. The slug route needs the Authyon
1006
+ * API of 2026-11-26 or newer.
1007
+ */
1008
+ find: (idOrSlug: string) => Promise<MyTenant>;
1009
+ /**
1010
+ * The direct, active sub-tenants of a tenant, acting as the user. One level
1011
+ * per call: each row's `childCount` says where the next call is worth
1012
+ * making. Needs `subtenants:tree:read` on the tenant or on one above it —
1013
+ * even on the user's own tenant, since listing the children is reading
1014
+ * below it.
1015
+ *
1016
+ * Paged like every other `skip`/`take` listing, with `search`, `filter`
1017
+ * (public scope only — build them with `tenantFilter`) and `orderBy`; see
1018
+ * `SubTenantListOptions`. A bad option raises `RangeError` before any
1019
+ * request. Requires the Authyon API of 2026-11-26 or newer.
1020
+ */
1021
+ subTenants: {
1022
+ /** GET /auth/tenants/{tenantId}/subtenants. */
1023
+ list: (tenantId: string, options?: SubTenantListOptions) => Promise<Paged<SubTenant>>;
1024
+ /**
1025
+ * GET /auth/tenants/subtenants — the same, for the tenant the user's token
1026
+ * is scoped to (its `tenant_id`). Same permission rule. Answers
1027
+ * `tenant.no_active_tenant` when the session never switched into one.
1028
+ */
1029
+ listCurrent: (options?: SubTenantListOptions) => Promise<Paged<SubTenant>>;
1030
+ };
1031
+ members: {
1032
+ /** Newest first; `search` matches email, username or name (at most 100 characters). */
1033
+ list: (tenantId: string, options?: MemberListOptions) => Promise<TenantMemberPage>;
1034
+ /** Adds an existing environment user by email; does not send an invitation email. */
1035
+ invite: (tenantId: string, input: InviteTenantMemberInput) => Promise<TenantMember>;
1036
+ remove: (tenantId: string, userId: string) => Promise<void>;
1037
+ };
1038
+ /**
1039
+ * Invites by e-mail or by link, acting as the user. Requires the
1040
+ * `tenants:members:invite` permission on the tenant.
1041
+ */
1042
+ invites: {
1043
+ list: (tenantId: string) => Promise<TenantInvite[]>;
1044
+ /** Always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
1045
+ create: (tenantId: string, input: TenantInviteInput) => Promise<TenantInviteIssued>;
1046
+ /** New link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1047
+ resend: (tenantId: string, inviteId: string, input?: {
1048
+ sendEmail?: boolean;
1049
+ }) => Promise<TenantInviteIssued>;
1050
+ revoke: (tenantId: string, inviteId: string) => Promise<void>;
1051
+ };
1052
+ };
1053
+ }
1054
+
1055
+ /** `security.approvals.create()` — something awaiting the customer's approval. */
1056
+ interface CreateApprovalInput {
1057
+ /** Environment user who must approve. */
1058
+ subjectId: string;
1059
+ /** Any JSON object (up to 16 KiB) describing what is being approved. Default `{}`. */
1060
+ payload?: ApprovalPayload;
1061
+ /** Restrict approval to a session in this tenant. */
1062
+ tenantId?: string;
1063
+ /** Lifetime in seconds, clamped to 60–600. Default 300. */
1064
+ expiresInSeconds?: number;
1065
+ /**
1066
+ * Optional. Sent as the `Idempotency-Key` header (max 128 chars): retrying
1067
+ * with the same key and payload returns the same approval; the same key
1068
+ * with a different payload fails with `idempotency_conflict`.
1069
+ */
1070
+ idempotencyKey?: string;
1071
+ }
1072
+ /** `security.approvals.consume()` — single-use redemption result. */
1073
+ interface ConsumedApproval {
1074
+ id: string;
1075
+ status: "consumed";
1076
+ consumedAt: string;
1077
+ /** The approved payload — execute exactly this. */
1078
+ payload: ApprovalPayload;
1079
+ payloadHash: string;
1080
+ assurance: ApprovalAssurance | null;
1081
+ }
1082
+ /** `security.otp.check()` result. */
1083
+ type OtpCheckResult = {
1084
+ valid: true;
1085
+ userId: string;
1086
+ /** Always `"otp"` (authenticator app). */
1087
+ method: string;
1088
+ verifiedAt: string;
1089
+ } | {
1090
+ valid: false;
1091
+ /**
1092
+ * Wrong codes left before the first consequence: the sign-out (3 in a
1093
+ * row) or the 15-minute lock (5). `0` when the user was just signed out.
1094
+ */
1095
+ attemptsRemaining: number;
1096
+ /**
1097
+ * True when this was the 3rd wrong code in a row (counted across login
1098
+ * 2FA, `security.otp.check` and `security.approvals.confirm`): every
1099
+ * session of the user was ended and they must sign in again.
1100
+ */
1101
+ sessionsRevoked?: boolean;
1102
+ };
1103
+
1104
+ interface ClientRequestContext {
1105
+ /** Real end-user IP, resolved only from infrastructure trusted by the application. */
1106
+ clientIp?: string;
1107
+ }
1108
+ /**
1109
+ * The header Authyon reads the real caller address from. `X-Forwarded-For` is
1110
+ * not it: the API rewrites the socket peer from the edge proxy's chain and then
1111
+ * resolves the client address from this header alone, so an address sent only
1112
+ * in XFF is dropped before anything reads it.
1113
+ */
1114
+ declare const CLIENT_IP_HEADER = "X-Authyon-Client-Ip";
1115
+ /** Rejects header injection and values that are not a single IPv4 or IPv6 address. */
1116
+ declare function normalizeClientIp(value: string): string;
1117
+
1118
+ type SafeJwtAlgorithm = "RS256" | "PS256" | "ES256" | "EdDSA";
1119
+ /**
1120
+ * The active tenant, as the `tenant` claim carries it. Present only on a
1121
+ * session scoped to one — a token minted before any tenant switch has no
1122
+ * tenant and no claim.
1123
+ *
1124
+ * Snake_case because these are wire names, not SDK ones: the claim is signed,
1125
+ * and renaming its fields on the way in would hide what was actually asserted.
1126
+ */
1127
+ interface AuthyonTenantClaim {
1128
+ id: string;
1129
+ slug: string;
1130
+ name: string;
1131
+ /** The tenant above this one, or `null` at a root. */
1132
+ parent_id?: string | null;
1133
+ /**
1134
+ * The materialised chain from the root down to this tenant. Signed, so a
1135
+ * consumer can answer "is that tenant under mine?" with a prefix comparison
1136
+ * and no round trip — which is the whole reason it is in the token.
1137
+ */
1138
+ path?: string;
1139
+ /** Distance from the root: `0` at a root tenant. */
1140
+ depth?: number;
1141
+ /**
1142
+ * Version of `path`. A tenant that gets moved bumps it, which is what makes
1143
+ * the signed path safe to trust: a token minted before the move no longer
1144
+ * matches and the API refuses it with `tenant.path_stale`, instead of
1145
+ * letting a stale prefix keep answering yes.
1146
+ */
1147
+ pv?: number;
1148
+ roles?: string[];
1149
+ /** Effective permissions AT this tenant. */
1150
+ permissions?: string[];
1151
+ /**
1152
+ * Set only when the session descended into this tenant from an ancestor,
1153
+ * naming the node the permissions came from — the user holds no membership
1154
+ * here. Treat it as borrowed authority if that matters to you (a banner, a
1155
+ * tighter trail, a refusal); ignore it and you have a session scoped to a
1156
+ * tenant, which is what it is. Absent on any other session.
1157
+ */
1158
+ via?: string | null;
1159
+ }
1160
+ interface AuthyonJwtClaims extends JWTPayload {
1161
+ sub: string;
1162
+ iss: string;
1163
+ aud: string | string[];
1164
+ exp: number;
1165
+ iat: number;
1166
+ email?: string;
1167
+ username?: string;
1168
+ roles?: string[];
1169
+ permissions?: string[];
1170
+ scope?: string;
1171
+ /** The active tenant and the grants held inside it. Absent until a switch. */
1172
+ tenant?: AuthyonTenantClaim;
1173
+ }
1174
+ interface VerifiedAccessToken {
1175
+ claims: AuthyonJwtClaims;
1176
+ protectedHeader: JWSHeaderParameters;
1177
+ }
1178
+ interface JwksTokenVerifierOptions {
1179
+ /** Exact trusted issuer from Authyon OpenID discovery. */
1180
+ issuer: string;
1181
+ /** Audience assigned to the API consuming this token. */
1182
+ audience: string | string[];
1183
+ /** Trusted HTTPS JWKS endpoint. Never derive this value from the token header. */
1184
+ jwksUri?: string;
1185
+ /** Static trusted keys for pinned or offline verification. */
1186
+ jwks?: JSONWebKeySet;
1187
+ algorithms?: readonly SafeJwtAlgorithm[];
1188
+ acceptedTokenTypes?: readonly string[];
1189
+ clockToleranceSeconds?: number;
1190
+ maxTokenAgeSeconds?: number;
1191
+ jwksTimeoutMs?: number;
1192
+ jwksCacheMs?: number;
1193
+ jwksCooldownMs?: number;
1194
+ }
1195
+ interface AuthyonJwksDiscoveryOptions extends Omit<JwksTokenVerifierOptions, "issuer" | "jwksUri" | "jwks"> {
1196
+ /** Optional pin; discovery fails if Authyon advertises a different issuer. */
1197
+ issuer?: string;
1198
+ /** Override the client environment key used by the discovery endpoint. */
1199
+ publishableKey?: string;
1200
+ }
1201
+ type TokenVerificationErrorCode = "token.invalid" | "token.expired" | "token.not_active" | "token.invalid_claims" | "token.invalid_signature" | "token.key_unavailable";
1202
+ declare class TokenVerificationError extends Error {
1203
+ readonly code: TokenVerificationErrorCode;
1204
+ constructor(code: TokenVerificationErrorCode, options?: {
1205
+ cause?: unknown;
1206
+ });
1207
+ }
1208
+ /** Secure, cached JWT signature and claims verifier backed by a trusted remote JWKS. */
1209
+ declare class JwksTokenVerifier {
1210
+ private readonly options;
1211
+ private readonly verifyKey;
1212
+ private readonly algorithms;
1213
+ private readonly acceptedTokenTypes;
1214
+ constructor(options: JwksTokenVerifierOptions);
1215
+ verifyAccessToken(token: string): Promise<VerifiedAccessToken>;
1216
+ }
1217
+
1218
+ /**
1219
+ * Server-side Authyon client: environment/tenant administration (OAuth
1220
+ * client-credentials) plus access-token verification (publishable key).
1221
+ * Never import this in browser code — client secrets must stay on your
1222
+ * server.
1223
+ */
1224
+ declare class AuthyonServerClient {
1225
+ #private;
1226
+ private readonly envKey?;
1227
+ private readonly clientId?;
1228
+ private readonly clientIp?;
1229
+ private readonly transport;
1230
+ private readonly http;
1231
+ private readonly environmentTokenProvider;
1232
+ constructor(options?: AuthyonServerClientOptions);
1233
+ private request;
1234
+ /** Mints (and caches) an environment access token from `clientId`/`clientSecret`. */
1235
+ private getEnvironmentAccessToken;
1236
+ readonly discovery: {
1237
+ /** GET /.well-known/jwks.json — the environment's public signing keys. */
1238
+ jwks: (publishableKey?: string) => Promise<JsonWebKeySet>;
1239
+ /** GET /.well-known/openid-configuration — OIDC discovery document. */
1240
+ openidConfiguration: (publishableKey?: string) => Promise<OpenIdConfiguration>;
1241
+ };
1242
+ /** Discovers Authyon's trusted issuer/JWKS and creates a cached local access-token verifier. */
1243
+ createJwksTokenVerifier(options: AuthyonJwksDiscoveryOptions): Promise<JwksTokenVerifier>;
1244
+ /** POST /auth/introspect — lightweight token introspection (RFC 7662). */
1245
+ introspect(token: string, context?: ClientRequestContext): Promise<IntrospectResult>;
1246
+ /** POST /auth/validate — recommended: cross-checks DB state, catches revocation immediately. */
1247
+ validate(token: string, context?: ClientRequestContext): Promise<ValidateResult>;
1248
+ readonly environmentAuth: {
1249
+ /** POST /env/oauth/token — exchanges environment client credentials for an access token. */
1250
+ token: (credentials: ClientCredentials) => Promise<TokenResult>;
1251
+ };
1252
+ readonly tenantAuth: {
1253
+ /** POST /tenant/oauth/token — exchanges a tenant's client credentials for a scoped access token. */
1254
+ token: (credentials: ClientCredentials) => Promise<TokenResult>;
1255
+ /** POST /tenant/auth/validate — validates an already-minted tenant-client bearer token. */
1256
+ validate: (accessToken: string, context?: ClientRequestContext) => Promise<TenantClientValidationResult>;
1257
+ };
1258
+ /**
1259
+ * Scopes a client to a single tenant's OAuth credentials — mints and
1260
+ * caches its access token independently of the environment plane. Use
1261
+ * this for the `TenantManagement` endpoints (`/tenant/...`), which act on
1262
+ * "the token's tenant" rather than one you pass by id.
1263
+ */
1264
+ tenant(credentials: ClientCredentials): TenantScopedClient;
1265
+ /** Uses an end-user token; the configured environment key selects the environment. */
1266
+ user(token: AccessTokenSource): UserScopedClient;
1267
+ readonly environment: {
1268
+ users: {
1269
+ /** GET /env/users — paginated list of users in the environment. */
1270
+ list: (params?: {
1271
+ search?: string;
1272
+ } & PaginationOptions) => Promise<Paged<EnvironmentUser>>;
1273
+ /** POST /env/users — create a user in the environment; returns only the new id. */
1274
+ create: (input: CreateUserInput) => Promise<{
1275
+ id: string;
1276
+ }>;
1277
+ /** GET /env/users/{userId} — fetch an environment user by id. */
1278
+ get: (userId: string) => Promise<EnvironmentUser>;
1279
+ /** POST /env/users/{userId}/roles — grant a role to an environment user. */
1280
+ assignRole: (userId: string, role: string) => Promise<void>;
1281
+ /** DELETE /env/users/{userId}/roles/{role} — revoke a role from an environment user. */
1282
+ removeRole: (userId: string, role: string) => Promise<void>;
1283
+ /** POST /env/users/{userId}/permissions — grant a direct permission to an environment user. */
1284
+ grantPermission: (userId: string, permission: string) => Promise<void>;
1285
+ /** DELETE /env/users/{userId}/permissions/{permission} — revoke a direct permission. */
1286
+ revokePermission: (userId: string, permission: string) => Promise<void>;
1287
+ /** POST /env/users/{userId}/unlock — clears an environment user's lockout. */
1288
+ unlock: (userId: string, reason?: string) => Promise<void>;
1289
+ /** POST /env/users/{userId}/password — sets a new password for the user. */
1290
+ setPassword: (userId: string, newPassword: string, reason?: string) => Promise<void>;
1291
+ /**
1292
+ * POST /env/password-resets — issues a password-reset token for the
1293
+ * account with this address and returns it, so your application can
1294
+ * deliver it in its own e-mail instead of Authyon's. Needs the
1295
+ * `authyon:users:password` scope. Unlike the public forgot-password
1296
+ * request, an unknown address rejects with `user.not_found` (404).
1297
+ * A previous live token for the same account stops working.
1298
+ */
1299
+ issuePasswordReset: (input: IssuePasswordResetInput) => Promise<PasswordResetIssued>;
1300
+ /**
1301
+ * POST /auth/password-reset/validate — for a backend hosting the reset
1302
+ * page: checks a token without spending it. Public, needs only the
1303
+ * `envKey`. Rejects with `user.password_reset.invalid` (401) when the
1304
+ * token is unknown, used or expired.
1305
+ */
1306
+ validatePasswordReset: (token: string) => Promise<PasswordResetPreview>;
1307
+ /**
1308
+ * POST /auth/password-reset/confirm — redeems the token and sets the new
1309
+ * password (every session of the account is signed out). Public, needs
1310
+ * only the `envKey`. Resolves with the `redirectUri` the reset was issued
1311
+ * with, or `null`.
1312
+ */
1313
+ confirmPasswordReset: (token: string, newPassword: string) => Promise<PasswordResetCompleted>;
1314
+ /** POST /env/users/{userId}/sessions/revoke-all — revokes every session the user has. */
1315
+ revokeSessions: (userId: string, reason?: string) => Promise<void>;
1316
+ /** DELETE /env/users/{userId}/sessions/{sessionId} — revokes a single session. */
1317
+ revokeSession: (userId: string, sessionId: string, reason?: string) => Promise<void>;
1318
+ /** POST /env/users/{userId}/disable — bans the user indefinitely; revokes live sessions. */
1319
+ disable: (userId: string, reason?: string) => Promise<void>;
1320
+ /** POST /env/users/{userId}/enable — lifts a ban. */
1321
+ enable: (userId: string, reason?: string) => Promise<void>;
1322
+ /** POST /env/users/{userId}/suspend — blocks the user temporarily; clears itself after `durationMinutes`. */
1323
+ suspend: (userId: string, durationMinutes: number, reason?: string) => Promise<void>;
1324
+ /** POST /env/users/{userId}/unsuspend — lifts a suspension early. */
1325
+ unsuspend: (userId: string, reason?: string) => Promise<void>;
1326
+ /** POST /env/users/{userId}/tenants — adds an environment user to a tenant. */
1327
+ assignTenant: (userId: string, tenantId: string, roles?: string[]) => Promise<void>;
1328
+ /** DELETE /env/users/{userId}/tenants/{tenantId} — removes an environment user from a tenant. */
1329
+ removeTenant: (userId: string, tenantId: string) => Promise<void>;
1330
+ };
1331
+ tenants: {
1332
+ credentials: {
1333
+ /** GET /env/tenants/{tenantId}/credentials. Returns metadata only, including revoked credentials. */
1334
+ list: (tenantId: string) => Promise<TenantCredentialSummary[]>;
1335
+ /** Paginated searchable listing. Prefer this over loading every credential. */
1336
+ listPage: (tenantId: string, options?: CredentialListOptions) => Promise<Paged<TenantCredentialSummary>>;
1337
+ get: (tenantId: string, credentialId: string) => Promise<CredentialDetail>;
1338
+ /** Explicit scopes/permissions; only issuance returns the client secret. */
1339
+ create: (tenantId: string, input: CreateTenantCredentialInput | CreateCredentialInput) => Promise<TenantCredentialIssued>;
1340
+ /** Returns a new secret once while keeping the same client id. */
1341
+ rotate: (tenantId: string, credentialId: string) => Promise<TenantCredentialIssued>;
1342
+ updatePermissions: (tenantId: string, credentialId: string, input: CredentialPermissionsInput) => Promise<void>;
1343
+ updateScopes: (tenantId: string, credentialId: string, scopes: readonly string[]) => Promise<void>;
1344
+ revoke: (tenantId: string, credentialId: string) => Promise<void>;
1345
+ };
1346
+ /**
1347
+ * GET /env/tenants — one page of the environment's tenants.
1348
+ *
1349
+ * `search` matches, case-insensitively and anywhere in the value, the
1350
+ * name, the slug, the description and the raw text of both metadata
1351
+ * documents — so a tenant filed with `{"cnpj":"00.000.000/0001-00"}`
1352
+ * is found by the number, and `cnpj` alone finds every tenant carrying
1353
+ * that key. `take` defaults to 25 and is capped at 100.
1354
+ *
1355
+ * `filter` is the structured half, and the one to reach for when more
1356
+ * than one condition has to hold: each entry is a condition on a JSON
1357
+ * document, they are ANDed with each other and with `search`, and they
1358
+ * run inside the statement — so the envelope keeps describing the
1359
+ * filtered set and you can page through it. Build them with
1360
+ * `tenantFilter`:
1361
+ *
1362
+ * ```ts
1363
+ * const page = await authyon.environment.tenants.list({
1364
+ * filter: [
1365
+ * tenantFilter.in("public.kind", ["reseller", "partner"]),
1366
+ * tenantFilter.in("custom.cnpj", [a, b]),
1367
+ * ],
1368
+ * take: 100,
1369
+ * });
1370
+ * ```
1371
+ *
1372
+ * `parentId` narrows the page to one level of the tree — `children()`
1373
+ * and `roots()` below are the same call with that one option set.
1374
+ *
1375
+ * Against an Authyon API older than 2026-10-21 this route ignored
1376
+ * skip/take/search and answered with a bare array; one older than
1377
+ * 2026-10-22 ignores `filter` and one older than 2026-10-31 ignores
1378
+ * `parentId`, which read as a page that is too wide rather than an error.
1379
+ */
1380
+ list: (params?: TenantListOptions) => Promise<Paged<Tenant>>;
1381
+ /**
1382
+ * One page of a tenant's direct sub-tenants — `list()` with `parentId`.
1383
+ *
1384
+ * Only one level: a node's own children carry `childCount`, so a tree
1385
+ * view asks again where that is above zero instead of reading the whole
1386
+ * subtree to draw the first level of it.
1387
+ */
1388
+ children: (parentTenantId: string, params?: Omit<TenantListOptions, "parentId">) => Promise<Paged<Tenant>>;
1389
+ /**
1390
+ * One page of the environment's root tenants — `list()` with no parent.
1391
+ *
1392
+ * This is the first level of the tree, and the difference from `list()`
1393
+ * is worth keeping straight: `list()` returns every tenant at every
1394
+ * depth, which is what a flat picker wants and what a tree view must not
1395
+ * start from.
1396
+ */
1397
+ roots: (params?: Omit<TenantListOptions, "parentId">) => Promise<Paged<Tenant>>;
1398
+ /**
1399
+ * Every sub-tenant in the environment, at any depth and under any
1400
+ * parent — `list()` with `minDepth: 1`. This is the one page
1401
+ * `children()` cannot produce, since it names a single parent, and the
1402
+ * one a flat "all sub-companies" screen wants: the envelope describes
1403
+ * the sub-tenants alone, so the pager stops where they do, and nobody
1404
+ * has to read the whole environment and drop the roots.
1405
+ *
1406
+ * Against an Authyon API older than 2026-10-31 the floor is ignored and
1407
+ * the roots come back too.
1408
+ */
1409
+ subTenants: (params?: Omit<TenantListOptions, "parentId" | "minDepth">) => Promise<Paged<Tenant>>;
1410
+ /**
1411
+ * POST /env/tenants — create a tenant in the environment.
1412
+ *
1413
+ * `parentTenantId` nests it under an existing tenant. The environment's
1414
+ * `maxTenantDepth` has to allow the level — it ships as `1`, roots only,
1415
+ * so this answers `tenant.depth.not_allowed` until an operator raises it
1416
+ * in the console.
1417
+ */
1418
+ create: (input: CreateTenantInput) => Promise<Tenant>;
1419
+ /**
1420
+ * GET /env/tenants/{tenantId} — fetch a tenant by id.
1421
+ *
1422
+ * Returns `ancestors` as well, the chain above it root first, so a
1423
+ * breadcrumb costs this one call rather than one per level.
1424
+ */
1425
+ get: (tenantId: string) => Promise<Tenant>;
1426
+ /** PUT /env/tenants/{tenantId} — update a tenant. */
1427
+ update: (tenantId: string, input: UpdateTenantInput) => Promise<Tenant>;
1428
+ /** PUT /env/tenants/{tenantId}/metadata - replace public and private metadata. */
1429
+ updateMetadata: (tenantId: string, input: Pick<CreateTenantInput, "publicMetadata" | "privateMetadata">) => Promise<void>;
1430
+ /**
1431
+ * POST /env/tenants/{tenantId}/disable — disable without removing tenant
1432
+ * data.
1433
+ *
1434
+ * Disables the branch below it too. A sub-tenant left live under a
1435
+ * disabled parent would go on authenticating its users, which is the one
1436
+ * thing switching a tenant off is there to stop — so check `childCount`
1437
+ * before calling this on a node with children.
1438
+ */
1439
+ disable: (tenantId: string) => Promise<void>;
1440
+ /**
1441
+ * DELETE /env/tenants/{tenantId} — logically delete (disable) a tenant,
1442
+ * and the branch below it. Same handler as `disable()`.
1443
+ */
1444
+ delete: (tenantId: string) => Promise<void>;
1445
+ /**
1446
+ * POST /env/tenants/{tenantId}/enable — the way back from `disable()`.
1447
+ *
1448
+ * Only this tenant comes back: a sub-tenant that went down with the
1449
+ * cascade stays off until enabled itself, and a tenant under a disabled
1450
+ * parent cannot come back before the parent does
1451
+ * (`tenant.ancestor_disabled`).
1452
+ *
1453
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1454
+ */
1455
+ enable: (tenantId: string) => Promise<void>;
1456
+ /**
1457
+ * POST /env/tenants/{tenantId}/move — hang the tenant, with everything
1458
+ * below it, under another parent, or at the root with `null`.
1459
+ *
1460
+ * Refused into itself or one of its own descendants
1461
+ * (`tenant.parent.cycle`), into a switched-off branch, or where the
1462
+ * branch's deepest node would pass the environment's level cap
1463
+ * (`tenant.depth.not_allowed`). Every token minted at the old position
1464
+ * is retired (`tenant.path_stale`), so sessions inside the branch sign
1465
+ * in again.
1466
+ *
1467
+ * Against an Authyon API older than 2026-11-03 this route does not exist.
1468
+ */
1469
+ move: (tenantId: string, parentTenantId: string | null) => Promise<void>;
1470
+ members: {
1471
+ /**
1472
+ * GET /env/tenants/{tenantId}/members — a tenant's members as full
1473
+ * user records, with the same shape `environment.users.list()` items
1474
+ * have, plus `tenantRoles` and `tenantPermissions` scoped to this
1475
+ * tenant.
1476
+ *
1477
+ * Paged like every other list: the `Paged<T>` envelope carries
1478
+ * `total` and `hasNext`, `take` defaults to 50 and is capped at 100,
1479
+ * newest member first. `search` matches email, username or name (at
1480
+ * most 100 characters, checked before any request).
1481
+ * Up to the Authyon API of 2026-10-21 this one route answered with a
1482
+ * bare array, so a caller had to page until a short page came back;
1483
+ * against such an API `data` is undefined and the array is the body
1484
+ * itself.
1485
+ */
1486
+ list: (tenantId: string, params?: MemberListOptions) => Promise<Paged<EnvironmentUser>>;
1487
+ /** POST /env/tenants/{tenantId}/members — add a member to a tenant. */
1488
+ add: (tenantId: string, userId: string, roles?: string[]) => Promise<void>;
1489
+ /** DELETE /env/tenants/{tenantId}/members/{userId} — remove a member from a tenant. */
1490
+ remove: (tenantId: string, userId: string) => Promise<void>;
1491
+ /** POST /env/tenants/{tenantId}/members/{userId}/roles — grant a tenant role to a member. */
1492
+ assignRole: (tenantId: string, userId: string, role: string) => Promise<void>;
1493
+ /** DELETE .../members/{userId}/roles/{role} — revoke a tenant role from a member. */
1494
+ removeRole: (tenantId: string, userId: string, role: string) => Promise<void>;
1495
+ /** POST .../members/{userId}/permissions — grant a permission to a tenant member. */
1496
+ grantPermission: (tenantId: string, userId: string, permission: string) => Promise<void>;
1497
+ /** DELETE .../members/{userId}/permissions/{permission} — revoke a permission from a tenant member. */
1498
+ revokePermission: (tenantId: string, userId: string, permission: string) => Promise<void>;
1499
+ };
1500
+ /**
1501
+ * Invites by e-mail or by link — for addresses that may not have an
1502
+ * account yet; accepting creates it. Managing them needs the
1503
+ * credential's `authyon:users:write` scope (listing, `authyon:tenants:read`).
1504
+ */
1505
+ invites: {
1506
+ /**
1507
+ * GET /env/tenants/{tenantId}/invites — one page of the tenant's
1508
+ * invites, newest first, optionally narrowed by address (`search`)
1509
+ * and by `status`. Up to 0.2.0-beta.26 this returned every invite as
1510
+ * a plain array.
1511
+ */
1512
+ list: (tenantId: string, options?: TenantInviteListOptions) => Promise<Paged<TenantInvite>>;
1513
+ /**
1514
+ * POST /env/tenants/{tenantId}/invites — invite an address. Always
1515
+ * returns `acceptUrl`; with `sendEmail: false` Authyon does not mail
1516
+ * it and you deliver the link yourself. Valid 7 days, single use, and
1517
+ * not readable again later.
1518
+ */
1519
+ create: (tenantId: string, input: TenantInviteInput) => Promise<TenantInviteIssued>;
1520
+ /** POST .../invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1521
+ resend: (tenantId: string, inviteId: string, input?: {
1522
+ sendEmail?: boolean;
1523
+ }) => Promise<TenantInviteIssued>;
1524
+ /** DELETE /env/tenants/{tenantId}/invites/{inviteId} — revoke a pending invite. */
1525
+ revoke: (tenantId: string, inviteId: string) => Promise<void>;
1526
+ /**
1527
+ * POST /auth/tenant-invites/preview — for a backend hosting the accept
1528
+ * page. Public: needs only `envKey`, the token is the credential.
1529
+ */
1530
+ preview: (token: string) => Promise<TenantInvitePreview>;
1531
+ /**
1532
+ * Joins the tenant; for an address with no account, also creates it
1533
+ * (password required) with the e-mail already confirmed. Does not
1534
+ * sign the user in.
1535
+ *
1536
+ * Without metadata: POST /auth/tenant-invites/accept — public, needs
1537
+ * only `envKey`. With `publicMetadata`/`privateMetadata`: POST
1538
+ * /env/tenant-invites/accept with the environment credential
1539
+ * (`authyon:users:write`), since only your backend may set them.
1540
+ */
1541
+ accept: (input: AcceptTenantInviteInput) => Promise<TenantInviteAccepted>;
1542
+ };
1543
+ roles: {
1544
+ /** GET /env/tenants/{tenantId}/roles — list a tenant's roles. */
1545
+ list: (tenantId: string) => Promise<Role[]>;
1546
+ /** POST /env/tenants/{tenantId}/roles — create a tenant role. */
1547
+ create: (tenantId: string, input: RoleInput) => Promise<Role>;
1548
+ /** GET /env/tenants/{tenantId}/roles/{roleId} — fetch a tenant role by id. */
1549
+ get: (tenantId: string, roleId: string) => Promise<Role>;
1550
+ /** PUT /env/tenants/{tenantId}/roles/{roleId} — update a tenant role. */
1551
+ update: (tenantId: string, roleId: string, input: RoleInput) => Promise<Role>;
1552
+ /** DELETE /env/tenants/{tenantId}/roles/{roleId} — delete a tenant role. */
1553
+ delete: (tenantId: string, roleId: string) => Promise<void>;
1554
+ };
1555
+ };
1556
+ roles: {
1557
+ /** GET /env/roles — environment-level roles, grouped into custom and system-defined. */
1558
+ list: () => Promise<RoleList>;
1559
+ /** POST /env/roles — create an environment-level role. */
1560
+ create: (input: RoleInput) => Promise<Role>;
1561
+ /** PUT /env/roles/{roleId} — update an environment-level role. */
1562
+ update: (roleId: string, input: RoleInput) => Promise<Role>;
1563
+ /** DELETE /env/roles/{roleId} — delete an environment-level role. */
1564
+ delete: (roleId: string) => Promise<void>;
1565
+ };
1566
+ permissions: {
1567
+ /** GET /env/permissions — environment-level permissions, grouped by the role they're attached to. */
1568
+ list: () => Promise<PermissionsByRole>;
1569
+ /** POST /env/permissions — create an environment-level permission. */
1570
+ create: (input: CreatePermissionInput) => Promise<Permission>;
1571
+ /** PUT /env/permissions/{permissionId} — update an environment-level permission. */
1572
+ update: (permissionId: string, description?: string) => Promise<Permission>;
1573
+ /** DELETE /env/permissions/{permissionId} — delete an environment-level permission. */
1574
+ delete: (permissionId: string) => Promise<void>;
1575
+ /** GET /permissions/reserved — reserved permission names you can't redefine. */
1576
+ reserved: () => Promise<ReservedPermissions>;
1577
+ };
1578
+ audit: {
1579
+ /** GET /env/audit — paginated list of the environment's audit events. */
1580
+ list: (params?: PaginationOptions) => Promise<Paged<AuditEvent>>;
1581
+ /** GET /env/audit/login-activity — paginated login activity in the environment. */
1582
+ loginActivity: (params?: PaginationOptions) => Promise<Paged<LoginActivity>>;
1583
+ };
1584
+ };
1585
+ readonly security: {
1586
+ otp: {
1587
+ /**
1588
+ * POST /env/users/{userId}/otp/verify — checks the user's authenticator
1589
+ * app (TOTP) code. A wrong code returns `{ valid: false }` instead of
1590
+ * throwing. Each code is accepted once; 3 wrong codes in a row sign the
1591
+ * user out everywhere (`sessionsRevoked: true`); 5 lock the check for 15
1592
+ * minutes (`rate_limited`). More than 50 wrong codes in 10 minutes from the
1593
+ * same credential pause it (`credential_throttled`). Needs `authyon:otp:verify`.
1594
+ */
1595
+ check: (userId: string, code: string) => Promise<OtpCheckResult>;
1596
+ };
1597
+ /**
1598
+ * The customer approves a payload with their authenticator code or
1599
+ * passkey, once.
1600
+ *
1601
+ * 1. `create()` the approval with the payload and the customer.
1602
+ * 2. The customer confirms it (`@authyon/auth` → `security.approvals.confirm`).
1603
+ * 3. `consume()` it right before executing, and execute the returned payload.
1604
+ */
1605
+ approvals: {
1606
+ /** POST /env/authorizations — registers a payload awaiting the customer's approval. */
1607
+ create: (input: CreateApprovalInput) => Promise<Approval>;
1608
+ /** GET /env/authorizations/{id} — current status and, once approved, the assurance evidence. */
1609
+ get: (id: string) => Promise<Approval>;
1610
+ /**
1611
+ * POST /env/authorizations/{id}/consume — redeems an approved approval
1612
+ * exactly once and returns the approved payload. Pass `payload` to have
1613
+ * the API check it matches (`payload_mismatch` otherwise).
1614
+ */
1615
+ consume: (id: string, payload?: ApprovalPayload) => Promise<ConsumedApproval>;
1616
+ };
1617
+ };
1618
+ readonly permissions: {
1619
+ /** POST /users/{userId}/permissions — grant a permission directly to a user. */
1620
+ grant: (userId: string, permission: string) => Promise<void>;
1621
+ /** DELETE /users/{userId}/permissions/{permission} — revoke a permission from a user. */
1622
+ revoke: (userId: string, permission: string) => Promise<void>;
1623
+ };
1624
+ /** @internal used by {@link TenantScopedClient} to share the base URL/fetch/error handling. */
1625
+ _requestAsTenant<T>(accessToken: string, path: string, options?: {
1626
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1627
+ body?: unknown;
1628
+ query?: object;
1629
+ headers?: Record<string, string>;
1630
+ }): Promise<T>;
1631
+ }
1632
+ /**
1633
+ * Client scoped to a single tenant's OAuth credentials — every call acts on
1634
+ * "the token's tenant" (`TenantManagement` endpoints), so there's no
1635
+ * `tenantId` parameter to pass.
1636
+ */
1637
+ declare class TenantScopedClient {
1638
+ private readonly server;
1639
+ private readonly tokenProvider;
1640
+ constructor(server: AuthyonServerClient, credentials: ClientCredentials);
1641
+ private getAccessToken;
1642
+ private request;
1643
+ /** POST /tenant/auth/validate — validates this tenant client's current bearer token. */
1644
+ validate(context?: ClientRequestContext): Promise<TenantClientValidationResult>;
1645
+ /** Invites to the token's tenant, by e-mail or by link. */
1646
+ readonly invites: {
1647
+ /**
1648
+ * GET /tenant/invites — one page of the tenant's invites, newest first,
1649
+ * optionally narrowed by address (`search`) and by `status`. Up to
1650
+ * 0.2.0-beta.26 this returned every invite as a plain array.
1651
+ */
1652
+ list: (options?: TenantInviteListOptions) => Promise<Paged<TenantInvite>>;
1653
+ /** POST /tenant/invites — always returns `acceptUrl`; `sendEmail: false` skips the e-mail. */
1654
+ create: (input: TenantInviteInput) => Promise<TenantInviteIssued>;
1655
+ /** POST /tenant/invites/{inviteId}/resend — new link (the previous one stops working), mailed unless `sendEmail` is `false`. */
1656
+ resend: (inviteId: string, input?: {
1657
+ sendEmail?: boolean;
1658
+ }) => Promise<TenantInviteIssued>;
1659
+ /** DELETE /tenant/invites/{inviteId} — revoke a pending invite. */
1660
+ revoke: (inviteId: string) => Promise<void>;
1661
+ };
1662
+ readonly members: {
1663
+ /**
1664
+ * GET /tenant/members — members of the token's tenant.
1665
+ *
1666
+ * Same handler as `/env/tenants/{id}/members` (the tenant comes from the
1667
+ * token instead of the path), so the same `Paged<T>` envelope of full
1668
+ * user records, `take` defaulting to 50 and capped at 100 — as opposed
1669
+ * to `/auth/tenants/{id}/members`'s lightweight member shape. `search`
1670
+ * works the same way too.
1671
+ */
1672
+ list: (params?: MemberListOptions) => Promise<Paged<EnvironmentUser>>;
1673
+ /** POST /tenant/members — add a member to the token's tenant. */
1674
+ add: (userId: string, roles?: string[]) => Promise<void>;
1675
+ /** DELETE /tenant/members/{userId} — remove a member from the token's tenant. */
1676
+ remove: (userId: string) => Promise<void>;
1677
+ /** POST /tenant/members/{userId}/roles — grant a role to a member of the tenant. */
1678
+ assignRole: (userId: string, role: string) => Promise<void>;
1679
+ /** DELETE /tenant/members/{userId}/roles/{role} — revoke a role from a member of the tenant. */
1680
+ removeRole: (userId: string, role: string) => Promise<void>;
1681
+ /** POST /tenant/members/{userId}/permissions — grant a permission to a member of the tenant. */
1682
+ grantPermission: (userId: string, permission: string) => Promise<void>;
1683
+ /** DELETE .../permissions/{permission} — revoke a permission from a member of the tenant. */
1684
+ revokePermission: (userId: string, permission: string) => Promise<void>;
1685
+ };
1686
+ readonly roles: {
1687
+ /**
1688
+ * GET /tenant/roles — roles in the token's tenant, grouped into custom
1689
+ * and system-defined.
1690
+ *
1691
+ * ⚠️ Inferred, not confirmed live (the test environment had no tenants
1692
+ * to exchange a scoped token for) — assumed to share `/env/roles`'
1693
+ * grouped shape, since both operate on the same underlying role model.
1694
+ */
1695
+ list: () => Promise<RoleList>;
1696
+ /** POST /tenant/roles — create a role in the tenant. */
1697
+ create: (input: RoleInput) => Promise<Role>;
1698
+ /** GET /tenant/roles/{roleId} — fetch a tenant role by id. */
1699
+ get: (roleId: string) => Promise<Role>;
1700
+ /** PUT /tenant/roles/{roleId} — update a role in the tenant. */
1701
+ update: (roleId: string, input: RoleInput) => Promise<Role>;
1702
+ /** DELETE /tenant/roles/{roleId} — delete a role in the tenant. */
1703
+ delete: (roleId: string) => Promise<void>;
1704
+ };
1705
+ }
1706
+ /** Convenience factory: `const authyon = createClient({ clientId, clientSecret })`. */
1707
+ declare function createClient(options?: AuthyonServerClientOptions): AuthyonServerClient;
1708
+
1709
+ export { type PasswordResetIssued as $, AuthyonServerClient as A, type BuiltInPermission as B, CLIENT_IP_HEADER as C, type CredentialListOptions as D, type CredentialPermissionsInput as E, type EnvironmentUser as F, FetchHttpAdapter as G, type HttpAdapter as H, type HttpAdapterRequest as I, JwksTokenVerifier as J, type HttpLogEvent as K, type HttpLogger as L, type IntrospectResult as M, type InviteTenantMemberInput as N, type IssuePasswordResetInput as O, type JsonWebKeySet as P, type JwksTokenVerifierOptions as Q, LoggingHttpAdapter as R, type LoginActivity as S, type MemberListOptions as T, type MyTenant as U, type OpenIdConfiguration as V, type Organization as W, type OtpCheckResult as X, type Paged as Y, type PaginationOptions as Z, type PasswordResetCompleted as _, type HttpLoggerOptions as a, type PasswordResetPreview as a0, type Permission as a1, type PermissionsByRole as a2, type ReservedPermissions as a3, type Role as a4, type RoleGrant as a5, type RoleInput as a6, type RoleList as a7, type RolePermissions as a8, type SafeJwtAlgorithm as a9, type TenantOrder as aA, type TenantOrderField as aB, type TenantParent as aC, TenantScopedClient as aD, type TokenResult as aE, TokenVerificationError as aF, type TokenVerificationErrorCode as aG, type UpdateOrganizationInput as aH, type UpdateTenantInput as aI, type User as aJ, UserScopedClient as aK, type ValidateResult as aL, type VerifiedAccessToken as aM, createClient as aN, normalizeClientIp as aO, tenantFilter as aP, type SecurityMethods as aa, type SubTenant as ab, type SubTenantListOptions as ac, type SubjectApprovals as ad, type SubjectSecurity as ae, TENANT_FILTER_MAX_DEPTH as af, TENANT_FILTER_MAX_VALUES as ag, TENANT_FILTER_MAX_VALUE_LENGTH as ah, type Tenant as ai, type TenantAncestor as aj, type TenantClientValidationResult as ak, type TenantCredentialIssued as al, type TenantCredentialSummary as am, type TenantFilterExpression as an, type TenantFilterValue as ao, type TenantInvite as ap, type TenantInviteAccepted as aq, type TenantInviteInput as ar, type TenantInviteIssued as as, type TenantInviteListOptions as at, type TenantInvitePreview as au, type TenantInviteStatus as av, type TenantListOptions as aw, type TenantMember as ax, type TenantMemberPage as ay, type TenantMembership as az, type AcceptTenantInviteInput as b, type AccessTokenSource as c, type Approval as d, type ApprovalAssurance as e, type ApprovalPayload as f, type ApprovalStatus as g, type ApprovalWebAuthnOptions as h, type AuditEvent as i, type AuthyonJwksDiscoveryOptions as j, type AuthyonJwtClaims as k, type AuthyonServerClientOptions as l, type AuthyonTenantClaim as m, type ClientCredentials as n, type ClientRequestContext as o, type ConfirmApprovalInput as p, type ConsumedApproval as q, type CreateApprovalInput as r, type CreateCredentialInput as s, type CreateOrganizationInput as t, type CreatePermissionInput as u, type CreateTenantCredentialInput as v, type CreateTenantInput as w, type CreateUserInput as x, type CredentialCreator as y, type CredentialDetail as z };