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

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