@hyper.authio/client 0.0.0-stage → 0.7.0

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,1627 @@
1
+ import { JWK, CryptoKey, JWTPayload, JWTVerifyGetKey } from 'jose';
2
+
3
+ /**
4
+ * Claim names Authio writes into its tokens.
5
+ */
6
+ declare const AuthioClaimTypes: {
7
+ readonly Subject: "sub";
8
+ readonly JwtId: "jti";
9
+ readonly Issuer: "iss";
10
+ readonly Audience: "aud";
11
+ readonly Expiration: "exp";
12
+ readonly IssuedAt: "iat";
13
+ readonly NotBefore: "nbf";
14
+ readonly AuthTime: "auth_time";
15
+ readonly TokenType: "typ";
16
+ readonly AuthorizedParty: "azp";
17
+ readonly Scope: "scope";
18
+ readonly SessionId: "sid";
19
+ readonly AuthenticationContextClass: "acr";
20
+ readonly AuthenticationMethods: "amr";
21
+ readonly IdentityProvider: "idp";
22
+ readonly Nonce: "nonce";
23
+ readonly AccessTokenHash: "at_hash";
24
+ readonly Events: "events";
25
+ readonly OrganizationId: "org_id";
26
+ readonly OrganizationAlias: "org_alias";
27
+ readonly AccountId: "account_id";
28
+ readonly Actor: "act";
29
+ readonly DelegationId: "delegation_id";
30
+ readonly ClientId: "client_id";
31
+ readonly Name: "name";
32
+ readonly GivenName: "given_name";
33
+ readonly FamilyName: "family_name";
34
+ readonly UniqueName: "unique_name";
35
+ readonly PreferredUsername: "preferred_username";
36
+ readonly UpdatedAt: "updated_at";
37
+ readonly Email: "email";
38
+ readonly EmailVerified: "email_verified";
39
+ readonly PhoneNumber: "phone_number";
40
+ readonly PhoneNumberVerified: "phone_number_verified";
41
+ readonly ConsumerName: "consumer_name";
42
+ readonly CredentialId: "credential_id";
43
+ readonly CredentialType: "credential_type";
44
+ readonly CredentialName: "credential_name";
45
+ readonly CredentialRealm: "credential_realm";
46
+ readonly CredentialClient: "credential_client";
47
+ readonly ActorType: "actor_type";
48
+ readonly OwnerUserId: "owner_user_id";
49
+ readonly OwnerUsername: "owner_username";
50
+ readonly UserResourceAccess: "user_resource_access";
51
+ readonly RealmResourceAccess: "realm_resource_access";
52
+ readonly ClientResourceAccess: "client_resource_access";
53
+ readonly PlanResourceAccess: "plan_resource_access";
54
+ readonly ConsumerResourceAccess: "consumer_resource_access";
55
+ readonly SecretResourceAccess: "secret_resource_access";
56
+ readonly SystemResourceAccess: "system_resource_access";
57
+ };
58
+ /**
59
+ * Where a role in a `*_resource_access` claim was granted.
60
+ *
61
+ * - `user`: to the person, directly or through one of their groups.
62
+ * - `realm`: to everyone who signs in to the realm.
63
+ * - `client`: to everyone who signs in through the client.
64
+ * - `plan`: by the plan of an Authio platform account (platform users only).
65
+ * - `consumer`: to a machine consumer of the client.
66
+ * - `secret`: to an account credential (API key, client secret, personal access token).
67
+ * - `system`: to an Authio platform user (the console).
68
+ */
69
+ type AuthioResourceAccessSource = "user" | "realm" | "client" | "plan" | "consumer" | "secret" | "system";
70
+ /**
71
+ * The seven `*_resource_access` claim names, mapped to their source.
72
+ */
73
+ declare const AuthioResourceAccessClaims: Readonly<Record<string, AuthioResourceAccessSource>>;
74
+ /**
75
+ * Scopes Authio defines.
76
+ */
77
+ declare const AuthioScopes: {
78
+ readonly OpenId: "openid";
79
+ readonly Profile: "profile";
80
+ readonly Email: "email";
81
+ readonly Phone: "phone";
82
+ readonly Roles: "roles";
83
+ readonly OfflineAccess: "offline_access";
84
+ };
85
+ /**
86
+ * Grant types Authio's token endpoint accepts.
87
+ */
88
+ declare const AuthioGrantTypes: {
89
+ readonly AuthorizationCode: "authorization_code";
90
+ readonly RefreshToken: "refresh_token";
91
+ readonly ClientCredentials: "client_credentials";
92
+ readonly Password: "password";
93
+ readonly DeviceCode: "urn:ietf:params:oauth:grant-type:device_code";
94
+ readonly TokenExchange: "urn:ietf:params:oauth:grant-type:token-exchange";
95
+ readonly PersonalAccessToken: "personal_access_token";
96
+ };
97
+ /**
98
+ * Token type identifiers.
99
+ */
100
+ declare const AuthioTokenTypes: {
101
+ readonly AccessTokenUrn: "urn:ietf:params:oauth:token-type:access_token";
102
+ readonly ConnectionAccessTokenUrn: "urn:authio:params:oauth:token-type:connection-access-token";
103
+ readonly AccessToken: "access_token";
104
+ readonly RefreshToken: "refresh_token";
105
+ };
106
+ /**
107
+ * OAuth error codes Authio answers with.
108
+ */
109
+ declare const AuthioOAuthErrors: {
110
+ readonly InvalidRequest: "invalid_request";
111
+ readonly InvalidClient: "invalid_client";
112
+ readonly InvalidGrant: "invalid_grant";
113
+ readonly UnauthorizedClient: "unauthorized_client";
114
+ readonly UnsupportedGrantType: "unsupported_grant_type";
115
+ readonly InvalidScope: "invalid_scope";
116
+ readonly InvalidTarget: "invalid_target";
117
+ readonly AccessDenied: "access_denied";
118
+ readonly InvalidToken: "invalid_token";
119
+ readonly AuthorizationPending: "authorization_pending";
120
+ readonly SlowDown: "slow_down";
121
+ readonly ExpiredToken: "expired_token";
122
+ readonly ConnectionRequired: "connection_required";
123
+ readonly ConnectionSelectionRequired: "connection_selection_required";
124
+ readonly ConnectionPolicyViolation: "connection_policy_violation";
125
+ readonly ServerError: "server_error";
126
+ readonly TemporarilyUnavailable: "temporarily_unavailable";
127
+ readonly LoginRequired: "login_required";
128
+ readonly InteractionRequired: "interaction_required";
129
+ readonly ConsentRequired: "consent_required";
130
+ readonly AccountSelectionRequired: "account_selection_required";
131
+ readonly InsufficientScope: "insufficient_scope";
132
+ readonly InsufficientUserAuthentication: "insufficient_user_authentication";
133
+ };
134
+ /**
135
+ * Webhook event types.
136
+ */
137
+ declare const AuthioWebhookEventTypes: {
138
+ readonly UserCreated: "user_created";
139
+ readonly UserUpdated: "user_updated";
140
+ readonly UserDeleted: "user_deleted";
141
+ readonly LoginSucceeded: "login_succeeded";
142
+ readonly LoginFailed: "login_failed";
143
+ readonly UserLockedOut: "user_locked_out";
144
+ readonly TokenRevoked: "token_revoked";
145
+ readonly KeysRotated: "keys_rotated";
146
+ readonly TokenReuseDetected: "token_reuse_detected";
147
+ readonly AdminResourceCreated: "admin_resource_created";
148
+ readonly AdminResourceUpdated: "admin_resource_updated";
149
+ readonly AdminResourceDeleted: "admin_resource_deleted";
150
+ readonly UserSuspended: "user_suspended";
151
+ readonly UserSuspensionEnded: "user_suspension_ended";
152
+ readonly AttackDetected: "attack_detected";
153
+ readonly CredentialCompromised: "credential_compromised";
154
+ readonly Ping: "ping";
155
+ };
156
+ /**
157
+ * Headers Authio sends with a webhook delivery.
158
+ */
159
+ declare const AuthioWebhookHeaders: {
160
+ readonly Signature: "X-Authio-Signature";
161
+ readonly Event: "X-Authio-Event";
162
+ readonly EventId: "X-Authio-Event-Id";
163
+ };
164
+ /**
165
+ * Who called an API, read from the access token (see `conformance/callers.json`).
166
+ *
167
+ * - `user`: a person signed in (the token carries `auth_time`).
168
+ * - `client`: a client authenticated as itself.
169
+ * - `consumer`: a machine consumer of a client (`credential_type` `client_consumer`).
170
+ * - `account_credential`: a credential of an Authio account (`credential_type` `account_secret`).
171
+ */
172
+ type AuthioCallerKind = "user" | "client" | "consumer" | "account_credential";
173
+ /**
174
+ * How a machine caller proved who it is.
175
+ */
176
+ type AuthioCredentialForm = "client_secret" | "personal_access_token" | "api_key" | "consumer_api_key";
177
+ /**
178
+ * The caller kinds.
179
+ */
180
+ declare const AuthioCallerKinds: readonly ["user", "client", "consumer", "account_credential"];
181
+ /**
182
+ * The values of `prompt` Authio honours.
183
+ */
184
+ declare const AuthioPrompts: readonly ["none", "login", "select_account", "consent"];
185
+ /**
186
+ * A value of `prompt`.
187
+ */
188
+ type AuthioPrompt = (typeof AuthioPrompts)[number];
189
+ /**
190
+ * Asymmetric signing algorithms Authio issues tokens with and accepts in client assertions.
191
+ */
192
+ declare const AuthioAsymmetricAlgorithms: readonly ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"];
193
+ /**
194
+ * Defaults shared by every Authio SDK.
195
+ */
196
+ declare const AuthioDefaults: {
197
+ readonly DiscoveryPath: "/.well-known/openid-configuration";
198
+ readonly ProtectedResourceMetadataPath: "/.well-known/oauth-protected-resource";
199
+ readonly RedactedValue: "[redacted]";
200
+ readonly PlatformRealm: "authio";
201
+ readonly PlatformClientId: "authio";
202
+ readonly ApiKeyPrefix: "ak_";
203
+ readonly ClientSecretPrefix: "cs_";
204
+ readonly PersonalAccessTokenPrefix: "pat_";
205
+ /** The `client_id` an account credential's client secret is exchanged with: `cred_` and the credential id (format N). */
206
+ readonly CredentialClientIdPrefix: "cred_";
207
+ readonly ApiKeyHeader: "x-api-key";
208
+ readonly RequestIdHeader: "X-Request-Id";
209
+ /** The header `typ` of a back-channel logout token. */
210
+ readonly LogoutTokenType: "logout+jwt";
211
+ /** The event a back-channel logout token carries. */
212
+ readonly BackchannelLogoutEvent: "http://schemas.openid.net/event/backchannel-logout";
213
+ /** Seconds. */
214
+ readonly ClockSkew: 30;
215
+ /** Seconds. */
216
+ readonly ClientAssertionLifetime: 120;
217
+ /** Seconds. */
218
+ readonly MaxClientAssertionLifetime: 3600;
219
+ /** Seconds. */
220
+ readonly DeviceInterval: 5;
221
+ /** Seconds. */
222
+ readonly DeviceSlowDownIncrement: 5;
223
+ /** Seconds a token without `expires_in` is assumed to live. */
224
+ readonly AssumedTokenLifetime: 300;
225
+ /** Seconds. */
226
+ readonly DiscoveryCacheDuration: 3600;
227
+ /** Seconds. */
228
+ readonly HttpTimeout: 30;
229
+ /** Seconds. */
230
+ readonly TokenRefreshSkew: 60;
231
+ /** Seconds. */
232
+ readonly WebhookTolerance: 300;
233
+ /** Smallest RSA key Authio verifies a client assertion from, in bits. */
234
+ readonly MinimumRsaKeySize: 2048;
235
+ readonly CredentialHeaders: readonly ["authorization", "proxy-authorization", "x-api-key", "cookie", "set-cookie"];
236
+ };
237
+
238
+ /**
239
+ * Base class of every error the Authio SDKs throw on purpose.
240
+ */
241
+ declare class AuthioError extends Error {
242
+ constructor(message: string, options?: {
243
+ cause?: unknown;
244
+ });
245
+ }
246
+ /**
247
+ * An OAuth error Authio answered with, or an answer the SDK could not read.
248
+ *
249
+ * `error` is the OAuth error code; `http_{status}` when the body carried none, and `invalid_response` when a success
250
+ * body could not be read.
251
+ */
252
+ declare class AuthioProtocolError extends AuthioError {
253
+ /** The OAuth error code. */
254
+ readonly error: string;
255
+ /** The OAuth error description. */
256
+ readonly errorDescription: string | undefined;
257
+ /** Authio's own error code (`error_code`), more specific than `error`. */
258
+ readonly errorCode: string | undefined;
259
+ /** The HTTP status, when the error came from a response. */
260
+ readonly status: number | undefined;
261
+ constructor(error: string, errorDescription?: string, errorCode?: string, status?: number, options?: {
262
+ cause?: unknown;
263
+ });
264
+ }
265
+ /**
266
+ * The discovery document could not be read, or names another issuer.
267
+ */
268
+ declare class AuthioDiscoveryError extends AuthioError {
269
+ }
270
+ /**
271
+ * The SDK was configured in a way it cannot work with.
272
+ */
273
+ declare class AuthioConfigurationError extends AuthioError {
274
+ }
275
+ /**
276
+ * Why a token was refused, with the outcome names of `conformance/tokens.json`.
277
+ */
278
+ type AuthioTokenFailure = "not_access_token" | "not_id_token" | "invalid_audience" | "invalid_issuer" | "expired" | "not_yet_valid" | "invalid_signature" | "invalid_algorithm" | "reference_token" | "malformed" | "decryption_failed" | "legacy_algorithm" | "invalid_nonce" | "invalid_at_hash" | "authentication_too_old" | "invalid_logout_token" | "signing_keys_unavailable";
279
+ /**
280
+ * A token (ID token, logout token, signed UserInfo, encrypted token) did not pass validation.
281
+ */
282
+ declare class AuthioTokenValidationError extends AuthioError {
283
+ /** Why, as a stable code. */
284
+ readonly reason: AuthioTokenFailure;
285
+ constructor(reason: AuthioTokenFailure, message: string, options?: {
286
+ cause?: unknown;
287
+ });
288
+ }
289
+ /**
290
+ * Why an authorization callback was refused before any code was exchanged.
291
+ */
292
+ type AuthioCallbackFailure = "state_mismatch" | "issuer_mismatch" | "missing_issuer" | "missing_code";
293
+ /**
294
+ * The authorization callback does not belong to the request this client made: `state` differs, the `iss` parameter
295
+ * (RFC 9207) names another issuer or is missing where Authio sends it, or there is no code.
296
+ */
297
+ declare class AuthioCallbackError extends AuthioError {
298
+ /** Why, as a stable code. */
299
+ readonly reason: AuthioCallbackFailure;
300
+ constructor(reason: AuthioCallbackFailure, message: string);
301
+ }
302
+ /**
303
+ * One message of an Admin API error, optionally tied to a field of the request.
304
+ */
305
+ interface AuthioAdminNotification {
306
+ readonly message: string;
307
+ readonly field?: string;
308
+ readonly code?: string;
309
+ }
310
+ /**
311
+ * The Admin API refused a request. `errorCode` is the envelope's top-level `errorCode`; the HTTP status is read from
312
+ * the response, never from the envelope's numeric `statusCode`.
313
+ */
314
+ declare class AuthioAdminError extends AuthioError {
315
+ /** The HTTP status. */
316
+ readonly status: number;
317
+ /** Authio's error code, such as `ValidationFailed` or `RealmNotFound`. */
318
+ readonly errorCode: string | undefined;
319
+ /** The messages, with the field each one is about. */
320
+ readonly notifications: readonly AuthioAdminNotification[];
321
+ /** The request id, from the envelope or the `X-Request-Id` header. */
322
+ readonly requestId: string | undefined;
323
+ /** Seconds to wait before retrying, from `Retry-After` (`429` and `503`). */
324
+ readonly retryAfterSeconds: number | undefined;
325
+ constructor(details: {
326
+ status: number;
327
+ errorCode?: string;
328
+ notifications?: readonly AuthioAdminNotification[];
329
+ requestId?: string;
330
+ retryAfterSeconds?: number;
331
+ cause?: unknown;
332
+ });
333
+ }
334
+
335
+ /**
336
+ * Time as the SDK sees it. Replace it in tests to control expiry, caching and device polling.
337
+ */
338
+ interface AuthioClock {
339
+ /** Milliseconds since the epoch. */
340
+ now(): number;
341
+ /** Waits `ms` milliseconds; rejects when the signal aborts. */
342
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
343
+ }
344
+ /**
345
+ * The real clock.
346
+ */
347
+ declare const systemClock: AuthioClock;
348
+ /**
349
+ * Where Authio is and how to reach it. Shared by the client and the API verifier.
350
+ */
351
+ interface AuthioConnectionOptions {
352
+ /**
353
+ * The realm's issuer, such as `https://auth.example.com/realms/acme`. When absent it is composed from
354
+ * `authority` and `realm`.
355
+ */
356
+ issuer?: string;
357
+ /** Authio's base URL, such as `https://auth.example.com`. */
358
+ authority?: string;
359
+ /** The realm name. */
360
+ realm?: string;
361
+ /**
362
+ * Refuses an `http` issuer or authority unless it is loopback. Defaults to `true`; turn it off only in
363
+ * development.
364
+ */
365
+ requireHttps?: boolean;
366
+ /** Seconds the discovery document is kept. Defaults to 3600. */
367
+ discoveryCacheDuration?: number;
368
+ /** Seconds every HTTP call may take. Defaults to 30. */
369
+ httpTimeout?: number;
370
+ /** The `fetch` every call goes through. Defaults to the global one. */
371
+ fetch?: typeof fetch;
372
+ /** The clock. Defaults to the system clock. */
373
+ clock?: AuthioClock;
374
+ }
375
+ /**
376
+ * How the client authenticates to the token, introspection, revocation and device endpoints.
377
+ */
378
+ type AuthioClientAuthentication = "client_secret_basic" | "client_secret_post" | "private_key_jwt" | "none";
379
+ /**
380
+ * The connection settings, resolved once.
381
+ */
382
+ interface AuthioConnection {
383
+ readonly issuer: string;
384
+ readonly discoveryUrl: string;
385
+ readonly requireHttps: boolean;
386
+ readonly discoveryCacheDurationMs: number;
387
+ readonly httpTimeoutMs: number;
388
+ readonly fetch: typeof fetch;
389
+ readonly clock: AuthioClock;
390
+ }
391
+ /**
392
+ * Resolves and validates the connection settings.
393
+ *
394
+ * @throws AuthioConfigurationError when the issuer cannot be composed or is not HTTPS.
395
+ */
396
+ declare function resolveConnection(options: AuthioConnectionOptions): AuthioConnection;
397
+ /**
398
+ * The issuer: `issuer` when set, else `{authority}/realms/{realm}`.
399
+ *
400
+ * @throws AuthioConfigurationError when neither is configured.
401
+ */
402
+ declare function resolveIssuer(options: Pick<AuthioConnectionOptions, "issuer" | "authority" | "realm">): string;
403
+ /**
404
+ * Whether a URL may be used to reach Authio: HTTPS, or HTTP on loopback (or anywhere when HTTPS is not required).
405
+ */
406
+ declare function isAllowedUrl(value: string, requireHttps: boolean): boolean;
407
+ /**
408
+ * Percent-encodes everything but RFC 3986 unreserved characters, as .NET's `Uri.EscapeDataString` does.
409
+ */
410
+ declare function escapeDataString(value: string): string;
411
+ /**
412
+ * Converts optional seconds to milliseconds, refusing negative or non-finite values.
413
+ *
414
+ * @internal
415
+ */
416
+ declare function seconds(value: number | undefined, fallback: number, name: string): number;
417
+
418
+ /**
419
+ * The realm's OpenID Connect discovery document. Members not listed are kept as sent.
420
+ */
421
+ interface AuthioDiscoveryDocument {
422
+ issuer: string;
423
+ authorization_endpoint?: string;
424
+ token_endpoint?: string;
425
+ userinfo_endpoint?: string;
426
+ jwks_uri?: string;
427
+ introspection_endpoint?: string;
428
+ revocation_endpoint?: string;
429
+ end_session_endpoint?: string;
430
+ device_authorization_endpoint?: string;
431
+ pushed_authorization_request_endpoint?: string;
432
+ scopes_supported?: string[];
433
+ response_types_supported?: string[];
434
+ response_modes_supported?: string[];
435
+ grant_types_supported?: string[];
436
+ subject_types_supported?: string[];
437
+ id_token_signing_alg_values_supported?: string[];
438
+ token_endpoint_auth_methods_supported?: string[];
439
+ token_endpoint_auth_signing_alg_values_supported?: string[];
440
+ introspection_endpoint_auth_methods_supported?: string[];
441
+ revocation_endpoint_auth_methods_supported?: string[];
442
+ code_challenge_methods_supported?: string[];
443
+ claims_supported?: string[];
444
+ prompt_values_supported?: string[];
445
+ authorization_response_iss_parameter_supported?: boolean;
446
+ [member: string]: unknown;
447
+ }
448
+ /**
449
+ * Reads and caches the discovery document.
450
+ */
451
+ interface AuthioDiscoveryClient {
452
+ /** The connection settings the client was built with. */
453
+ readonly connection: AuthioConnection;
454
+ /**
455
+ * The document, read at most once per cache period (concurrent callers share one read).
456
+ *
457
+ * @throws AuthioDiscoveryError when it cannot be read or names another issuer.
458
+ */
459
+ get(signal?: AbortSignal): Promise<AuthioDiscoveryDocument>;
460
+ /** Drops the cached document, so the next `get` reads it again. */
461
+ invalidate(): void;
462
+ }
463
+ /**
464
+ * Creates a discovery client. It needs no client credentials, so an API that only validates tokens can use it.
465
+ */
466
+ declare function createAuthioDiscoveryClient(options: AuthioConnectionOptions | AuthioConnection): AuthioDiscoveryClient;
467
+
468
+ /**
469
+ * The OAuth error body Authio answers with.
470
+ */
471
+ interface AuthioErrorResponse {
472
+ error?: string;
473
+ error_description?: string;
474
+ error_code?: string;
475
+ connect_uri?: string;
476
+ connection_provider?: string;
477
+ connections?: {
478
+ id: string;
479
+ label?: string;
480
+ external_login?: string;
481
+ }[];
482
+ [member: string]: unknown;
483
+ }
484
+ /**
485
+ * Joins scopes into one space-separated value, splitting values that already hold several and dropping duplicates.
486
+ *
487
+ * @returns `undefined` when there is no scope.
488
+ */
489
+ declare function toScopeString(scopes: Iterable<string> | string | undefined | null): string | undefined;
490
+
491
+ /**
492
+ * A private key as the SDK accepts it: PEM text (PKCS#8, PKCS#1 RSA or SEC1 EC; PKCS#1 and SEC1 need Node), a JWK
493
+ * (object or JSON text), or a `CryptoKey`.
494
+ */
495
+ type AuthioPrivateKeyInput = string | JWK | CryptoKey;
496
+ /**
497
+ * The algorithms a client assertion may be signed with.
498
+ */
499
+ declare const AuthioClientAssertionAlgorithms: readonly ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"];
500
+
501
+ /**
502
+ * The client secret, or a function returning the current one, called for every request so a rotated secret is used
503
+ * without a restart.
504
+ */
505
+ type AuthioSecretSource = string | (() => string | Promise<string>);
506
+ /**
507
+ * How the client proves who it is.
508
+ */
509
+ interface AuthioClientCredentialsSettings {
510
+ /** The client id. */
511
+ clientId: string;
512
+ /**
513
+ * The client secret, for `client_secret_basic` and `client_secret_post`; or a function returning the current one,
514
+ * called for every request.
515
+ */
516
+ clientSecret?: AuthioSecretSource;
517
+ /**
518
+ * Defaults to `private_key_jwt` when only a private key is configured, else `client_secret_basic`. A public client
519
+ * sets `none`.
520
+ */
521
+ clientAuthentication?: AuthioClientAuthentication;
522
+ /** The private key for `private_key_jwt`. */
523
+ clientPrivateKey?: AuthioPrivateKeyInput;
524
+ /** A PEM file holding the private key for `private_key_jwt` (Node only); re-read when it changes. */
525
+ clientPrivateKeyPath?: string;
526
+ /** The `kid` of the key, as registered in Authio. */
527
+ clientKeyId?: string;
528
+ /** The assertion's signing algorithm. Defaults to RS256 for RSA keys and the curve's ES algorithm for EC keys. */
529
+ clientSigningAlgorithm?: string;
530
+ /** Seconds a client assertion lives. Defaults to 120, at most 3600. */
531
+ clientAssertionLifetime?: number;
532
+ }
533
+ /**
534
+ * Builds the HTTP Basic value for a client id and secret, escaping both first as RFC 6749 §2.3.1 asks.
535
+ */
536
+ declare function toBasicAuthorization(clientId: string, clientSecret: string): string;
537
+
538
+ /**
539
+ * The client's own encryption key, the pair Authio encrypts the client's tokens and UserInfo to: the private JWK
540
+ * Authio hands over when it generates the pair (object or JSON text), or a PEM private key (PKCS#8 or PKCS#1 RSA).
541
+ */
542
+ type AuthioEncryptionKey = string | JWK;
543
+ /**
544
+ * Where the encryption key comes from: the key itself, or a function returning it (read again on every new
545
+ * algorithm, so a rotated key is picked up).
546
+ */
547
+ type AuthioEncryptionKeySource = AuthioEncryptionKey | (() => AuthioEncryptionKey | Promise<AuthioEncryptionKey>);
548
+ /**
549
+ * Opens a compact JWE and returns its plaintext; a token that is not a JWE comes back unchanged.
550
+ *
551
+ * @throws AuthioTokenValidationError with `legacy_algorithm` for RSA1_5 and `decryption_failed` when the key cannot
552
+ * open it.
553
+ */
554
+ type AuthioTokenDecrypter = (token: string) => Promise<string>;
555
+ /**
556
+ * The key management algorithms Authio encrypts with, and this SDK decrypts.
557
+ */
558
+ declare const AuthioKeyManagementAlgorithms: readonly ["RSA-OAEP", "RSA-OAEP-256"];
559
+ /**
560
+ * Key management algorithms Authio may still use for clients registered long ago. Node and WebCrypto cannot decrypt
561
+ * RSA1_5 (PKCS#1 v1.5), so this SDK refuses it even with `allowLegacyEncryptionAlgorithms`.
562
+ */
563
+ declare const AuthioLegacyKeyManagementAlgorithms: readonly ["RSA1_5"];
564
+ /**
565
+ * The content encryption algorithms Authio encrypts with.
566
+ */
567
+ declare const AuthioContentEncryptionAlgorithms: readonly ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"];
568
+ /**
569
+ * Options of the decrypter.
570
+ */
571
+ interface AuthioTokenDecrypterOptions {
572
+ /** The setting the key came from, named in errors. Defaults to `clientEncryptionKey`. */
573
+ setting?: string;
574
+ /**
575
+ * Accepted for parity with the other Authio SDKs. RSA1_5 stays refused here, with an error saying so, because
576
+ * neither Node nor WebCrypto can decrypt PKCS#1 v1.5.
577
+ */
578
+ allowLegacyEncryptionAlgorithms?: boolean;
579
+ }
580
+ /**
581
+ * Whether a value is a compact JWE (five segments).
582
+ */
583
+ declare function isAuthioTokenEncrypted(token: unknown): token is string;
584
+ /**
585
+ * Creates a decrypter for the client's own encryption key. Keys are imported once per algorithm.
586
+ *
587
+ * @param key The key, a function returning it, or `undefined` when none is configured: an encrypted token then throws.
588
+ * @param options The setting name for errors, and the legacy algorithm switch. A string is taken as the setting name.
589
+ */
590
+ declare function createAuthioTokenDecrypter(key: AuthioEncryptionKeySource | undefined, options?: AuthioTokenDecrypterOptions | string): AuthioTokenDecrypter;
591
+ /**
592
+ * Reads the client's encryption key from a PEM or JWK file (Node only), again whenever the file changes.
593
+ *
594
+ * @internal
595
+ */
596
+ declare function encryptionKeyFromFile(path: string, setting?: string): () => Promise<AuthioEncryptionKey>;
597
+
598
+ /**
599
+ * The claims of a validated ID token. Authio writes `typ` = `ID`, `sid`, `auth_time`, `acr`, `amr`, `nonce` and
600
+ * `at_hash`, besides the profile claims of the granted scopes.
601
+ */
602
+ interface AuthioIdTokenClaims extends JWTPayload {
603
+ sub: string;
604
+ sid?: string;
605
+ nonce?: string;
606
+ auth_time?: number;
607
+ acr?: string;
608
+ amr?: string[];
609
+ at_hash?: string;
610
+ [claim: string]: unknown;
611
+ }
612
+ /**
613
+ * A validated back-channel logout token: end the sessions of `subject`, or the one session `sessionId` names.
614
+ */
615
+ interface AuthioLogoutToken {
616
+ /** `sub`, when the token names the person. */
617
+ readonly subject: string | undefined;
618
+ /** `sid`, when the token names one session. */
619
+ readonly sessionId: string | undefined;
620
+ /** `jti`. */
621
+ readonly tokenId: string | undefined;
622
+ /** Every claim. */
623
+ readonly claims: Readonly<JWTPayload>;
624
+ }
625
+ /**
626
+ * The realm's signing keys, read from the discovery document's `jwks_uri` and cached; an unknown `kid` makes it read
627
+ * them again (at most once every 30 seconds).
628
+ *
629
+ * @internal
630
+ */
631
+ type AuthioSigningKeys = (signal?: AbortSignal) => Promise<JWTVerifyGetKey>;
632
+ /**
633
+ * What a JWT is checked against.
634
+ *
635
+ * @internal
636
+ */
637
+ interface AuthioJwtExpectations {
638
+ readonly issuer: string;
639
+ readonly audiences: readonly string[];
640
+ readonly algorithms?: readonly string[];
641
+ /** Seconds. */
642
+ readonly clockSkew?: number;
643
+ /** Milliseconds since the epoch. */
644
+ readonly now: number;
645
+ readonly requiredClaims?: readonly string[];
646
+ }
647
+ /**
648
+ * Creates the cached reader of the realm's signing keys.
649
+ *
650
+ * @internal
651
+ */
652
+ declare function createAuthioSigningKeys(connection: AuthioConnection, discovery: AuthioDiscoveryClient): AuthioSigningKeys;
653
+ /**
654
+ * Verifies a signed JWT: signature by a realm key with an accepted algorithm, `iss`, `aud`, `exp` (required) and
655
+ * `nbf` with the clock skew.
656
+ *
657
+ * @throws AuthioTokenValidationError naming why the token was refused.
658
+ * @internal
659
+ */
660
+ declare function verifyAuthioJwt(token: string, keys: JWTVerifyGetKey, expected: AuthioJwtExpectations): Promise<{
661
+ payload: JWTPayload;
662
+ header: Record<string, unknown>;
663
+ }>;
664
+ /**
665
+ * Turns a `jose` failure into the refusal it stands for, worded as ASP.NET Core's bearer handler words it.
666
+ *
667
+ * @internal
668
+ */
669
+ declare function toTokenValidationError(error: unknown, audiences: readonly string[], token: string): AuthioTokenValidationError;
670
+ /**
671
+ * The `at_hash` / `c_hash` of a value for a signing algorithm: the left half of its SHA-256, SHA-384 or SHA-512
672
+ * digest, base64url-encoded (OpenID Connect Core §3.1.3.6).
673
+ */
674
+ declare function computeAuthioTokenHash(value: string, algorithm: string): Promise<string>;
675
+
676
+ /**
677
+ * The PKCE method (RFC 7636). `S256` is the default; `plain` only when asked for, for a client that cannot hash.
678
+ */
679
+ type AuthioCodeChallengeMethod = "S256" | "plain";
680
+ /**
681
+ * A PKCE pair: send `codeChallenge` with the authorization request and `codeVerifier` with the code exchange.
682
+ */
683
+ interface AuthioPkcePair {
684
+ readonly codeVerifier: string;
685
+ readonly codeChallenge: string;
686
+ readonly codeChallengeMethod: AuthioCodeChallengeMethod;
687
+ }
688
+ /**
689
+ * What an authorization request asks Authio for. Every member is optional; `redirectUri` falls back to the client's.
690
+ */
691
+ interface AuthioAuthorizationRequest {
692
+ /** Where Authio sends the person back. Defaults to the client's `redirectUri`. */
693
+ redirectUri?: string;
694
+ /** Defaults to `openid`. */
695
+ scopes?: Iterable<string> | string;
696
+ /** The resource server the access token is for (RFC 8707). */
697
+ resource?: string;
698
+ /** The organization (its handle) the sign-in is for. Authoritative: the person cannot switch to another one. */
699
+ organization?: string;
700
+ /** `none` (silent), `login`, `select_account`, `consent`; several are joined with spaces. */
701
+ prompt?: AuthioPrompt | readonly AuthioPrompt[];
702
+ /** Seconds the person's sign-in may be old; Authio asks again past it, and the ID token's `auth_time` is checked. */
703
+ maxAge?: number;
704
+ /** Authentication context classes asked for: `1` one factor, `2` several, `3` one of them phishing-resistant. */
705
+ acrValues?: string | readonly string[];
706
+ /** Pre-fills the identifier on the sign-in screen. */
707
+ loginHint?: string;
708
+ /** A previously issued ID token, naming the person whose session is renewed. */
709
+ idTokenHint?: string;
710
+ /** Languages of the hosted screens, most preferred first. */
711
+ uiLocales?: string | readonly string[];
712
+ /** `page` (default) or `popup`, the layout of the hosted screens. */
713
+ display?: "page" | "popup";
714
+ /** `query` (default) or `web_message`, the popup's answer posted to the opener window. */
715
+ responseMode?: "query" | "web_message";
716
+ /** Shorthand for `display: "popup"` with `responseMode: "web_message"`. */
717
+ popup?: boolean;
718
+ /** The alias of the identity provider to go straight to, skipping Authio's sign-in screen. */
719
+ idpHint?: string;
720
+ /** Defaults to `S256`. */
721
+ codeChallengeMethod?: AuthioCodeChallengeMethod;
722
+ /** A `state` of your own; a random one otherwise. */
723
+ state?: string;
724
+ /** A `nonce` of your own; a random one otherwise. */
725
+ nonce?: string;
726
+ /** Further parameters, sent as given. */
727
+ extraParameters?: Record<string, string | undefined>;
728
+ }
729
+ /**
730
+ * What the application keeps between the authorization request and the callback (in its session, a cookie, …), to
731
+ * check the callback and redeem the code.
732
+ */
733
+ interface AuthioAuthorizationTransaction {
734
+ readonly state: string;
735
+ readonly nonce: string;
736
+ readonly codeVerifier: string;
737
+ readonly codeChallengeMethod: AuthioCodeChallengeMethod;
738
+ readonly redirectUri: string;
739
+ readonly resource?: string;
740
+ readonly maxAge?: number;
741
+ }
742
+ /**
743
+ * An authorization URL and the transaction to keep until the callback.
744
+ */
745
+ interface AuthioAuthorizationUrl {
746
+ readonly url: string;
747
+ readonly transaction: AuthioAuthorizationTransaction;
748
+ }
749
+ /**
750
+ * A `WWW-Authenticate` bearer challenge, as an API answers it (RFC 6750, RFC 9470, RFC 9728).
751
+ */
752
+ interface AuthioBearerChallenge {
753
+ readonly error: string | undefined;
754
+ readonly errorDescription: string | undefined;
755
+ /** `insufficient_scope`: the scopes required. */
756
+ readonly scope: string | undefined;
757
+ /** `insufficient_user_authentication`: the context classes to ask for. */
758
+ readonly acrValues: string | undefined;
759
+ /** `insufficient_user_authentication`: how old the sign-in may be, in seconds. */
760
+ readonly maxAge: number | undefined;
761
+ /** RFC 9728: where the API's protected resource metadata is. */
762
+ readonly resourceMetadata: string | undefined;
763
+ }
764
+ /**
765
+ * Creates a PKCE pair: a 256-bit random verifier and its S256 (or plain) challenge.
766
+ */
767
+ declare function createAuthioPkce(method?: AuthioCodeChallengeMethod): Promise<AuthioPkcePair>;
768
+ /**
769
+ * A random, URL-safe value of `bytes` random bytes, for `state` and `nonce`.
770
+ */
771
+ declare function randomValue(bytes?: number): string;
772
+ /**
773
+ * Parses a `WWW-Authenticate` bearer challenge, or `undefined` when the header holds none.
774
+ */
775
+ declare function parseAuthioBearerChallenge(header: string | null | undefined): AuthioBearerChallenge | undefined;
776
+
777
+ /**
778
+ * A token endpoint answer, as Authio sends it.
779
+ */
780
+ interface AuthioTokenResponse {
781
+ access_token: string;
782
+ token_type?: string;
783
+ /** Seconds. */
784
+ expires_in?: number;
785
+ /** Rotated on every refresh: store the new one. */
786
+ refresh_token?: string;
787
+ /** Seconds. */
788
+ refresh_expires_in?: number;
789
+ id_token?: string;
790
+ scope?: string;
791
+ session_state?: string;
792
+ issued_token_type?: string;
793
+ [member: string]: unknown;
794
+ }
795
+ /**
796
+ * An introspection answer (RFC 7662). Authio adds the token's other claims (roles, organization, claim-mapper
797
+ * claims, the user's own claims) as extra members.
798
+ */
799
+ interface AuthioIntrospectionResult {
800
+ active: boolean;
801
+ scope?: string;
802
+ client_id?: string;
803
+ username?: string;
804
+ token_type?: string;
805
+ exp?: number;
806
+ iat?: number;
807
+ nbf?: number;
808
+ sub?: string;
809
+ aud?: string | string[];
810
+ iss?: string;
811
+ jti?: string;
812
+ [member: string]: unknown;
813
+ }
814
+ /**
815
+ * A device authorization answer (RFC 8628).
816
+ */
817
+ interface AuthioDeviceAuthorization {
818
+ device_code: string;
819
+ user_code: string;
820
+ verification_uri: string;
821
+ verification_uri_complete?: string;
822
+ /** Seconds. */
823
+ expires_in: number;
824
+ /** Seconds between polls. */
825
+ interval?: number;
826
+ [member: string]: unknown;
827
+ }
828
+ /**
829
+ * What Authio's UserInfo endpoint answers: `sub` and the standard claims of the granted `profile`, `email` and `phone`
830
+ * scopes. Roles, claim-mapper claims, the user's own claims and the organization never reach it; read them from the
831
+ * access token or the ID token.
832
+ */
833
+ interface AuthioUserInfo {
834
+ sub: string;
835
+ name?: string;
836
+ given_name?: string;
837
+ family_name?: string;
838
+ preferred_username?: string;
839
+ email?: string;
840
+ email_verified?: boolean;
841
+ phone_number?: string;
842
+ phone_number_verified?: boolean;
843
+ [claim: string]: unknown;
844
+ }
845
+ /**
846
+ * A cached client-credentials token.
847
+ */
848
+ interface AuthioClientCredentialsToken {
849
+ readonly accessToken: string;
850
+ readonly tokenType: string;
851
+ /** Milliseconds since the epoch. */
852
+ readonly expiresAt: number;
853
+ /** When the cache renews it, in milliseconds since the epoch. */
854
+ readonly refreshAt: number;
855
+ readonly scope: string | undefined;
856
+ }
857
+ /**
858
+ * One of the person's connected accounts at a provider.
859
+ */
860
+ interface AuthioConnectionChoice {
861
+ readonly id: string;
862
+ readonly label?: string;
863
+ /** The account's login at the provider. */
864
+ readonly externalLogin?: string;
865
+ }
866
+ /**
867
+ * The account at the provider a connection token belongs to.
868
+ */
869
+ interface AuthioExternalAccount {
870
+ id?: string;
871
+ login?: string;
872
+ email?: string;
873
+ [member: string]: unknown;
874
+ }
875
+ /**
876
+ * The outcome of exchanging a user's token for the token of one of their connected accounts.
877
+ */
878
+ type AuthioConnectionExchangeResult = AuthioConnectionGranted | AuthioConnectionRequired | AuthioConnectionSelectionRequired | AuthioConnectionRefused;
879
+ /**
880
+ * The provider's access token.
881
+ */
882
+ interface AuthioConnectionGranted {
883
+ readonly status: "granted";
884
+ readonly accessToken: string;
885
+ /** `urn:authio:params:oauth:token-type:connection-access-token`. */
886
+ readonly issuedTokenType?: string;
887
+ readonly tokenType?: string;
888
+ /** Seconds. */
889
+ readonly expiresIn?: number;
890
+ readonly scope?: string;
891
+ readonly connectionId?: string;
892
+ readonly provider: string;
893
+ /** The kind of provider, such as `GitHubApp`. */
894
+ readonly providerType?: string;
895
+ readonly externalAccount?: AuthioExternalAccount;
896
+ }
897
+ /**
898
+ * The person has not connected an account at the provider yet; send them to `connectUri`.
899
+ */
900
+ interface AuthioConnectionRequired {
901
+ readonly status: "required";
902
+ readonly connectUri?: string;
903
+ readonly provider: string;
904
+ readonly errorCode?: string;
905
+ readonly errorDescription: string;
906
+ }
907
+ /**
908
+ * The person has several accounts at the provider; ask again with one `connectionId`.
909
+ */
910
+ interface AuthioConnectionSelectionRequired {
911
+ readonly status: "selection_required";
912
+ readonly provider: string;
913
+ readonly connections: readonly AuthioConnectionChoice[];
914
+ readonly errorCode?: string;
915
+ readonly errorDescription: string;
916
+ }
917
+ /**
918
+ * Authio refused the exchange.
919
+ */
920
+ interface AuthioConnectionRefused {
921
+ readonly status: "refused";
922
+ readonly error: string;
923
+ readonly errorCode?: string;
924
+ readonly errorDescription: string;
925
+ readonly connectUri?: string;
926
+ }
927
+ /**
928
+ * What one poll of the device flow's token endpoint means (RFC 8628 §3.5).
929
+ */
930
+ type AuthioDevicePollOutcome = {
931
+ readonly outcome: "keep_polling";
932
+ readonly intervalIncrease: number;
933
+ } | {
934
+ readonly outcome: "failed";
935
+ readonly error: string;
936
+ };
937
+
938
+ /**
939
+ * Everything the Authio client needs: where Authio is, and the client's credentials.
940
+ */
941
+ interface AuthioClientOptions extends AuthioConnectionOptions, AuthioClientCredentialsSettings {
942
+ /**
943
+ * Seconds before expiry a cached token is renewed (capped at half its lifetime). Defaults to 60.
944
+ */
945
+ tokenRefreshSkew?: number;
946
+ /**
947
+ * The private half of the client's own encryption key, to read ID tokens, UserInfo and logout tokens Authio
948
+ * encrypts to the client (RSA-OAEP or RSA-OAEP-256); or a function returning it.
949
+ */
950
+ clientEncryptionKey?: AuthioEncryptionKeySource;
951
+ /** A PEM or JWK file holding `clientEncryptionKey` (Node only), read on first use. */
952
+ clientEncryptionKeyPath?: string;
953
+ /**
954
+ * Accepted for parity with the other Authio SDKs; RSA1_5 stays refused here, because Node and WebCrypto cannot
955
+ * decrypt it. Defaults to `false`.
956
+ */
957
+ allowLegacyEncryptionAlgorithms?: boolean;
958
+ /** Where Authio sends the person back after signing in, unless a request names another. */
959
+ redirectUri?: string;
960
+ /** Where Authio sends the person after signing out, unless a request names another. */
961
+ postLogoutRedirectUri?: string;
962
+ /** Seconds of clock skew tolerated on ID tokens, logout tokens and signed UserInfo. Defaults to 30. */
963
+ clockSkew?: number;
964
+ /** Algorithms ID tokens, logout tokens and signed UserInfo are accepted with. Defaults to RS*, PS*, ES*. */
965
+ validAlgorithms?: readonly string[];
966
+ }
967
+ /**
968
+ * What a completed sign-in yields.
969
+ */
970
+ interface AuthioAuthorizationResult {
971
+ /** The token endpoint's answer: access token, refresh token, ID token. */
972
+ readonly tokens: AuthioTokenResponse;
973
+ /** The validated ID token's claims, when Authio issued one (the `openid` scope). */
974
+ readonly idToken: AuthioIdTokenClaims | undefined;
975
+ }
976
+ /**
977
+ * What the end-session URL carries (OpenID Connect RP-Initiated Logout).
978
+ */
979
+ interface AuthioEndSessionRequest {
980
+ /** The ID token of the session to end. */
981
+ idTokenHint?: string;
982
+ /** Where to send the person afterwards; must be registered. Defaults to the client's `postLogoutRedirectUri`. */
983
+ postLogoutRedirectUri?: string;
984
+ /** Echoed back to `postLogoutRedirectUri`. */
985
+ state?: string;
986
+ /** The language of the signed-out screen. */
987
+ uiLocales?: string | readonly string[];
988
+ /** Sends the client id unless `false`, so Authio knows the client without an ID token. */
989
+ includeClientId?: boolean;
990
+ }
991
+ /**
992
+ * Per-call options.
993
+ */
994
+ interface AuthioCallOptions {
995
+ /** Aborts the call. */
996
+ signal?: AbortSignal;
997
+ }
998
+ /**
999
+ * The token endpoint's grants.
1000
+ */
1001
+ interface AuthioTokenClient {
1002
+ /** `client_credentials`, optionally for a resource (RFC 8707). */
1003
+ clientCredentials(options?: {
1004
+ scopes?: Iterable<string> | string;
1005
+ resource?: string;
1006
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1007
+ /** Redeems an authorization code. */
1008
+ authorizationCode(options: {
1009
+ code: string;
1010
+ redirectUri: string;
1011
+ codeVerifier?: string;
1012
+ resource?: string;
1013
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1014
+ /** Refreshes; the answer carries the rotated refresh token, which must be stored. */
1015
+ refresh(options: {
1016
+ refreshToken: string;
1017
+ scopes?: Iterable<string> | string;
1018
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1019
+ /** Exchanges a user's access token for one addressed to another resource (RFC 8693, on-behalf-of). */
1020
+ exchange(options: {
1021
+ subjectToken: string;
1022
+ scopes?: Iterable<string> | string;
1023
+ resource?: string;
1024
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1025
+ /**
1026
+ * Exchanges a user's access token for the token of one of their connected accounts. OAuth refusals come back as
1027
+ * a result, never thrown.
1028
+ */
1029
+ exchangeForConnection(options: {
1030
+ subjectToken: string;
1031
+ provider: string;
1032
+ connectionId?: string;
1033
+ } & AuthioCallOptions): Promise<AuthioConnectionExchangeResult>;
1034
+ /** Starts the device flow (RFC 8628). */
1035
+ deviceAuthorization(options?: {
1036
+ scopes?: Iterable<string> | string;
1037
+ } & AuthioCallOptions): Promise<AuthioDeviceAuthorization>;
1038
+ /**
1039
+ * Polls until the person approves: waits `interval` (default 5 s) before each poll, adds 5 s on `slow_down`, throws
1040
+ * on `access_denied` and `expired_token`, and throws `expired_token` when `expires_in` elapses locally.
1041
+ */
1042
+ pollDevice(authorization: AuthioDeviceAuthorization | {
1043
+ device_code: string;
1044
+ interval?: number;
1045
+ expires_in?: number;
1046
+ }, options?: AuthioCallOptions): Promise<AuthioTokenResponse>;
1047
+ /** The resource owner password grant, where the client allows it. */
1048
+ password(options: {
1049
+ username: string;
1050
+ password: string;
1051
+ scopes?: Iterable<string> | string;
1052
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1053
+ /**
1054
+ * The `personal_access_token` grant: a `pat_` value presented as `client_secret`, with the consumer's client id for
1055
+ * a consumer's token or none for an account's token. The client's own credentials are not sent.
1056
+ */
1057
+ personalAccessToken(options: {
1058
+ token: string;
1059
+ clientId?: string;
1060
+ scopes?: Iterable<string> | string;
1061
+ resource?: string;
1062
+ } & AuthioCallOptions): Promise<AuthioTokenResponse>;
1063
+ }
1064
+ /**
1065
+ * Client-credentials tokens, cached per scopes and resource.
1066
+ */
1067
+ interface AuthioClientCredentialsCache {
1068
+ /**
1069
+ * A token for the scopes and resource, renewed `tokenRefreshSkew` before expiry (at most half its lifetime);
1070
+ * concurrent callers for one key share one request.
1071
+ */
1072
+ getToken(options?: {
1073
+ scopes?: Iterable<string> | string;
1074
+ resource?: string;
1075
+ } & AuthioCallOptions): Promise<AuthioClientCredentialsToken>;
1076
+ /** Drops the cached token; with `accessToken`, only when the cache still holds that token. */
1077
+ invalidate(options?: {
1078
+ scopes?: Iterable<string> | string;
1079
+ resource?: string;
1080
+ accessToken?: string;
1081
+ }): void;
1082
+ }
1083
+ /**
1084
+ * The Authio client.
1085
+ */
1086
+ interface AuthioClient {
1087
+ /** The issuer. */
1088
+ readonly issuer: string;
1089
+ /** The client id. */
1090
+ readonly clientId: string;
1091
+ /** The connection settings. */
1092
+ readonly connection: AuthioConnection;
1093
+ /** The discovery document. */
1094
+ readonly discovery: AuthioDiscoveryClient;
1095
+ /** The token endpoint. */
1096
+ readonly tokens: AuthioTokenClient;
1097
+ /** Cached client-credentials tokens. */
1098
+ readonly clientCredentials: AuthioClientCredentialsCache;
1099
+ /**
1100
+ * Introspects a token as this client (RFC 7662). Authio answers according to who asks: a token requested for a
1101
+ * resource (RFC 8707) is active only to the client that resource server names as its introspection client.
1102
+ */
1103
+ introspect(token: string, options?: {
1104
+ tokenTypeHint?: string;
1105
+ } & AuthioCallOptions): Promise<AuthioIntrospectionResult>;
1106
+ /** Revokes a token (RFC 7009). */
1107
+ revoke(token: string, options?: {
1108
+ tokenTypeHint?: string;
1109
+ } & AuthioCallOptions): Promise<void>;
1110
+ /**
1111
+ * Reads UserInfo. A UserInfo answered as `application/jwt` is decrypted with `clientEncryptionKey` when it is a
1112
+ * JWE, then verified against the realm's keys (`iss` the issuer, `aud` the client).
1113
+ */
1114
+ userInfo(accessToken: string, options?: AuthioCallOptions): Promise<AuthioUserInfo>;
1115
+ /**
1116
+ * A `fetch` that sends a cached client-credentials token, and on a `401` drops it and retries once.
1117
+ */
1118
+ clientCredentialsFetch(options?: {
1119
+ scopes?: Iterable<string> | string;
1120
+ resource?: string;
1121
+ fetch?: typeof fetch;
1122
+ }): typeof fetch;
1123
+ /**
1124
+ * Builds the authorization URL (PKCE S256, `state`, `nonce` and Authio's parameters) and the transaction to keep
1125
+ * until the callback.
1126
+ */
1127
+ createAuthorizationUrl(request?: AuthioAuthorizationRequest & AuthioCallOptions): Promise<AuthioAuthorizationUrl>;
1128
+ /**
1129
+ * Completes a sign-in: checks `state` and the `iss` parameter (RFC 9207), throws the OAuth error Authio sent back,
1130
+ * redeems the code with the PKCE verifier, and validates the ID token (nonce, `at_hash`, `max_age`).
1131
+ *
1132
+ * @param callback The callback URL, its query, or its parameters (a `web_message` answer, a parsed query).
1133
+ * @param transaction What `createAuthorizationUrl` returned with the URL.
1134
+ * @throws AuthioCallbackError when the callback is not for this transaction.
1135
+ * @throws AuthioProtocolError for an OAuth error.
1136
+ * @throws AuthioTokenValidationError when the ID token does not validate.
1137
+ */
1138
+ handleAuthorizationCallback(callback: string | URL | URLSearchParams | Readonly<Record<string, unknown>>, transaction: AuthioAuthorizationTransaction, options?: AuthioCallOptions): Promise<AuthioAuthorizationResult>;
1139
+ /**
1140
+ * Validates an ID token: decrypted with `clientEncryptionKey` when it is a JWE, then signature (cached JWKS), `iss`,
1141
+ * `aud` = the client id, `exp` with the skew, payload `typ` = `ID`, and `nonce`, `at_hash` and `auth_time` when
1142
+ * given.
1143
+ *
1144
+ * @throws AuthioTokenValidationError naming why it was refused.
1145
+ */
1146
+ validateIdToken(idToken: string, expectations?: {
1147
+ nonce?: string;
1148
+ accessToken?: string;
1149
+ maxAge?: number;
1150
+ } & AuthioCallOptions): Promise<AuthioIdTokenClaims>;
1151
+ /**
1152
+ * Validates a back-channel logout token Authio posted as `logout_token`.
1153
+ *
1154
+ * @throws AuthioTokenValidationError naming why it was refused (`invalid_logout_token` for the logout-specific rules).
1155
+ */
1156
+ validateLogoutToken(logoutToken: string, options?: AuthioCallOptions): Promise<AuthioLogoutToken>;
1157
+ /** Builds the end-session URL (RP-Initiated Logout). */
1158
+ createEndSessionUrl(request?: AuthioEndSessionRequest & AuthioCallOptions): Promise<string>;
1159
+ /**
1160
+ * Builds an authorization URL that satisfies an API's `insufficient_user_authentication` challenge (RFC 9470): its
1161
+ * `acr_values` and `max_age`, with `prompt=login` when the challenge asks for a sign-in made just now (`max_age=0`).
1162
+ *
1163
+ * @param challenge The `WWW-Authenticate` header value, or the challenge already parsed.
1164
+ */
1165
+ createStepUpAuthorizationUrl(challenge: string | AuthioBearerChallenge, request?: AuthioAuthorizationRequest & AuthioCallOptions): Promise<AuthioAuthorizationUrl>;
1166
+ }
1167
+ /**
1168
+ * Creates the Authio client.
1169
+ *
1170
+ * @throws AuthioConfigurationError when the settings are incomplete.
1171
+ */
1172
+ declare function createAuthioClient(options: AuthioClientOptions): AuthioClient;
1173
+ /**
1174
+ * When a token answer expires, and when a cache should renew it: `expires_in` (else 5 minutes) after `issuedAt`,
1175
+ * renewed `refreshSkewMs` before that, at most half its lifetime.
1176
+ */
1177
+ declare function toClientCredentialsToken(response: AuthioTokenResponse, issuedAt: number, refreshSkewMs: number): AuthioClientCredentialsToken;
1178
+ /**
1179
+ * Reads the answer of a connected-account token exchange (see `conformance/oauth-responses.json`).
1180
+ *
1181
+ * @internal
1182
+ */
1183
+ declare function toConnectionExchangeResult(body: string, status: number, provider: string): AuthioConnectionExchangeResult;
1184
+ /**
1185
+ * What a device-flow poll's OAuth error means: keep polling (5 seconds slower after `slow_down`), or stop with it.
1186
+ */
1187
+ declare function toDevicePollOutcome(error: string): AuthioDevicePollOutcome;
1188
+
1189
+ /**
1190
+ * A successful Admin API answer: the envelope's `data` (one object, or a listing's page `{ items, totalCount,
1191
+ * pageNumber, pageSize }`), nothing for `204`.
1192
+ */
1193
+ interface AuthioAdminSuccess<T = unknown> {
1194
+ readonly ok: true;
1195
+ readonly data?: T;
1196
+ }
1197
+ /**
1198
+ * A refused Admin API answer.
1199
+ */
1200
+ interface AuthioAdminFailure {
1201
+ readonly ok: false;
1202
+ readonly error: AuthioAdminError;
1203
+ }
1204
+ /**
1205
+ * An Admin API answer, read.
1206
+ */
1207
+ type AuthioAdminEnvelope<T = unknown> = AuthioAdminSuccess<T> | AuthioAdminFailure;
1208
+ /**
1209
+ * How an account credential is presented: `ak_` (API key), `cs_` (client secret, exchanged first) or `pat_`
1210
+ * (personal access token).
1211
+ */
1212
+ type AuthioAccountCredentialKind = "api_key" | "client_secret" | "personal_access_token";
1213
+ /**
1214
+ * Options of `createAuthioAccountCredential`.
1215
+ */
1216
+ interface AuthioAccountCredentialOptions extends Omit<AuthioConnectionOptions, "issuer" | "realm"> {
1217
+ /** Authio's base URL, such as `https://auth.example.com`. Required. */
1218
+ authority?: string;
1219
+ /** The credential's value: `ak_…`, `cs_…` or `pat_…`. */
1220
+ credential: string;
1221
+ /** The credential's id, needed to exchange a `cs_` secret (its `client_id` is `cred_` and the id without dashes). */
1222
+ credentialId?: string;
1223
+ /** How an `ak_` or `pat_` value is sent directly: `Authorization: Bearer` (default) or `x-api-key`. */
1224
+ presentAs?: "bearer" | "x-api-key";
1225
+ /** Exchanges a `pat_` value with the `personal_access_token` grant instead of sending it directly. */
1226
+ exchangePersonalAccessToken?: boolean;
1227
+ /** Narrows an exchanged token to these `admin:{permission}:{method}` scopes. */
1228
+ scopes?: Iterable<string> | string;
1229
+ /** Seconds before expiry an exchanged token is renewed (at most half its lifetime). Defaults to 60. */
1230
+ tokenRefreshSkew?: number;
1231
+ }
1232
+ /**
1233
+ * An account credential ready to call the Admin API with.
1234
+ */
1235
+ interface AuthioAccountCredential {
1236
+ /** How the credential is presented. */
1237
+ readonly kind: AuthioAccountCredentialKind;
1238
+ /** Whether it is exchanged at the `authio` realm's token endpoint before use. */
1239
+ readonly exchanged: boolean;
1240
+ /** The headers that authenticate a request: `Authorization` or `x-api-key`. */
1241
+ headers(signal?: AbortSignal): Promise<Record<string, string>>;
1242
+ /** Drops an exchanged token, so the next request exchanges again. */
1243
+ invalidate(): void;
1244
+ /**
1245
+ * A `fetch` that authenticates every request; on `401` with an exchanged token it exchanges again and retries once;
1246
+ * on `429` or `503` it waits `Retry-After` and retries an idempotent request (`GET`, `HEAD`, `PUT`, `DELETE`) once.
1247
+ */
1248
+ readonly fetch: typeof fetch;
1249
+ }
1250
+ /**
1251
+ * Reads an Admin API answer (see `conformance/admin-envelopes.json`). The status is the HTTP one, never the
1252
+ * envelope's numeric `statusCode`; `requestId` falls back to `X-Request-Id`, and `retryAfterSeconds` comes from
1253
+ * `Retry-After`.
1254
+ */
1255
+ declare function parseAuthioAdminEnvelope<T = unknown>(status: number, body: string | null | undefined, headers?: Headers | Readonly<Record<string, string | undefined>>): AuthioAdminEnvelope<T>;
1256
+ /**
1257
+ * Reads an Admin API response, throwing `AuthioAdminError` when it is not a success.
1258
+ */
1259
+ declare function readAuthioAdminResponse<T = unknown>(response: Response): Promise<AuthioAdminSuccess<T>>;
1260
+ /**
1261
+ * Prepares an account credential for the Admin API: `ak_` and `pat_` go directly as `Authorization: Bearer` (or
1262
+ * `x-api-key`); a `cs_` secret is exchanged at `{authority}/realms/authio` with `client_credentials` and the
1263
+ * `client_id` `cred_{id}`; a `pat_` may be exchanged with the `personal_access_token` grant instead. Exchanged tokens
1264
+ * are cached and renewed before expiry.
1265
+ *
1266
+ * @throws AuthioConfigurationError when the value has no known prefix or a `cs_` secret comes without its id.
1267
+ */
1268
+ declare function createAuthioAccountCredential(options: AuthioAccountCredentialOptions): AuthioAccountCredential;
1269
+ /**
1270
+ * The `client_id` an account credential's client secret is exchanged with: `cred_` and the id in format N (no dashes,
1271
+ * lower case). An id already starting with `cred_` is kept.
1272
+ */
1273
+ declare function toCredentialClientId(credentialId: string): string;
1274
+
1275
+ /**
1276
+ * One role read from a `*_resource_access` claim, with the permissions it grants.
1277
+ */
1278
+ interface AuthioResourceAccessRole {
1279
+ /** The claim the role came from. */
1280
+ readonly source: AuthioResourceAccessSource;
1281
+ /** The role name. */
1282
+ readonly name: string;
1283
+ /** Resource → methods the role allows on it. */
1284
+ readonly permissions: Readonly<Record<string, readonly string[]>>;
1285
+ }
1286
+ /**
1287
+ * The roles and permissions a token carries in its `*_resource_access` claims, merged across sources.
1288
+ *
1289
+ * Every comparison is case-insensitive, as Authio's own check is. When a name appears in different case, the first
1290
+ * spelling read is the one listed.
1291
+ */
1292
+ declare class AuthioResourceAccess {
1293
+ /** No role at all. */
1294
+ static readonly empty: AuthioResourceAccess;
1295
+ /** Every role read, in claim order, one entry per source it came from. */
1296
+ readonly entries: readonly AuthioResourceAccessRole[];
1297
+ /** Every distinct role name. */
1298
+ readonly roles: readonly string[];
1299
+ /** Resource → every method any role allows on it. */
1300
+ readonly permissions: Readonly<Record<string, readonly string[]>>;
1301
+ private readonly lookup;
1302
+ constructor(entries: Iterable<AuthioResourceAccessRole>);
1303
+ /** Whether no role was read. */
1304
+ get isEmpty(): boolean;
1305
+ /**
1306
+ * Whether the token holds the role, from any source or only from the given ones.
1307
+ */
1308
+ hasRole(role: string, sources?: readonly AuthioResourceAccessSource[]): boolean;
1309
+ /**
1310
+ * Authio's grant rule: whether any role (from any source, or only from the given ones) allows `method` on
1311
+ * `resource`.
1312
+ */
1313
+ grants(resource: string, method: string, sources?: readonly AuthioResourceAccessSource[]): boolean;
1314
+ /**
1315
+ * The roles that came from one source.
1316
+ */
1317
+ fromSource(source: AuthioResourceAccessSource): AuthioResourceAccessRole[];
1318
+ }
1319
+ /**
1320
+ * The source a claim name stands for, when it is one of the seven `*_resource_access` claims.
1321
+ */
1322
+ declare function resourceAccessSourceOf(claimType: string | undefined | null): AuthioResourceAccessSource | undefined;
1323
+ /**
1324
+ * Reads the roles of every `*_resource_access` claim. Takes a JWT payload or introspection answer, or
1325
+ * `[type, value]` pairs; each value may be the JSON object itself or its JSON text. Other claims are ignored.
1326
+ */
1327
+ declare function parseResourceAccess(claims: Readonly<Record<string, unknown>> | Iterable<readonly [string, unknown]>): AuthioResourceAccess;
1328
+ /**
1329
+ * Reads the roles of one claim value, as strictly as Authio does: a value that is not exactly
1330
+ * `{role: {resource: [method]}}` contributes nothing at all. `null` roles, resources and methods are allowed and grant
1331
+ * nothing.
1332
+ */
1333
+ declare function parseResourceAccessClaim(source: AuthioResourceAccessSource, value: unknown): AuthioResourceAccessRole[];
1334
+
1335
+ /**
1336
+ * Why a webhook delivery failed verification.
1337
+ */
1338
+ type AuthioWebhookVerificationFailure = "missing_signature" | "malformed_signature" | "signature_mismatch" | "timestamp_outside_tolerance";
1339
+ /**
1340
+ * The outcome of verifying a webhook signature.
1341
+ */
1342
+ type AuthioWebhookVerificationResult = {
1343
+ readonly valid: true;
1344
+ readonly timestamp: Date;
1345
+ } | {
1346
+ readonly valid: false;
1347
+ readonly failure: AuthioWebhookVerificationFailure;
1348
+ readonly reason: string;
1349
+ readonly timestamp?: Date;
1350
+ };
1351
+ /**
1352
+ * A webhook event. `data` holds the event-specific payload as delivered (snake_case); read it typed, in camelCase,
1353
+ * with the `as…` helpers.
1354
+ */
1355
+ interface AuthioWebhookEvent {
1356
+ readonly id: string;
1357
+ readonly type: string;
1358
+ /** Seconds since the epoch. */
1359
+ readonly created_at: number;
1360
+ readonly realm_id?: string | null;
1361
+ readonly client_id?: string | null;
1362
+ readonly data: unknown;
1363
+ [member: string]: unknown;
1364
+ }
1365
+ /** `user_created`, `user_updated`, `user_deleted`, as delivered. */
1366
+ interface AuthioWebhookUserData {
1367
+ id: string;
1368
+ username?: string | null;
1369
+ email?: string | null;
1370
+ first_name?: string | null;
1371
+ last_name?: string | null;
1372
+ email_confirmed: boolean;
1373
+ status?: string | null;
1374
+ realm_id?: string | null;
1375
+ client_id?: string | null;
1376
+ }
1377
+ /** `login_succeeded`, `login_failed`, as delivered. */
1378
+ interface AuthioWebhookLoginData {
1379
+ grant_type?: string | null;
1380
+ user_id?: string | null;
1381
+ username?: string | null;
1382
+ email?: string | null;
1383
+ ip_address?: string | null;
1384
+ user_agent?: string | null;
1385
+ session_id?: string | null;
1386
+ failure_reason?: string | null;
1387
+ resource?: string | null;
1388
+ scopes?: string[] | null;
1389
+ authentication_methods?: string[] | null;
1390
+ acr?: string | null;
1391
+ identity_provider?: string | null;
1392
+ consumer_id?: string | null;
1393
+ consumer_name?: string | null;
1394
+ }
1395
+ /** `user_locked_out`, as delivered. */
1396
+ interface AuthioWebhookUserLockedOutData {
1397
+ user_id: string;
1398
+ username?: string | null;
1399
+ email?: string | null;
1400
+ lockout_end?: string | null;
1401
+ access_failed_count: number;
1402
+ }
1403
+ /** `token_revoked`, as delivered. */
1404
+ interface AuthioWebhookTokenRevokedData {
1405
+ token_id?: string | null;
1406
+ subject?: string | null;
1407
+ session_id?: string | null;
1408
+ token_type_hint?: string | null;
1409
+ }
1410
+ /**
1411
+ * `keys_rotated`, as delivered: `rotation_days` and `automatic` on a scheduled rotation, `revoked_keys_count` on a
1412
+ * manual one.
1413
+ */
1414
+ interface AuthioWebhookKeysRotatedData {
1415
+ signing_key_id?: string | null;
1416
+ encryption_key_id?: string | null;
1417
+ revoked_keys_count?: number | null;
1418
+ rotation_days?: number | null;
1419
+ automatic?: boolean | null;
1420
+ }
1421
+ /** `token_reuse_detected`, as delivered. */
1422
+ interface AuthioWebhookTokenReuseDetectedData {
1423
+ token_id?: string | null;
1424
+ subject?: string | null;
1425
+ session_id?: string | null;
1426
+ ip_address?: string | null;
1427
+ user_agent?: string | null;
1428
+ }
1429
+ /** `admin_resource_created`, `admin_resource_updated`, `admin_resource_deleted`, as delivered. */
1430
+ interface AuthioWebhookAdminResourceData {
1431
+ action?: string | null;
1432
+ resource_type?: string | null;
1433
+ resource_id?: string | null;
1434
+ parent_id?: string | null;
1435
+ realm_id?: string | null;
1436
+ client_id?: string | null;
1437
+ /** `User` or `Credential`. */
1438
+ actor_type?: string | null;
1439
+ actor_user_id?: string | null;
1440
+ actor_username?: string | null;
1441
+ actor_email?: string | null;
1442
+ actor_credential_id?: string | null;
1443
+ actor_credential_name?: string | null;
1444
+ actor_platform_operator?: boolean | null;
1445
+ ip_address?: string | null;
1446
+ method?: string | null;
1447
+ path?: string | null;
1448
+ /** What changed, by resource type; kept as delivered. */
1449
+ details?: Record<string, unknown> | null;
1450
+ }
1451
+ /** `user_suspended`, `user_suspension_ended`, as delivered. */
1452
+ interface AuthioWebhookUserSuspensionData {
1453
+ id: string;
1454
+ user_id: string;
1455
+ level?: string | null;
1456
+ status?: string | null;
1457
+ starts_at?: string | null;
1458
+ ends_at?: string | null;
1459
+ restricted_scopes: string[];
1460
+ revokes_every_role: boolean;
1461
+ revoked_role_ids: string[];
1462
+ sessions_terminated_at?: string | null;
1463
+ lifted_at?: string | null;
1464
+ }
1465
+ /** `attack_detected`, as delivered: an attack on the realm and the measure Authio took. */
1466
+ interface AuthioWebhookAttackDetectedData {
1467
+ incident_id: string;
1468
+ /** Such as `credential_stuffing`. */
1469
+ kind?: string | null;
1470
+ severity?: string | null;
1471
+ /** Such as `source_blocked`. */
1472
+ measure?: string | null;
1473
+ ip_address?: string | null;
1474
+ country?: string | null;
1475
+ asn?: number | null;
1476
+ network_operator?: string | null;
1477
+ user_id?: string | null;
1478
+ started_at?: string | null;
1479
+ }
1480
+ /** `credential_compromised`, as delivered: a person's password was used by an attacker. */
1481
+ interface AuthioWebhookCredentialCompromisedData {
1482
+ incident_id: string;
1483
+ user_id?: string | null;
1484
+ username?: string | null;
1485
+ ip_address?: string | null;
1486
+ country?: string | null;
1487
+ asn?: number | null;
1488
+ network_operator?: string | null;
1489
+ password_change_required?: boolean | null;
1490
+ }
1491
+ /** `ping`, as delivered. */
1492
+ interface AuthioWebhookPingData {
1493
+ message?: string | null;
1494
+ subscription?: string | null;
1495
+ }
1496
+ /**
1497
+ * The data shape of each event type, as delivered (snake_case).
1498
+ */
1499
+ interface AuthioWebhookDataByType {
1500
+ user_created: AuthioWebhookUserData;
1501
+ user_updated: AuthioWebhookUserData;
1502
+ user_deleted: AuthioWebhookUserData;
1503
+ login_succeeded: AuthioWebhookLoginData;
1504
+ login_failed: AuthioWebhookLoginData;
1505
+ user_locked_out: AuthioWebhookUserLockedOutData;
1506
+ token_revoked: AuthioWebhookTokenRevokedData;
1507
+ keys_rotated: AuthioWebhookKeysRotatedData;
1508
+ token_reuse_detected: AuthioWebhookTokenReuseDetectedData;
1509
+ admin_resource_created: AuthioWebhookAdminResourceData;
1510
+ admin_resource_updated: AuthioWebhookAdminResourceData;
1511
+ admin_resource_deleted: AuthioWebhookAdminResourceData;
1512
+ user_suspended: AuthioWebhookUserSuspensionData;
1513
+ user_suspension_ended: AuthioWebhookUserSuspensionData;
1514
+ attack_detected: AuthioWebhookAttackDetectedData;
1515
+ credential_compromised: AuthioWebhookCredentialCompromisedData;
1516
+ ping: AuthioWebhookPingData;
1517
+ }
1518
+ /**
1519
+ * A snake_case name in camelCase.
1520
+ */
1521
+ type AuthioCamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Head}${Capitalize<AuthioCamelCase<Tail>>}` : S;
1522
+ /**
1523
+ * An object whose top-level member names are turned into camelCase, values unchanged.
1524
+ */
1525
+ type AuthioCamelCased<T> = {
1526
+ [K in keyof T as K extends string ? AuthioCamelCase<K> : K]: T[K];
1527
+ };
1528
+ /** The data of a user event, as the typed accessor exposes it. */
1529
+ type AuthioWebhookUser = AuthioCamelCased<AuthioWebhookUserData>;
1530
+ /** The data of a login event, as the typed accessor exposes it. */
1531
+ type AuthioWebhookLogin = AuthioCamelCased<AuthioWebhookLoginData>;
1532
+ /** The data of a lockout event, as the typed accessor exposes it. */
1533
+ type AuthioWebhookUserLockedOut = AuthioCamelCased<AuthioWebhookUserLockedOutData>;
1534
+ /** The data of a revocation event, as the typed accessor exposes it. */
1535
+ type AuthioWebhookTokenRevoked = AuthioCamelCased<AuthioWebhookTokenRevokedData>;
1536
+ /** The data of a key rotation event, as the typed accessor exposes it. */
1537
+ type AuthioWebhookKeysRotated = AuthioCamelCased<AuthioWebhookKeysRotatedData>;
1538
+ /** The data of a refresh token reuse event, as the typed accessor exposes it. */
1539
+ type AuthioWebhookTokenReuseDetected = AuthioCamelCased<AuthioWebhookTokenReuseDetectedData>;
1540
+ /** The data of an admin resource event, as the typed accessor exposes it. */
1541
+ type AuthioWebhookAdminResource = AuthioCamelCased<AuthioWebhookAdminResourceData>;
1542
+ /** The data of a suspension event, as the typed accessor exposes it. */
1543
+ type AuthioWebhookUserSuspension = AuthioCamelCased<AuthioWebhookUserSuspensionData>;
1544
+ /** The data of an attack event, as the typed accessor exposes it. */
1545
+ type AuthioWebhookAttackDetected = AuthioCamelCased<AuthioWebhookAttackDetectedData>;
1546
+ /** The data of a compromised credential event, as the typed accessor exposes it. */
1547
+ type AuthioWebhookCredentialCompromised = AuthioCamelCased<AuthioWebhookCredentialCompromisedData>;
1548
+ /** The data of a ping, as the typed accessor exposes it. */
1549
+ type AuthioWebhookPing = AuthioCamelCased<AuthioWebhookPingData>;
1550
+ /**
1551
+ * An event narrowed to one type, with its data typed as delivered.
1552
+ */
1553
+ type AuthioTypedWebhookEvent<T extends keyof AuthioWebhookDataByType> = AuthioWebhookEvent & {
1554
+ readonly type: T;
1555
+ readonly data: AuthioWebhookDataByType[T];
1556
+ };
1557
+ /**
1558
+ * Verifies the `X-Authio-Signature` header (`t={unixSeconds},v1={hex}`) against the raw body: HMAC-SHA256 of
1559
+ * `{t}.{body}` with the secret, compared in constant time, any matching `v1` accepted, the signature checked before
1560
+ * the timestamp.
1561
+ *
1562
+ * @param signatureHeader The header value.
1563
+ * @param rawBody The body exactly as received.
1564
+ * @param secret The webhook's secret.
1565
+ * @param options `tolerance` in seconds (default 300) and `now` in milliseconds (default the current time).
1566
+ */
1567
+ declare function verifyWebhookSignature(signatureHeader: string | null | undefined, rawBody: string | Uint8Array, secret: string, options?: {
1568
+ tolerance?: number;
1569
+ now?: number;
1570
+ }): Promise<AuthioWebhookVerificationResult>;
1571
+ /**
1572
+ * Computes the `X-Authio-Signature` value Authio would send, for tests and replays.
1573
+ *
1574
+ * @param timestamp Milliseconds since the epoch, or a date.
1575
+ */
1576
+ declare function computeWebhookSignatureHeader(rawBody: string | Uint8Array, secret: string, timestamp: number | Date): Promise<string>;
1577
+ /**
1578
+ * Parses a webhook body.
1579
+ *
1580
+ * @throws SyntaxError when it is not JSON or has no `type`.
1581
+ */
1582
+ declare function parseWebhookEvent(rawBody: string | Uint8Array): AuthioWebhookEvent;
1583
+ /**
1584
+ * Parses a webhook body, or returns `undefined` when it cannot be read.
1585
+ */
1586
+ declare function tryParseWebhookEvent(rawBody: string | Uint8Array | null | undefined): AuthioWebhookEvent | undefined;
1587
+ /**
1588
+ * Whether the event is of one of the given types, narrowing its data.
1589
+ */
1590
+ declare function isWebhookEventOfType<T extends keyof AuthioWebhookDataByType>(event: AuthioWebhookEvent, ...types: T[]): event is AuthioTypedWebhookEvent<T>;
1591
+ /** The data of a user event in camelCase, or `undefined` for any other type. */
1592
+ declare const asUserEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookUserData> | undefined;
1593
+ /** The data of a login event in camelCase, or `undefined` for any other type. */
1594
+ declare const asLoginEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookLoginData> | undefined;
1595
+ /** The data of a lockout event in camelCase, or `undefined` for any other type. */
1596
+ declare const asUserLockedOutEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookUserLockedOutData> | undefined;
1597
+ /** The data of a revocation event in camelCase, or `undefined` for any other type. */
1598
+ declare const asTokenRevokedEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookTokenRevokedData> | undefined;
1599
+ /** The data of a key rotation event in camelCase, or `undefined` for any other type. */
1600
+ declare const asKeysRotatedEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookKeysRotatedData> | undefined;
1601
+ /** The data of a refresh token reuse event in camelCase, or `undefined` for any other type. */
1602
+ declare const asTokenReuseDetectedEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookTokenReuseDetectedData> | undefined;
1603
+ /** The data of an admin resource event in camelCase, or `undefined` for any other type. */
1604
+ declare const asAdminResourceEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookAdminResourceData> | undefined;
1605
+ /** The data of a suspension event in camelCase, or `undefined` for any other type. */
1606
+ declare const asUserSuspensionEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookUserSuspensionData> | undefined;
1607
+ /** The data of an attack event in camelCase, or `undefined` for any other type. */
1608
+ declare const asAttackDetectedEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookAttackDetectedData> | undefined;
1609
+ /** The data of a compromised credential event in camelCase, or `undefined` for any other type. */
1610
+ declare const asCredentialCompromisedEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookCredentialCompromisedData> | undefined;
1611
+ /** The data of a ping in camelCase, or `undefined` for any other type. */
1612
+ declare const asPingEvent: (event: AuthioWebhookEvent) => AuthioCamelCased<AuthioWebhookPingData> | undefined;
1613
+ /**
1614
+ * Whether Authio documents the event type. An unknown type still parses; read its `data` as delivered.
1615
+ */
1616
+ declare function isKnownWebhookEventType(type: string): type is keyof AuthioWebhookDataByType;
1617
+ /**
1618
+ * The data of any known event in camelCase (what the typed accessor of its type returns), or `undefined` for an
1619
+ * unknown type.
1620
+ */
1621
+ declare function readWebhookEventData(event: AuthioWebhookEvent): Record<string, unknown> | undefined;
1622
+ /**
1623
+ * Turns the top-level member names of an object from snake_case into camelCase, leaving the values as they are.
1624
+ */
1625
+ declare function toCamelCasedMembers<T extends object>(value: T): AuthioCamelCased<T>;
1626
+
1627
+ export { type AuthioAccountCredential, type AuthioAccountCredentialKind, type AuthioAccountCredentialOptions, type AuthioAdminEnvelope, AuthioAdminError, type AuthioAdminFailure, type AuthioAdminNotification, type AuthioAdminSuccess, AuthioAsymmetricAlgorithms, type AuthioAuthorizationRequest, type AuthioAuthorizationResult, type AuthioAuthorizationTransaction, type AuthioAuthorizationUrl, type AuthioBearerChallenge, type AuthioCallOptions, AuthioCallbackError, type AuthioCallbackFailure, type AuthioCallerKind, AuthioCallerKinds, type AuthioCamelCase, type AuthioCamelCased, AuthioClaimTypes, type AuthioClient, AuthioClientAssertionAlgorithms, type AuthioClientAuthentication, type AuthioClientCredentialsCache, type AuthioClientCredentialsSettings, type AuthioClientCredentialsToken, type AuthioClientOptions, type AuthioClock, type AuthioCodeChallengeMethod, AuthioConfigurationError, type AuthioConnection, type AuthioConnectionChoice, type AuthioConnectionExchangeResult, type AuthioConnectionGranted, type AuthioConnectionOptions, type AuthioConnectionRefused, type AuthioConnectionRequired, type AuthioConnectionSelectionRequired, AuthioContentEncryptionAlgorithms, type AuthioCredentialForm, AuthioDefaults, type AuthioDeviceAuthorization, type AuthioDevicePollOutcome, type AuthioDiscoveryClient, type AuthioDiscoveryDocument, AuthioDiscoveryError, type AuthioEncryptionKey, type AuthioEncryptionKeySource, type AuthioEndSessionRequest, AuthioError, type AuthioErrorResponse, type AuthioExternalAccount, AuthioGrantTypes, type AuthioIdTokenClaims, type AuthioIntrospectionResult, type AuthioJwtExpectations, AuthioKeyManagementAlgorithms, AuthioLegacyKeyManagementAlgorithms, type AuthioLogoutToken, AuthioOAuthErrors, type AuthioPkcePair, type AuthioPrivateKeyInput, type AuthioPrompt, AuthioPrompts, AuthioProtocolError, AuthioResourceAccess, AuthioResourceAccessClaims, type AuthioResourceAccessRole, type AuthioResourceAccessSource, AuthioScopes, type AuthioSecretSource, type AuthioSigningKeys, type AuthioTokenClient, type AuthioTokenDecrypter, type AuthioTokenDecrypterOptions, type AuthioTokenFailure, type AuthioTokenResponse, AuthioTokenTypes, AuthioTokenValidationError, type AuthioTypedWebhookEvent, type AuthioUserInfo, type AuthioWebhookAdminResource, type AuthioWebhookAdminResourceData, type AuthioWebhookAttackDetected, type AuthioWebhookAttackDetectedData, type AuthioWebhookCredentialCompromised, type AuthioWebhookCredentialCompromisedData, type AuthioWebhookDataByType, type AuthioWebhookEvent, AuthioWebhookEventTypes, AuthioWebhookHeaders, type AuthioWebhookKeysRotated, type AuthioWebhookKeysRotatedData, type AuthioWebhookLogin, type AuthioWebhookLoginData, type AuthioWebhookPing, type AuthioWebhookPingData, type AuthioWebhookTokenReuseDetected, type AuthioWebhookTokenReuseDetectedData, type AuthioWebhookTokenRevoked, type AuthioWebhookTokenRevokedData, type AuthioWebhookUser, type AuthioWebhookUserData, type AuthioWebhookUserLockedOut, type AuthioWebhookUserLockedOutData, type AuthioWebhookUserSuspension, type AuthioWebhookUserSuspensionData, type AuthioWebhookVerificationFailure, type AuthioWebhookVerificationResult, asAdminResourceEvent, asAttackDetectedEvent, asCredentialCompromisedEvent, asKeysRotatedEvent, asLoginEvent, asPingEvent, asTokenReuseDetectedEvent, asTokenRevokedEvent, asUserEvent, asUserLockedOutEvent, asUserSuspensionEvent, computeAuthioTokenHash, computeWebhookSignatureHeader, createAuthioAccountCredential, createAuthioClient, createAuthioDiscoveryClient, createAuthioPkce, createAuthioSigningKeys, createAuthioTokenDecrypter, encryptionKeyFromFile, escapeDataString, isAllowedUrl, isAuthioTokenEncrypted, isKnownWebhookEventType, isWebhookEventOfType, parseAuthioAdminEnvelope, parseAuthioBearerChallenge, parseResourceAccess, parseResourceAccessClaim, parseWebhookEvent, randomValue, readAuthioAdminResponse, readWebhookEventData, resolveConnection, resolveIssuer, resourceAccessSourceOf, seconds, systemClock, toBasicAuthorization, toCamelCasedMembers, toClientCredentialsToken, toConnectionExchangeResult, toCredentialClientId, toDevicePollOutcome, toScopeString, toTokenValidationError, tryParseWebhookEvent, verifyAuthioJwt, verifyWebhookSignature };