@okeav/idp-pg 0.0.0-stage → 0.1.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.
Files changed (111) hide show
  1. package/.env.example +159 -0
  2. package/CHANGELOG.md +58 -0
  3. package/LICENSE +21 -0
  4. package/README.md +275 -3
  5. package/package.json +78 -6
  6. package/src/cache/cache-adapter.js +22 -0
  7. package/src/cache/index.js +68 -0
  8. package/src/cache/memory.adapter.js +85 -0
  9. package/src/cache/redis.adapter.js +96 -0
  10. package/src/config/console-logger.js +10 -0
  11. package/src/config/constants.js +178 -0
  12. package/src/config/defaults.js +100 -0
  13. package/src/config/from-env.js +150 -0
  14. package/src/config/init.js +286 -0
  15. package/src/config/state.js +22 -0
  16. package/src/errors/error-codes.js +97 -0
  17. package/src/errors/idp-error.js +75 -0
  18. package/src/hooks/index.js +85 -0
  19. package/src/index.js +167 -0
  20. package/src/magic-link/controller.js +129 -0
  21. package/src/magic-link/schemas.js +12 -0
  22. package/src/mfa/attempt-guard.js +48 -0
  23. package/src/mfa/controller.js +309 -0
  24. package/src/mfa/factor-store.js +37 -0
  25. package/src/mfa/memory-attempt-counter.js +58 -0
  26. package/src/mfa/schemas.js +11 -0
  27. package/src/mfa/secret-cipher.js +133 -0
  28. package/src/mfa/secrets.js +156 -0
  29. package/src/middleware/auth-context.middleware.js +149 -0
  30. package/src/middleware/cookie-parser.js +4 -0
  31. package/src/middleware/csrf.js +48 -0
  32. package/src/middleware/require-recent-auth.middleware.js +30 -0
  33. package/src/middleware/require-service-caller.middleware.js +32 -0
  34. package/src/middleware/service-context.middleware.js +70 -0
  35. package/src/middleware/validate-body.js +16 -0
  36. package/src/middleware/validate-query.js +22 -0
  37. package/src/oauth2/authorize.controller.js +233 -0
  38. package/src/oauth2/client-auth.js +77 -0
  39. package/src/oauth2/client.controller.js +122 -0
  40. package/src/oauth2/consent.controller.js +63 -0
  41. package/src/oauth2/login-challenge.js +50 -0
  42. package/src/oauth2/redirect-uri.js +25 -0
  43. package/src/oauth2/schemas.js +103 -0
  44. package/src/oauth2/token.controller.js +370 -0
  45. package/src/oidc/discovery.controller.js +36 -0
  46. package/src/oidc/end-session.controller.js +137 -0
  47. package/src/oidc/userinfo.controller.js +49 -0
  48. package/src/password-auth/controllers.js +927 -0
  49. package/src/password-auth/schemas.js +76 -0
  50. package/src/rate-limit/enforce.js +35 -0
  51. package/src/rate-limit/index.js +48 -0
  52. package/src/rate-limit/keys.js +36 -0
  53. package/src/rate-limit/memory.adapter.js +75 -0
  54. package/src/rate-limit/noop.adapter.js +14 -0
  55. package/src/rate-limit/rate-limiter.js +18 -0
  56. package/src/rate-limit/redis.adapter.js +71 -0
  57. package/src/routes/build-router.js +238 -0
  58. package/src/security/attempt-budget.js +47 -0
  59. package/src/security/clock-skew.js +63 -0
  60. package/src/service-mesh/key-status.js +22 -0
  61. package/src/service-mesh/local-key-lookup.js +12 -0
  62. package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
  63. package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
  64. package/src/service-mesh/service-identity.client.js +89 -0
  65. package/src/service-mesh/service-key.controller.js +170 -0
  66. package/src/service-mesh/verify-service-token.js +75 -0
  67. package/src/signing/jwks.controller.js +30 -0
  68. package/src/signing/jwks.js +24 -0
  69. package/src/signing/key-registry.js +97 -0
  70. package/src/signing/token.service.js +336 -0
  71. package/src/sso/binding.js +30 -0
  72. package/src/sso/callback.controller.js +186 -0
  73. package/src/sso/initiate.controller.js +92 -0
  74. package/src/sso/providers.js +237 -0
  75. package/src/sso/schemas.js +7 -0
  76. package/src/storage/interfaces.js +178 -0
  77. package/src/storage/postgres/db.js +68 -0
  78. package/src/storage/postgres/index.js +160 -0
  79. package/src/storage/postgres/migrations/run-migrations.js +122 -0
  80. package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
  81. package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
  82. package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
  83. package/src/storage/postgres/repositories/consent.repository.js +68 -0
  84. package/src/storage/postgres/repositories/credential.repository.js +75 -0
  85. package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
  86. package/src/storage/postgres/repositories/service-key.repository.js +76 -0
  87. package/src/storage/postgres/repositories/session.repository.js +290 -0
  88. package/src/storage/postgres/repositories/user.repository.js +328 -0
  89. package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
  90. package/src/storage/postgres/run.js +22 -0
  91. package/src/utils/account-status.js +26 -0
  92. package/src/utils/cookies.js +129 -0
  93. package/src/utils/device-fingerprint.js +58 -0
  94. package/src/utils/email-hash.js +23 -0
  95. package/src/utils/oauth-client-credentials.js +51 -0
  96. package/src/utils/password.js +40 -0
  97. package/src/utils/safe-equal.js +12 -0
  98. package/src/utils/session-family.js +158 -0
  99. package/src/utils/session-kind.js +15 -0
  100. package/src/utils/url.js +17 -0
  101. package/src/webauthn/authentication.controller.js +126 -0
  102. package/src/webauthn/challenge-store.js +17 -0
  103. package/src/webauthn/config.js +25 -0
  104. package/src/webauthn/mfa.controller.js +119 -0
  105. package/src/webauthn/registration.controller.js +128 -0
  106. package/src/webauthn/schemas.js +41 -0
  107. package/src/webauthn/shared.js +63 -0
  108. package/src/webhooks/dispatcher.js +135 -0
  109. package/src/webhooks/sign.js +55 -0
  110. package/src/webhooks/wrap-hooks.js +51 -0
  111. package/types/index.d.ts +777 -0
@@ -0,0 +1,777 @@
1
+ import type { Request, Response, NextFunction, RequestHandler, ErrorRequestHandler, Router } from 'express';
2
+
3
+ // ── Config ─────────────────────────────────────────────────────────────────
4
+
5
+ export interface SigningKeyEntry {
6
+ /** Raw PEM or base64-encoded PEM. Omit on a key you only want to verify with (e.g. a RETIRED key kept for old tokens). */
7
+ privateKey?: string;
8
+ publicKey: string;
9
+ status: 'ACTIVE' | 'ROTATING' | 'RETIRED' | 'REVOKED';
10
+ }
11
+
12
+ export interface StorageContract {
13
+ /** The pg.Pool the store queries through. */
14
+ pool: import('pg').Pool;
15
+ close(): Promise<void>;
16
+ /** The database server's clock (the clock-skew guard's reference). */
17
+ databaseTime(): Promise<{ time: Date }>;
18
+ /** Deletes every expired row now (also run every `postgres.pruneIntervalSeconds`). Resolves the count per repository. */
19
+ pruneExpired(): Promise<Record<string, number>>;
20
+ userRepository: unknown;
21
+ sessionRepository: unknown;
22
+ authorizationCodeRepository: unknown;
23
+ consentRepository: unknown;
24
+ oauthClientRepository: unknown;
25
+ verificationTokenRepository: unknown;
26
+ serviceKeyRepository: unknown;
27
+ credentialRepository: unknown;
28
+ attemptCounterRepository: AttemptCounterRepository;
29
+ // Loosely typed for now — the per-repository semantics are documented as JSDoc in
30
+ // src/storage/interfaces.js and implemented in src/storage/postgres/repositories.
31
+ }
32
+
33
+ export interface PostgresConfig {
34
+ /** e.g. postgres://user:pass@host:5432/idp?sslmode=verify-full — or pass `pool`. */
35
+ connectionString?: string;
36
+ /** A pg.Pool of yours (not ended by `storage.close()`). Instead of connectionString / poolConfig. */
37
+ pool?: import('pg').Pool;
38
+ /** Extra pg.Pool options (max, ssl, statement_timeout, idleTimeoutMillis …). */
39
+ poolConfig?: import('pg').PoolConfig;
40
+ /**
41
+ * 'verify' (default): refuse to start unless every migration of this version is applied, unchanged.
42
+ * 'apply': apply pending migrations first (advisory-locked, safe from several instances). 'skip'.
43
+ */
44
+ migrations?: 'verify' | 'apply' | 'skip';
45
+ /** Delete expired rows this often (default 3600; >= 60); 0 = off — then call `storage.pruneExpired()` yourself. */
46
+ pruneIntervalSeconds?: number;
47
+ }
48
+
49
+ /**
50
+ * Optional storage repository behind the attempt budgets (`mfa:<userId>`,
51
+ * `password-login:<userId>`, `email-verification:<email hash>`,
52
+ * `password-change:<userId>`, spent MFA challenges): atomic fixed-window
53
+ * failure counters with a lock, shared by every app instance.
54
+ * See src/storage/interfaces.js for the exact semantics `recordFailure` must have.
55
+ */
56
+ export interface AttemptCounterRepository {
57
+ get(key: string): Promise<{ count: number; windowExpiresAt: Date; lockedUntil: Date | null } | null>;
58
+ recordFailure(key: string, opts: { max: number; windowSeconds: number; lockSeconds: number }): Promise<{ count: number; windowExpiresAt: Date; lockedUntil: Date | null }>;
59
+ reset(key: string): Promise<void>;
60
+ pruneExpired?(): Promise<{ deletedCount: number }>;
61
+ }
62
+
63
+ /**
64
+ * At-rest encryption for TOTP secrets — plug in a KMS/HSM via
65
+ * `config.mfa.secretCipher`. `encrypt`'s output is stored verbatim and must
66
+ * not be a bare base32 string (that shape marks a legacy plain-text secret);
67
+ * a prefix such as `kms:` is enough. `context` is the owning user's id —
68
+ * bind it to the ciphertext so a value copied onto another user fails.
69
+ */
70
+ export interface SecretCipher {
71
+ encrypt(plaintext: string, opts: { context: string }): string | Promise<string>;
72
+ decrypt(ciphertext: string, opts: { context: string }): string | Promise<string>;
73
+ /** True when `ciphertext` was written under a non-current key; it is then re-encrypted on the next successful verify. */
74
+ needsRotation?(ciphertext: string): boolean;
75
+ }
76
+
77
+ /** A 32-byte key, base64. A bare string's id is a fingerprint of the key; `{ id, key }` names it explicitly. */
78
+ export type MfaEncryptionKey = string | { id: string; key: string };
79
+
80
+ export interface IdpConfig {
81
+ /** https URL (plain http only for localhost / 127.0.0.1 / [::1], or with NODE_ENV=development) — checked at startup. */
82
+ issuer: string;
83
+ /** The PostgreSQL database (PostgreSQL 14 or later). */
84
+ postgres: PostgresConfig;
85
+ cache?: {
86
+ adapter?: 'memory' | 'redis';
87
+ keyPrefix?: string;
88
+ redis?: { host: string; port: number; username?: string; password?: string; db?: number; tls?: boolean | Record<string, unknown>; keepAliveMs?: number };
89
+ };
90
+ signingKeys: { keys: Record<string, SigningKeyEntry> };
91
+ cookies?: {
92
+ /**
93
+ * Default: NODE_ENV !== 'development'. Secure session cookies are named `__Host-access_token` /
94
+ * `__Host-refresh_token` (or `__Secure-…` with `domain`); without Secure, plain `access_token` /
95
+ * `refresh_token`.
96
+ */
97
+ secure?: boolean;
98
+ /** Default 'lax' (case-insensitive). 'none' requires secure cookies (checked at startup). */
99
+ sameSite?: 'lax' | 'strict' | 'none';
100
+ /**
101
+ * Share the session cookies with subdomains. Rules out the `__Host-` prefix: the cookies become
102
+ * `__Secure-…`, and a request carrying one twice is refused (400 COOKIE_CONFLICT).
103
+ */
104
+ domain?: string;
105
+ /**
106
+ * Exact origins (e.g. `https://app.example.com` — no path, no trailing slash; checked at startup)
107
+ * of your frontends that make cookie-authenticated requests. A cookie-authenticated
108
+ * POST/PUT/PATCH/DELETE from any other origin is refused (403 CSRF_ORIGIN_REJECTED), as is any
109
+ * browser request to an endpoint that sets or clears session cookies. The issuer's origin is
110
+ * always trusted; Bearer-authenticated requests are unaffected.
111
+ */
112
+ trustedOrigins?: string[];
113
+ /**
114
+ * Whether login/refresh JSON bodies also carry the refresh token. Default `'auto'`: only for
115
+ * non-browser clients — a browser request (it sends `Origin` or `Sec-Fetch-Site`) gets it in its
116
+ * httpOnly cookie only. `true`: always (a browser app that keeps the token itself). `false`: never.
117
+ */
118
+ refreshTokenInBody?: boolean | 'auto';
119
+ /**
120
+ * The path the refresh-token cookie is scoped to. Default: `<router mount path>/session`, taken from
121
+ * the request. Set it (e.g. `/auth/session`) to pin it when the mount path can vary in spelling.
122
+ */
123
+ sessionPath?: string;
124
+ };
125
+ registration?: {
126
+ /** Persist the user-supplied `metadata` from POST /register. Default false — it is attacker-controlled. */
127
+ acceptMetadata?: boolean;
128
+ };
129
+ session?: {
130
+ /**
131
+ * Default true (since 0.4.0): `POST /refresh` re-invokes `hooks.resolveAuthContext`, so a
132
+ * role/capability change (a demotion, a suspension in your app) takes effect at the next
133
+ * access-token rotation. Set false to carry the login-time `claims` forward verbatim — they
134
+ * then stay frozen for the whole session family (up to `absoluteLifetimeSeconds`).
135
+ */
136
+ reresolveClaimsOnRefresh?: boolean;
137
+ /**
138
+ * Default true (since 0.3.0): `authContextMiddleware` looks up the
139
+ * access token's session row (by `jti`) on every request and refuses
140
+ * the token if the row is missing, revoked or expired — so logout-all,
141
+ * password reset/change and session revocation take effect on every
142
+ * instance immediately. Costs one indexed storage read per
143
+ * authenticated request. Set false to fall back to the per-process
144
+ * revocation cache only: logout-all and password reset/change then
145
+ * don't revoke access tokens at all until they expire, and a single
146
+ * logout/revocation only takes effect on the instance that handled it.
147
+ */
148
+ verifyOnEachRequest?: boolean;
149
+ /** How recent (seconds) a login must be for `requireRecentAuth` — passkey/MFA enrolment, passkey and account deletion. Default 900. */
150
+ recentAuthMaxAgeSeconds?: number;
151
+ /** A login's refresh-token family ends after this however actively it is refreshed. Default 90 days. */
152
+ absoluteLifetimeSeconds?: number;
153
+ /** A rotated refresh token replayed within this many seconds is only refused; later, it revokes its whole family. Default 10. */
154
+ refreshReuseGraceSeconds?: number;
155
+ };
156
+ /** Seconds; each must be a positive integer (checked at startup). */
157
+ ttls?: Partial<{
158
+ accessToken: number; idToken: number; refreshToken: number; internalToken: number;
159
+ authCode: number; revocationCache: number; refreshTokenCache: number;
160
+ passwordReset: number; emailVerification: number; magicLink: number; mfaChallenge: number;
161
+ ssoState: number; ssoExchange: number; discoveryCache: number; webauthnChallenge: number;
162
+ }>;
163
+ security: {
164
+ /** Random, at least 32 characters (checked at startup). Never rotate — it keys the email lookup index. */
165
+ emailHashPepper: string;
166
+ /**
167
+ * Random, at least 32 characters, different from `emailHashPepper` (checked at startup). Every stored
168
+ * token/code/link/recovery-code hash and HMAC-stored client secret is keyed by a key derived from it
169
+ * per purpose. To rotate it, move the old value to `previousTokenHashSecrets`.
170
+ */
171
+ tokenHashSecret: string;
172
+ /**
173
+ * Earlier `tokenHashSecret` values, newest first (each at least 32 characters). What was hashed under
174
+ * them still verifies; new hashes always use `tokenHashSecret`. Drop one once everything hashed under
175
+ * it has expired or been replaced (see docs/api/bootstrap-config.md). Default [].
176
+ */
177
+ previousTokenHashSecrets?: string[];
178
+ /** Wrong passwords per `accountLockDurationMs` window before password login (only) is locked — active accounts with a password only. Default 5. */
179
+ maxFailedLoginAttempts?: number;
180
+ /** The counting window and the password-login lock's length, in ms. Default 1_800_000 (30 min). */
181
+ accountLockDurationMs?: number;
182
+ /** Integer 10-15 (default 12). */
183
+ bcryptRounds?: number;
184
+ /** Tests only: allow bcryptRounds down to 4. */
185
+ allowWeakBcryptRounds?: boolean;
186
+ /**
187
+ * Wrong 6-digit email-verification codes (the link has no budget): `maxFailedAttempts` per
188
+ * verification ticket and per address without one, each over at least the code's lifetime (window
189
+ * and lock are raised to `ttls.emailVerification`), and `maxTotalFailedAttempts` per address in all
190
+ * (a year-long cap) — then only the link works. Defaults: 5, 24h, 24h, 20.
191
+ */
192
+ verificationCodeLockout?: { maxFailedAttempts?: number; windowSeconds?: number; lockSeconds?: number; maxTotalFailedAttempts?: number };
193
+ /** Per-account limit on wrong current passwords at /password/change. Defaults: 5 in 3600s, locked 3600s. */
194
+ passwordChangeLockout?: { maxFailedAttempts?: number; windowSeconds?: number; lockSeconds?: number };
195
+ };
196
+ mfa?: {
197
+ issuerLabel?: string;
198
+ recoveryCodeCount?: number;
199
+ /** Default true. When true, startup requires `encryptionKey` or `secretCipher` (unless `allowPlaintext`). Set false if you don't use TOTP MFA. */
200
+ enabled?: boolean;
201
+ /** Current AES-256-GCM key for TOTP secrets at rest. */
202
+ encryptionKey?: MfaEncryptionKey;
203
+ /** Retired keys still accepted for decryption during a rotation. */
204
+ previousEncryptionKeys?: MfaEncryptionKey[];
205
+ /** Custom cipher (e.g. KMS) — takes precedence over `encryptionKey`. */
206
+ secretCipher?: SecretCipher;
207
+ /**
208
+ * Refuse plain-text secrets (left over from ≤0.2.x, or written straight into the database).
209
+ * Default: true whenever `encryptionKey` or `secretCipher` is set — run `migrateMfaSecrets()` to
210
+ * encrypt old ones, or set false to keep reading them during a migration.
211
+ */
212
+ requireEncrypted?: boolean;
213
+ /** Development only: allow MFA with no key, storing secrets in plain text (logs a loud warning). */
214
+ allowPlaintext?: boolean;
215
+ /** Per-account second-factor lockout. Defaults: 5 failures in 900s lock for 900s. */
216
+ lockout?: { maxFailedAttempts?: number; windowSeconds?: number; lockSeconds?: number };
217
+ };
218
+ magicLink?: { allowSignupViaMagicLink?: boolean };
219
+ /**
220
+ * Fully opt-in — omit entirely to leave WebAuthn/passkey routes disabled.
221
+ * Validated lazily on first WebAuthn handler call, not at
222
+ * `initIdentityProvider()` startup. `rpID` must be the *frontend's*
223
+ * registrable domain, not necessarily this API's own host.
224
+ */
225
+ webauthn?: {
226
+ rpID?: string; rpName?: string; origin?: string | string[];
227
+ /**
228
+ * Default false: passkey-login options ignore `email` and always ask for a discoverable credential, because
229
+ * listing an address's credential ids reveals whether it has an account. Set true only if you rely on
230
+ * non-discoverable credentials (unknown addresses then get a stable decoy id).
231
+ */
232
+ allowCredentialsByEmail?: boolean;
233
+ };
234
+ oauthProviders?: {
235
+ google?: { clientId: string; clientSecret: string };
236
+ github?: { clientId: string; clientSecret: string };
237
+ /**
238
+ * `tenant` defaults to `'common'`. With a multi-tenant authority (`common`, `organizations`,
239
+ * `consumers`) the account's email is NOT trusted — any tenant admin can set it — so a
240
+ * Microsoft identity can't create or link an account by email. Pin `tenant` to your own
241
+ * tenant, or set `trustEmail: true` only if you accept that risk.
242
+ */
243
+ microsoft?: { clientId: string; clientSecret: string; tenant?: string; trustEmail?: boolean };
244
+ apple?: { clientId: string; teamId: string; keyId: string; privateKeyPem: string };
245
+ linkedin?: { clientId: string; clientSecret: string };
246
+ };
247
+ oauth2?: {
248
+ /**
249
+ * Which clients must use PKCE (S256) at /oauth2/authorize. `'all'` (default) — every client, the
250
+ * RFC 9700 recommendation (a confidential client without PKCE is open to code injection);
251
+ * `'public'` — public clients only (always required for them).
252
+ */
253
+ requirePkce?: 'all' | 'public';
254
+ };
255
+ oidc?: {
256
+ /**
257
+ * The IdP page that asks "sign out?" for RP-initiated logout. When set, `GET /session/end` without
258
+ * a matching `id_token_hint` redirects there with its query parameters; the page POSTs them back to
259
+ * `/session/end`. https (http only for localhost), on the issuer's origin or a `cookies.trustedOrigins`
260
+ * origin (checked at startup). Unset: that GET answers `{ action: 'logout_confirmation_required' }`.
261
+ */
262
+ endSessionConfirmationUrl?: string;
263
+ };
264
+ /**
265
+ * Bounds on this server's clock vs the database's (token, code and lockout lifetimes use the local
266
+ * clock). Measured at startup — which fails past `maxSkewSeconds` — and every `checkIntervalSeconds`.
267
+ */
268
+ clock?: {
269
+ /** Default 30. */
270
+ maxSkewSeconds?: number;
271
+ /** Default 2: a warning is logged past it. */
272
+ warnSkewSeconds?: number;
273
+ /** Default 600 (minimum 10). */
274
+ checkIntervalSeconds?: number;
275
+ };
276
+ /** Required (startup fails otherwise) as soon as any `oauthProviders` entry has a `clientId`. */
277
+ sso?: {
278
+ /** Absolute base URL providers redirect back to (`<base>/sso/<provider>/callback`). https (http only for localhost, or with NODE_ENV=development). */
279
+ baseCallbackUrl?: string;
280
+ /** Origins (scheme://host[:port]) SSO may send the browser back to. https, or http only for localhost. */
281
+ allowedRedirectOrigins?: string[];
282
+ /** Timeout for each call to a provider (token exchange, userinfo). Default 10000. */
283
+ providerTimeoutMs?: number;
284
+ };
285
+ serviceMesh?: {
286
+ /** One registration credential per service (preferred): `{ billing: '<secret>', ... }`. Proves which service registers, and lets it rotate its key. Each ≥ 32 characters and different from `bootstrapSecret`. */
287
+ bootstrapSecrets?: Record<string, string>;
288
+ /** Legacy shared registration secret (≥ 32 characters): can register a NEW name only (never one listed in bootstrapSecrets), never replace an existing service's key. */
289
+ bootstrapSecret?: string;
290
+ /** Names allowed to register at all. */
291
+ allowedServiceNames?: string[];
292
+ /** Default 'token'. 'secret'/'both' accept the shared secret with an unverified x-service-name. */
293
+ tokenMode?: 'token' | 'secret' | 'both';
294
+ ownServiceName?: string;
295
+ /** ≥ 32 characters. */
296
+ sharedSecret?: string;
297
+ /** Let requireServiceCallerMiddleware accept shared-secret callers (their name is unverified). Default false. */
298
+ allowLegacySecretCallers?: boolean;
299
+ /** How long a rotated-away (ROTATING) service key still verifies, in seconds. Default 3600. */
300
+ rotationGraceSeconds?: number;
301
+ };
302
+ rateLimiting?: {
303
+ /** Set false to disable entirely — e.g. you already rate-limit at a gateway/CDN layer. Default true. */
304
+ enabled?: boolean;
305
+ adapter?: 'memory' | 'redis';
306
+ keyPrefix?: string;
307
+ /** Only read if adapter === 'redis'; omit to reuse cache.adapter's Redis connection when that's also 'redis'. */
308
+ redis?: { host: string; port: number; username?: string; password?: string; db?: number; tls?: boolean | Record<string, unknown> };
309
+ login?: RateLimitRule;
310
+ loginByEmail?: RateLimitRule;
311
+ passwordReset?: RateLimitRule;
312
+ /** Password-reset requests per address. Default 3/hour. */
313
+ passwordResetByEmail?: RateLimitRule;
314
+ mfaChallenge?: RateLimitRule;
315
+ refreshToken?: RateLimitRule;
316
+ magicLink?: RateLimitRule;
317
+ /** Magic-link requests per address. Default 3/hour. */
318
+ magicLinkByEmail?: RateLimitRule;
319
+ /** POST /register and /register/resend-verification, per IP. Default 10/hour. */
320
+ register?: RateLimitRule;
321
+ /** POST /register/verify-email, per IP. Default 20/15min. */
322
+ emailVerification?: RateLimitRule;
323
+ /** Verification emails sent to one address (register, re-register, resend). Default 3/hour. */
324
+ verificationEmailByEmail?: RateLimitRule;
325
+ /** POST /webauthn/authentication/options and /verify (unauthenticated passkey login), per IP. Default 60/5min. */
326
+ webauthnAuthentication?: RateLimitRule;
327
+ /** /oauth2/token, /oauth2/token/revoke and /oauth2/token/introspect, per IP. Default 120/min. */
328
+ oauth2Token?: RateLimitRule;
329
+ /** GET /sso/:provider, per IP. Default 30/5min. */
330
+ ssoInitiate?: RateLimitRule;
331
+ /** POST /internal/service-keys (bootstrap-secret guesses), per IP. Default 20/15min. */
332
+ serviceKeyRegistration?: RateLimitRule;
333
+ };
334
+ /**
335
+ * Outbound webhook delivery — additive to `hooks` (in-process callbacks),
336
+ * never a replacement. Every `onAuditLog`/named hook event also gets
337
+ * POSTed, signed, to each configured endpoint. Omit or leave `endpoints`
338
+ * empty to disable entirely (the default) — delivery failures, including
339
+ * after exhausting retries, are only ever logged and never affect the
340
+ * underlying auth operation.
341
+ */
342
+ webhooks?: {
343
+ endpoints?: WebhookEndpoint[];
344
+ maxAttempts?: number;
345
+ retryBaseDelayMs?: number;
346
+ timeoutMs?: number;
347
+ /** Deliveries (with retries) in flight at once; beyond this, events are dropped with a warning. Default 100. */
348
+ maxInFlight?: number;
349
+ };
350
+ hooks?: AuthHooks;
351
+ /** How long a hook is awaited before the request carries on without it (it keeps running). Default 10000. */
352
+ hookTimeoutMs?: number;
353
+ logger?: Logger;
354
+ }
355
+
356
+ export interface Logger {
357
+ info(obj: unknown, msg?: string): void;
358
+ warn(obj: unknown, msg?: string): void;
359
+ error(obj: unknown, msg?: string): void;
360
+ debug(obj: unknown, msg?: string): void;
361
+ }
362
+
363
+ // ── Hooks ──────────────────────────────────────────────────────────────────
364
+
365
+ export interface AuditLogEvent {
366
+ action: string;
367
+ [key: string]: unknown;
368
+ timestamp: string;
369
+ }
370
+
371
+ export interface AuthHooks {
372
+ onAuditLog?(event: AuditLogEvent): void | Promise<void>;
373
+ onVerificationEmailRequested?(payload: { email: string; firstName?: string; lastName?: string; verificationToken: string; verificationCode: string | null }): void | Promise<void>;
374
+ onPasswordResetRequested?(payload: { email: string; resetToken: string; firstName?: string; lastName?: string }): void | Promise<void>;
375
+ onPasswordChanged?(payload: { userId: string; email: string; firstName: string; lastName: string; locale: string; when: string; deviceInfo: string; ipAddress: string }): void | Promise<void>;
376
+ onSuspiciousActivityDetected?(payload: { userId: string; email: string; firstName: string; lastName: string; locale: string; when: string; failedAttempts: number; unlocksAt: string }): void | Promise<void>;
377
+ onNewDeviceLogin?(payload: { userId: string; email: string; firstName: string; lastName: string; locale: string; when: string; deviceInfo: string; ipAddress: string }): void | Promise<void>;
378
+ onMagicLinkRequested?(payload: { email: string; magicLinkToken: string; firstName?: string; lastName?: string; isNewUser: boolean }): void | Promise<void>;
379
+ /**
380
+ * Called synchronously during login (password/MFA/SSO) to resolve the
381
+ * opaque `claims` bag embedded in the issued access token. Defaults to
382
+ * `() => ({})` if not supplied — the package never validates or
383
+ * interprets whatever you return here (role/scopes/capabilities/tenant
384
+ * id/anything is entirely up to you).
385
+ */
386
+ resolveAuthContext?(user: IdentityUser, ctx: { isNewUser: boolean; isNewLink?: boolean; method?: string; provider?: string; extra?: Record<string, unknown> }): { claims: Record<string, unknown> } | Promise<{ claims: Record<string, unknown> }>;
387
+ }
388
+
389
+ // ── Domain shapes ────────────────────────────────────────────────────────
390
+
391
+ export interface IdentityUser {
392
+ id: string;
393
+ email: string;
394
+ status: 'ACTIVE' | 'DISABLED' | 'INVITED' | 'LOCKED' | 'PENDING_VERIFICATION' | 'SUSPENDED' | 'DELETED';
395
+ mfaEnabled: boolean;
396
+ profile: { firstName?: string; lastName?: string; displayName?: string; avatarUrl?: string; locale?: string; zoneinfo?: string };
397
+ metadata: Record<string, unknown>;
398
+ lastLoginAt?: Date;
399
+ createdAt: Date;
400
+ updatedAt: Date;
401
+ }
402
+
403
+ export interface IssuedToken {
404
+ token: string;
405
+ expiresAt: Date;
406
+ kid: string;
407
+ jti: string;
408
+ }
409
+
410
+ export interface AccessTokenClaims {
411
+ sub: string;
412
+ email?: string;
413
+ claims?: Record<string, unknown>;
414
+ type: 'access_token';
415
+ iss: string;
416
+ aud: string;
417
+ jti: string;
418
+ iat: number;
419
+ exp: number;
420
+ /** Present (true) on tokens with no session row behind them — see `issueAccessToken`. */
421
+ sessionless?: boolean;
422
+ /** OAuth2-issued tokens only: the client the token was issued to (also its `aud`). */
423
+ client_id?: string;
424
+ /** OAuth2-issued tokens only: space-separated granted scopes. */
425
+ scope?: string;
426
+ /** `'client_credentials'` on machine tokens (no user; `sub` is the client id). */
427
+ gty?: 'client_credentials';
428
+ }
429
+
430
+ /**
431
+ * Which party an access token was issued to. `authContextMiddleware` / `verifyAccessToken`
432
+ * accept only `'first-party'` unless told otherwise — a token this IdP issued to a third-party
433
+ * OAuth2 client is never a credential for the IdP's own routes.
434
+ */
435
+ export type AccessTokenKind = 'first-party' | 'oauth2-user' | 'oauth2-client';
436
+
437
+ export interface VerifyAccessTokenOptions {
438
+ issuer?: string;
439
+ /** The `aud` a first-party token must carry. Default: the issuer. */
440
+ audience?: string | string[];
441
+ /** Token kinds accepted. Default `['first-party']`. */
442
+ accept?: AccessTokenKind[];
443
+ }
444
+
445
+ // Express augmentation — `req.auth` / `req.serviceCaller` after the
446
+ // respective middleware runs; `req.validatedQuery` after validateQuery().
447
+ declare module 'express-serve-static-core' {
448
+ interface Request {
449
+ auth?: {
450
+ /** Undefined for `'oauth2-client'` (client_credentials) tokens — there is no user. */
451
+ userId?: string;
452
+ email?: string;
453
+ claims: Record<string, unknown>;
454
+ tokenKind: AccessTokenKind;
455
+ /** OAuth2 tokens only. */
456
+ clientId?: string;
457
+ /** OAuth2 tokens only: the granted scopes. */
458
+ scopes?: string[];
459
+ /** `authTime`: when the user last actually logged in (seconds), carried across refreshes; null if unknown. */
460
+ tokenMeta: { issuedAt: number; expiresAt: number; jti: string; authTime: number | null };
461
+ };
462
+ /** `scopes` are whatever the calling service put in its own token — not granted by anyone; never authorize on them alone. */
463
+ serviceCaller?: { name: string; scopes?: string[]; region?: string; source: 'token' | 'legacy-secret' };
464
+ validatedQuery?: Record<string, unknown>;
465
+ }
466
+ }
467
+
468
+ // ── Bootstrap ────────────────────────────────────────────────────────────
469
+
470
+ export function initIdentityProvider(config: IdpConfig): Promise<{ config: IdpConfig; logger: Logger; storage: StorageContract; cache: CacheAdapter }>;
471
+ export function configFromEnv(env?: NodeJS.ProcessEnv): IdpConfig;
472
+
473
+ /** Applies this version's schema migrations (advisory-locked). Resolves the migrations it applied. A pool passed in is left open. */
474
+ export function runMigrations(target: import('pg').Pool | import('pg').PoolConfig | string): Promise<string[]>;
475
+ /** The store `initIdentityProvider` uses — exposed for tooling (e.g. a maintenance job). */
476
+ export function createPostgresStorage(
477
+ options: PostgresConfig,
478
+ emailDeps: { hashEmail: (email: string) => string; normalizeEmail: (email: string) => string },
479
+ context?: { logger?: Logger },
480
+ ): Promise<StorageContract>;
481
+ export const MIN_POSTGRES_VERSION: number;
482
+ /** The advisory-lock key runMigrations holds (a bigint, as a string). */
483
+ export const MIGRATION_LOCK_KEY: string;
484
+
485
+ // ── Errors ───────────────────────────────────────────────────────────────
486
+
487
+ export class IdpError extends Error {
488
+ code: string;
489
+ httpStatus: number;
490
+ /** Mirrors httpStatus, for Express's default handler and similar conventions. */
491
+ status: number;
492
+ statusCode: number;
493
+ /** True below 500: the message is written for clients. */
494
+ expose: boolean;
495
+ cause?: unknown;
496
+ constructor(opts: { code: string; httpStatus?: number; message?: string; cause?: unknown });
497
+ }
498
+ export function isIdpError(err: unknown): err is IdpError;
499
+ /**
500
+ * Express error handler safe for the internet: IdpError < 500 → { error, message }; anything else → 500 { error } with no internals.
501
+ * 5xx errors are logged (path only) through `opts.logger`, or by default the logger given to `initIdentityProvider`.
502
+ */
503
+ export function idpErrorHandler(opts?: { logger?: Logger }): ErrorRequestHandler;
504
+ export const ERROR_CODES: Record<string, string>;
505
+
506
+ // ── Token issuance / verification ────────────────────────────────────────
507
+
508
+ /**
509
+ * Tokens minted through this export have no session row, so by default they
510
+ * carry `sessionless: true` and are exempt from `session.verifyOnEachRequest`.
511
+ * Pass `sessionless: false` only if you created a session row with this
512
+ * token's `jti` yourself.
513
+ */
514
+ export function issueAccessToken(input: { sub: string; email?: string; claims?: Record<string, unknown> }, opts?: { ttlSeconds?: number; audience?: string; sessionless?: boolean; authTime?: number }): Promise<IssuedToken>;
515
+ /**
516
+ * Verifies signature, issuer, expiry, type and audience/kind — NOT revocation. A resource server that
517
+ * must refuse revoked sessions (logout-all, password reset) should use `authContextMiddleware`, which
518
+ * also checks the session store (`session.verifyOnEachRequest`).
519
+ */
520
+ export function verifyAccessToken(token: string, opts?: VerifyAccessTokenOptions): Promise<AccessTokenClaims>;
521
+ /** `opts.scopes` decide which user claims are released (default: openid email profile); `opts.authTime` (seconds) becomes `auth_time`. */
522
+ export function issueIdToken(user: IdentityUser, audience: string, nonce?: string, opts?: { scopes?: string[]; authTime?: number; ttlSeconds?: number }): Promise<IssuedToken>;
523
+ export function issueOAuth2AccessToken(subject: { id: string }, client: { clientId: string; accessTokenTTL?: number }, scopes: string[], opts?: { sessionless?: boolean }): Promise<IssuedToken>;
524
+ export function issueMfaChallengeToken(subjectId: string): Promise<string>;
525
+ /** For health checks: this server's clock minus the database's (`level`: 'unknown' when the database's time couldn't be read). */
526
+ export function checkClockSkew(): Promise<{ skewMs: number | null; ok: boolean; level: 'ok' | 'warn' | 'error' | 'unknown' }>;
527
+ /** Checks signature, expiry, `type`, `iss` (the issuer) and `aud` (`<issuer>#mfa-challenge`). */
528
+ export function verifyMfaChallengeToken(token: string): { sub: string; type: 'mfa_challenge'; iss: string; aud: string; jti: string; iat: number; exp: number };
529
+ export function verifyIssuedToken(token: string, opts?: { issuer?: string }): Record<string, unknown> | null;
530
+
531
+ // ── JWKS / discovery ─────────────────────────────────────────────────────
532
+
533
+ export const jwksHandler: RequestHandler;
534
+ export const authPublicKeyHandler: RequestHandler;
535
+ export const openidConfigurationHandler: RequestHandler;
536
+
537
+ // ── Service mesh (S2S JWKS trust) ────────────────────────────────────────
538
+
539
+ export const registerServiceKeyHandler: RequestHandler;
540
+ export const getServicesJwksHandler: RequestHandler;
541
+ /** Revokes a service key (no longer published or accepted). Resolves whether a key was found. */
542
+ export function revokeServiceKey(kid: string): Promise<boolean>;
543
+ export const s2sBootstrapMiddleware: RequestHandler;
544
+ /** `idpBaseUrl` must be https (http only for localhost, or with NODE_ENV=development) — throws otherwise. */
545
+ export function initServiceIdentity(opts: { serviceName: string; privateKeyPem: string; region?: string; idpBaseUrl: string; bootstrapSecret: string }): Promise<{ kid: string }>;
546
+ export function mintServiceToken(targetService: string, opts?: { scopes?: string[] }): string;
547
+ export const issueServiceToken: typeof mintServiceToken;
548
+ export function getServiceIdentity(): { serviceName: string; kid: string; region: string };
549
+ /** `idpBaseUrl` (or the one from `initServiceIdentity`) must be https (http only for localhost, or with NODE_ENV=development). */
550
+ export function verifyServiceTokenRemote(token: string, opts: { expectedAud: string; expectedIss?: string; idpBaseUrl?: string }): Promise<Record<string, unknown>>;
551
+
552
+ // ── Middleware ───────────────────────────────────────────────────────────
553
+
554
+ export function authContextMiddleware(opts?: VerifyAccessTokenOptions & { optional?: boolean }): RequestHandler;
555
+ /** Step-up gate: 401 REAUTHENTICATION_REQUIRED unless the user logged in within `maxAgeSeconds` (default `session.recentAuthMaxAgeSeconds`). Mount after authContextMiddleware. */
556
+ export function requireRecentAuth(opts?: { maxAgeSeconds?: number }): RequestHandler;
557
+ export function serviceContextMiddleware(opts?: { ownServiceName?: string }): RequestHandler;
558
+ export function requireServiceCallerMiddleware(...allowedCallers: string[]): RequestHandler;
559
+ export function validateBody(schema: { parse: (input: unknown) => unknown }): RequestHandler;
560
+ export function validateQuery(schema: { parse: (input: unknown) => unknown }): RequestHandler;
561
+ export const cookieParser: (...args: unknown[]) => RequestHandler;
562
+
563
+ // ── Password / email identity flows ─────────────────────────────────────
564
+
565
+ export const registerHandler: RequestHandler;
566
+ export const verifyEmailHandler: RequestHandler;
567
+ export const resendVerificationEmailHandler: RequestHandler;
568
+ export const loginHandler: RequestHandler;
569
+ export const refreshTokenHandler: RequestHandler;
570
+ export const logoutHandler: RequestHandler;
571
+ export const logoutAllHandler: RequestHandler;
572
+ export const forgotPasswordHandler: RequestHandler;
573
+ export const resetPasswordHandler: RequestHandler;
574
+ export const changePasswordHandler: RequestHandler;
575
+ export const getMeHandler: RequestHandler;
576
+ export const updateMeHandler: RequestHandler;
577
+ export const deleteMeHandler: RequestHandler;
578
+ export const listSessionsHandler: RequestHandler;
579
+ export const revokeSessionHandler: RequestHandler;
580
+ export const revokeAllSessionsHandler: RequestHandler;
581
+
582
+ // ── MFA ──────────────────────────────────────────────────────────────────
583
+
584
+ export const getMfaStatusHandler: RequestHandler;
585
+ export const setupMfaHandler: RequestHandler;
586
+ export const confirmMfaHandler: RequestHandler;
587
+ export const disableMfaHandler: RequestHandler;
588
+ export const regenerateRecoveryCodesHandler: RequestHandler;
589
+ export const verifyMfaChallengeHandler: RequestHandler;
590
+
591
+ // ── OAuth2 authorization server + OIDC ───────────────────────────────────
592
+
593
+ export const registerOAuthClientHandler: RequestHandler;
594
+ export const getOAuthClientHandler: RequestHandler;
595
+ export const listOAuthClientsHandler: RequestHandler;
596
+ export const updateOAuthClientHandler: RequestHandler;
597
+ export const rotateOAuthClientSecretHandler: RequestHandler;
598
+ export const deactivateOAuthClientHandler: RequestHandler;
599
+ export const approveOAuthClientHandler: RequestHandler;
600
+ export const authorizeHandler: RequestHandler;
601
+ export const confirmConsentHandler: RequestHandler;
602
+ export const denyConsentHandler: RequestHandler;
603
+ export const tokenHandler: RequestHandler;
604
+ export const revokeTokenHandler: RequestHandler;
605
+ export const introspectTokenHandler: RequestHandler;
606
+ export const getConsentHandler: RequestHandler;
607
+ export const listConsentsHandler: RequestHandler;
608
+ export const revokeConsentHandler: RequestHandler;
609
+ export const userinfoHandler: RequestHandler;
610
+ export const endSessionHandler: RequestHandler;
611
+
612
+ // ── SSO ──────────────────────────────────────────────────────────────────
613
+
614
+ export const initiateSsoHandler: RequestHandler;
615
+ export const ssoCallbackHandler: RequestHandler;
616
+
617
+ // ── Magic link (passwordless email login) ────────────────────────────────
618
+
619
+ export const requestMagicLinkHandler: RequestHandler;
620
+ export const verifyMagicLinkHandler: RequestHandler;
621
+
622
+ // ── WebAuthn / passkeys ──────────────────────────────────────────────────
623
+ // Registration always requires an authenticated caller (adding a passkey to
624
+ // an existing account). Primary authentication requires no prior auth
625
+ // (passwordless login). The MFA variants complete the challenge
626
+ // `loginHandler` issued when `user.mfaEnabled`, as an alternative to
627
+ // `verifyMfaChallengeHandler` (TOTP) — both draw on the same stored
628
+ // credentials, but are distinct ceremonies scoped differently (usernameless/
629
+ // discoverable for primary login vs. scoped to one known user for MFA).
630
+
631
+ export const generateRegistrationOptionsHandler: RequestHandler;
632
+ export const verifyRegistrationHandler: RequestHandler;
633
+ /** GET /me/passkeys and DELETE /me/passkeys/:credentialId (owner-scoped). */
634
+ export const listPasskeysHandler: RequestHandler;
635
+ export const deletePasskeyHandler: RequestHandler;
636
+ export const generateAuthenticationOptionsHandler: RequestHandler;
637
+ export const verifyAuthenticationHandler: RequestHandler;
638
+ export const generateMfaWebauthnChallengeOptionsHandler: RequestHandler;
639
+ export const verifyMfaWebauthnChallengeHandler: RequestHandler;
640
+
641
+ // ── MFA secret encryption ────────────────────────────────────────────────
642
+
643
+ /** Built-in AES-256-GCM cipher. Stored format: `v1:<keyId>:<iv>:<ciphertext>:<tag>` (base64url parts). */
644
+ export class AesGcmSecretCipher implements SecretCipher {
645
+ constructor(opts: { currentKey: MfaEncryptionKey; previousKeys?: MfaEncryptionKey[] });
646
+ readonly currentKeyId: string;
647
+ encrypt(plaintext: string, opts?: { context?: string }): string;
648
+ decrypt(ciphertext: string, opts?: { context?: string }): string;
649
+ needsRotation(ciphertext: string): boolean;
650
+ }
651
+ /**
652
+ * Encrypts every plain-text `mfaSecret`/`mfaTempSecret` (and re-encrypts any
653
+ * under a non-current key) in one pass. Idempotent; safe while serving
654
+ * traffic. Per-user errors are collected in `failed`, not thrown.
655
+ */
656
+ export function migrateMfaSecrets(opts?: { batchSize?: number; dryRun?: boolean }): Promise<{ scanned: number; encrypted: number; reencrypted: number; failed: Array<{ userId: string; error: string }> }>;
657
+
658
+ // ── Cache adapters ───────────────────────────────────────────────────────
659
+
660
+ export interface CacheAdapter {
661
+ get(key: string): Promise<unknown | null>;
662
+ set(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
663
+ del(key: string): Promise<void>;
664
+ expire(key: string, ttlSeconds: number): Promise<void>;
665
+ /** Atomic get-and-delete — of two concurrent callers, exactly one gets the value. */
666
+ take(key: string): Promise<unknown | null>;
667
+ }
668
+ export class MemoryCacheAdapter implements CacheAdapter {
669
+ /** `maxEntries` (default 100000): when full, expired then oldest entries are evicted. */
670
+ constructor(opts?: { sweepIntervalMs?: number; maxEntries?: number });
671
+ get(key: string): Promise<unknown | null>;
672
+ set(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
673
+ del(key: string): Promise<void>;
674
+ expire(key: string, ttlSeconds: number): Promise<void>;
675
+ /** Atomic get-and-delete — of two concurrent callers, exactly one gets the value. */
676
+ take(key: string): Promise<unknown | null>;
677
+ close(): void;
678
+ }
679
+ export class RedisCacheAdapter implements CacheAdapter {
680
+ constructor(opts: { redis: unknown });
681
+ get(key: string): Promise<unknown | null>;
682
+ set(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
683
+ del(key: string): Promise<void>;
684
+ expire(key: string, ttlSeconds: number): Promise<void>;
685
+ /** Atomic get-and-delete — of two concurrent callers, exactly one gets the value. */
686
+ take(key: string): Promise<unknown | null>;
687
+ }
688
+ export function createRedisCacheAdapter(opts: { host: string; port: number; username?: string; password?: string; db?: number; tls?: boolean | Record<string, unknown>; keepAliveMs?: number }): Promise<RedisCacheAdapter>;
689
+
690
+ // ── Rate limiter adapters ────────────────────────────────────────────────
691
+
692
+ export interface RateLimitRule {
693
+ max?: number;
694
+ windowSeconds?: number;
695
+ }
696
+ export interface RateLimitResult {
697
+ allowed: boolean;
698
+ remaining: number;
699
+ resetAt: number;
700
+ }
701
+ export interface RateLimiter {
702
+ check(key: string): Promise<RateLimitResult>;
703
+ increment(key: string, opts: { max: number; windowSeconds: number }): Promise<RateLimitResult>;
704
+ reset(key: string): Promise<void>;
705
+ }
706
+ export class MemoryRateLimiter implements RateLimiter {
707
+ /**
708
+ * `maxKeys` (default 500000): when full, expired windows and then the oldest counters that haven't
709
+ * reached their limit are evicted; a NEW key is refused (an error — fail-closed call sites answer 503)
710
+ * only if every counter is exhausted.
711
+ */
712
+ constructor(opts?: { sweepIntervalMs?: number; maxKeys?: number });
713
+ check(key: string): Promise<RateLimitResult>;
714
+ increment(key: string, opts: { max: number; windowSeconds: number }): Promise<RateLimitResult>;
715
+ reset(key: string): Promise<void>;
716
+ close(): void;
717
+ }
718
+ export class RedisRateLimiter implements RateLimiter {
719
+ constructor(opts: { redis: unknown });
720
+ check(key: string): Promise<RateLimitResult>;
721
+ increment(key: string, opts: { max: number; windowSeconds: number }): Promise<RateLimitResult>;
722
+ reset(key: string): Promise<void>;
723
+ }
724
+ export function createRedisRateLimiter(opts: { redis?: unknown; host?: string; port?: number; username?: string; password?: string; db?: number; tls?: boolean | Record<string, unknown> }): Promise<RedisRateLimiter>;
725
+ /** Used when `rateLimiting.enabled === false` — every check passes. */
726
+ export class NoopRateLimiter implements RateLimiter {
727
+ check(key: string): Promise<RateLimitResult>;
728
+ increment(key: string, opts: { max: number; windowSeconds: number }): Promise<RateLimitResult>;
729
+ reset(key: string): Promise<void>;
730
+ }
731
+
732
+ // ── Outbound webhooks ────────────────────────────────────────────────────
733
+
734
+ /**
735
+ * `url` must be https (http only for localhost); `secret` at least 16 characters. `events` limits which
736
+ * events the endpoint receives. Credential fields (reset/magic-link tokens, verification codes) are
737
+ * stripped unless `includeCredentials` — set it only on the endpoint that sends those emails.
738
+ */
739
+ export interface WebhookEndpoint {
740
+ url: string;
741
+ secret: string;
742
+ events?: string[];
743
+ includeCredentials?: boolean;
744
+ }
745
+ export class WebhookDispatcher {
746
+ constructor(opts: { endpoints?: WebhookEndpoint[]; maxAttempts?: number; retryBaseDelayMs?: number; timeoutMs?: number; maxInFlight?: number }, logger?: Logger);
747
+ readonly isNoop: boolean;
748
+ /** Fire-and-forget — never returns a promise callers need (or are expected) to await. */
749
+ dispatch(event: string, payload: unknown, opts?: { credentialFields?: string[] }): void;
750
+ }
751
+ /**
752
+ * For consumers receiving webhook deliveries from this package. Verifies the
753
+ * `X-Idp-Signature` header (`t=<unix seconds>,v1=<hex hmac>`) against the
754
+ * exact raw (unparsed) request body.
755
+ */
756
+ /** Pass several secrets during rotation; after verifying, de-duplicate on the body's `id`. */
757
+ export function verifyWebhookSignature(secret: string | string[], rawBody: string, signatureHeader: string | undefined, opts?: { toleranceSeconds?: number }): boolean;
758
+
759
+ // ── Schemas ──────────────────────────────────────────────────────────────
760
+
761
+ export const schemas: Record<string, { parse: (input: unknown) => unknown }>;
762
+
763
+ // ── Router convenience ───────────────────────────────────────────────────
764
+
765
+ export interface BuildRouterOptions {
766
+ /**
767
+ * OAuth2 client administration (`/oauth2/clients*`). NOT mounted unless
768
+ * given; when given, every route runs behind `middleware` (your admin
769
+ * auth). Passing it without at least one middleware throws.
770
+ */
771
+ clientManagement?: { middleware: RequestHandler | RequestHandler[] };
772
+ /** Set a surface to false to leave its routes unmounted. All default to true. */
773
+ features?: Partial<Record<'magicLink' | 'webauthn' | 'sso' | 'oauth2' | 'oidc' | 'serviceMesh', boolean>>;
774
+ /** @deprecated Never had any effect on buildRouter(); accepted and ignored. */
775
+ ownServiceName?: string;
776
+ }
777
+ export function buildRouter(opts?: BuildRouterOptions): Router;