@basaltkit/auth 1.5.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/apikeys-plugin.d.ts +37 -0
- package/dist/apikeys-plugin.js +56 -0
- package/dist/apikeys.d.ts +54 -0
- package/dist/apikeys.js +86 -0
- package/dist/auth.d.ts +279 -0
- package/dist/auth.js +535 -0
- package/dist/hashing.d.ts +23 -0
- package/dist/hashing.js +42 -0
- package/dist/index.d.ts +14 -1123
- package/dist/index.js +14 -1753
- package/dist/jwt.d.ts +26 -0
- package/dist/jwt.js +57 -0
- package/dist/oauth-plugin.d.ts +32 -0
- package/dist/oauth-plugin.js +63 -0
- package/dist/oauth.d.ts +115 -0
- package/dist/oauth.js +242 -0
- package/dist/plugin.d.ts +56 -0
- package/dist/plugin.js +44 -0
- package/dist/routes.d.ts +23 -0
- package/dist/routes.js +223 -0
- package/dist/secret-box.d.ts +10 -0
- package/dist/secret-box.js +38 -0
- package/dist/stores.d.ts +196 -0
- package/dist/stores.js +169 -0
- package/dist/throttle.d.ts +32 -0
- package/dist/throttle.js +45 -0
- package/dist/totp.d.ts +40 -0
- package/dist/totp.js +108 -0
- package/dist/webauthn-plugin.d.ts +13 -0
- package/dist/webauthn-plugin.js +17 -0
- package/dist/webauthn.d.ts +219 -0
- package/dist/webauthn.js +248 -0
- package/package.json +11 -12
package/dist/index.d.ts
CHANGED
|
@@ -1,1123 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* embedded in every hash, so raising them here never breaks verification of
|
|
16
|
-
* older, cheaper hashes; those simply verify at their stored cost.
|
|
17
|
-
*/
|
|
18
|
-
declare class ScryptPasswordHasher implements PasswordHasher {
|
|
19
|
-
private readonly params;
|
|
20
|
-
constructor(params?: {
|
|
21
|
-
N: number;
|
|
22
|
-
r: number;
|
|
23
|
-
p: number;
|
|
24
|
-
});
|
|
25
|
-
hash(plain: string): Promise<string>;
|
|
26
|
-
verify(plain: string, hashed: string): Promise<boolean>;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
declare class TokenInvalidError extends BasaltError {
|
|
30
|
-
readonly status = 401;
|
|
31
|
-
constructor();
|
|
32
|
-
}
|
|
33
|
-
declare class TokenExpiredError extends BasaltError {
|
|
34
|
-
readonly status = 401;
|
|
35
|
-
constructor();
|
|
36
|
-
}
|
|
37
|
-
interface JwtClaims {
|
|
38
|
-
sub: string;
|
|
39
|
-
iat: number;
|
|
40
|
-
exp?: number;
|
|
41
|
-
/** Access-token version — checked against TokenVersionStore for revocation. */
|
|
42
|
-
tv?: number;
|
|
43
|
-
[claim: string]: unknown;
|
|
44
|
-
}
|
|
45
|
-
/** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
|
|
46
|
-
declare function signJwt(claims: Record<string, unknown> & {
|
|
47
|
-
sub: string;
|
|
48
|
-
}, options: {
|
|
49
|
-
secret: string;
|
|
50
|
-
expiresIn?: DurationInput;
|
|
51
|
-
}): string;
|
|
52
|
-
/** Verifies signature and expiry; returns the claims. */
|
|
53
|
-
declare function verifyJwt(token: string, secret: string): JwtClaims;
|
|
54
|
-
|
|
55
|
-
/** The stored user record. Apps map this onto their own user table. */
|
|
56
|
-
interface AuthUser {
|
|
57
|
-
id: string;
|
|
58
|
-
email: string;
|
|
59
|
-
passwordHash: string;
|
|
60
|
-
emailVerified?: boolean;
|
|
61
|
-
[key: string]: unknown;
|
|
62
|
-
}
|
|
63
|
-
/** What lands in ctx().user — never carries the password hash. */
|
|
64
|
-
interface PublicUser {
|
|
65
|
-
id: string;
|
|
66
|
-
email: string;
|
|
67
|
-
emailVerified?: boolean;
|
|
68
|
-
}
|
|
69
|
-
/** Fields the email-verification / password-reset flows update on a user. */
|
|
70
|
-
type UserPatch = Partial<Pick<AuthUser, 'passwordHash' | 'emailVerified'>>;
|
|
71
|
-
interface UserSource {
|
|
72
|
-
findByEmail(email: string): Promise<AuthUser | null>;
|
|
73
|
-
findById(id: string): Promise<AuthUser | null>;
|
|
74
|
-
create(data: {
|
|
75
|
-
email: string;
|
|
76
|
-
passwordHash: string;
|
|
77
|
-
}): Promise<AuthUser>;
|
|
78
|
-
/** Required for email verification and password reset. Returns the updated user. */
|
|
79
|
-
update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
80
|
-
}
|
|
81
|
-
declare class MemoryUserSource implements UserSource {
|
|
82
|
-
private readonly users;
|
|
83
|
-
findByEmail(email: string): Promise<AuthUser | null>;
|
|
84
|
-
findById(id: string): Promise<AuthUser | null>;
|
|
85
|
-
create(data: {
|
|
86
|
-
email: string;
|
|
87
|
-
passwordHash: string;
|
|
88
|
-
}): Promise<AuthUser>;
|
|
89
|
-
update(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
90
|
-
}
|
|
91
|
-
type AuthTokenPurpose = 'verify_email' | 'reset_password';
|
|
92
|
-
interface AuthTokenRecord {
|
|
93
|
-
token: string;
|
|
94
|
-
userId: string;
|
|
95
|
-
purpose: AuthTokenPurpose;
|
|
96
|
-
expiresAt: number;
|
|
97
|
-
usedAt?: number;
|
|
98
|
-
}
|
|
99
|
-
/** Stores single-use, expiring tokens for verification and reset flows. */
|
|
100
|
-
interface AuthTokenStore {
|
|
101
|
-
create(record: AuthTokenRecord): Promise<void>;
|
|
102
|
-
find(token: string): Promise<AuthTokenRecord | null>;
|
|
103
|
-
markUsed(token: string): Promise<void>;
|
|
104
|
-
/** Invalidate outstanding tokens of a purpose for a user before issuing a new one. */
|
|
105
|
-
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
106
|
-
}
|
|
107
|
-
declare class MemoryAuthTokenStore implements AuthTokenStore {
|
|
108
|
-
private readonly records;
|
|
109
|
-
create(record: AuthTokenRecord): Promise<void>;
|
|
110
|
-
find(token: string): Promise<AuthTokenRecord | null>;
|
|
111
|
-
markUsed(token: string): Promise<void>;
|
|
112
|
-
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* A stored API key. The plaintext key is never persisted — only its SHA-256
|
|
116
|
-
* `hash` (for O(1) lookup) and a short `prefix` (for display in listings).
|
|
117
|
-
*/
|
|
118
|
-
interface ApiKeyRecord {
|
|
119
|
-
id: string;
|
|
120
|
-
/** Human label, e.g. "CI pipeline". */
|
|
121
|
-
name: string;
|
|
122
|
-
/** Visible portion shown in listings, e.g. `mk_live_ab12cd`. */
|
|
123
|
-
prefix: string;
|
|
124
|
-
/** SHA-256 of the full presented key. */
|
|
125
|
-
hash: string;
|
|
126
|
-
/** Owning tenant, when created inside a tenant context. */
|
|
127
|
-
tenantId?: string;
|
|
128
|
-
/** User who created the key, when created by a logged-in user. */
|
|
129
|
-
userId?: string;
|
|
130
|
-
/** Granted scopes; `*` means all. */
|
|
131
|
-
scopes: string[];
|
|
132
|
-
createdAt: number;
|
|
133
|
-
lastUsedAt?: number;
|
|
134
|
-
revokedAt?: number;
|
|
135
|
-
}
|
|
136
|
-
/** What a listing exposes — never the hash. */
|
|
137
|
-
type ApiKeyInfo = Omit<ApiKeyRecord, 'hash'>;
|
|
138
|
-
interface ApiKeyFilter {
|
|
139
|
-
tenantId?: string;
|
|
140
|
-
userId?: string;
|
|
141
|
-
}
|
|
142
|
-
interface ApiKeyStore {
|
|
143
|
-
create(record: ApiKeyRecord): Promise<void>;
|
|
144
|
-
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
145
|
-
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
146
|
-
/** Active (non-revoked) keys matching the filter. */
|
|
147
|
-
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
148
|
-
touch(id: string, at: number): Promise<void>;
|
|
149
|
-
revoke(id: string, at: number): Promise<void>;
|
|
150
|
-
}
|
|
151
|
-
declare class MemoryApiKeyStore implements ApiKeyStore {
|
|
152
|
-
private readonly records;
|
|
153
|
-
create(record: ApiKeyRecord): Promise<void>;
|
|
154
|
-
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
155
|
-
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
156
|
-
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
157
|
-
touch(id: string, at: number): Promise<void>;
|
|
158
|
-
revoke(id: string, at: number): Promise<void>;
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Per-user MFA state. `secret` is the base32 TOTP secret; `recoveryCodes`
|
|
162
|
-
* holds SHA-256 hashes of single-use backup codes (never the plaintext).
|
|
163
|
-
*/
|
|
164
|
-
interface MfaRecord {
|
|
165
|
-
secret: string;
|
|
166
|
-
enabled: boolean;
|
|
167
|
-
recoveryCodes: string[];
|
|
168
|
-
/**
|
|
169
|
-
* The last TOTP step (counter) accepted for this user. Codes at a step ≤ this
|
|
170
|
-
* are rejected, so an intercepted 6-digit code cannot be replayed within its
|
|
171
|
-
* validity window (RFC 6238 §5.2). Undefined until the first accepted code.
|
|
172
|
-
*/
|
|
173
|
-
lastUsedStep?: number;
|
|
174
|
-
}
|
|
175
|
-
interface MfaStore {
|
|
176
|
-
get(userId: string): Promise<MfaRecord | null>;
|
|
177
|
-
set(userId: string, record: MfaRecord): Promise<void>;
|
|
178
|
-
delete(userId: string): Promise<void>;
|
|
179
|
-
}
|
|
180
|
-
declare class MemoryMfaStore implements MfaStore {
|
|
181
|
-
private readonly records;
|
|
182
|
-
get(userId: string): Promise<MfaRecord | null>;
|
|
183
|
-
set(userId: string, record: MfaRecord): Promise<void>;
|
|
184
|
-
delete(userId: string): Promise<void>;
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Per-user access-token version. Access tokens carry the version they were
|
|
188
|
-
* minted at; bumping it (on password reset or an explicit "log out everywhere")
|
|
189
|
-
* invalidates every access token issued before the bump — the missing piece for
|
|
190
|
-
* revoking stateless JWTs before they expire. Opt-in via `authPlugin`.
|
|
191
|
-
*/
|
|
192
|
-
interface TokenVersionStore {
|
|
193
|
-
/** Current version for the user (0 if never bumped). */
|
|
194
|
-
get(userId: string): Promise<number>;
|
|
195
|
-
/** Bump the version and return the new value. */
|
|
196
|
-
increment(userId: string): Promise<number>;
|
|
197
|
-
}
|
|
198
|
-
declare class MemoryTokenVersionStore implements TokenVersionStore {
|
|
199
|
-
private readonly versions;
|
|
200
|
-
get(userId: string): Promise<number>;
|
|
201
|
-
increment(userId: string): Promise<number>;
|
|
202
|
-
}
|
|
203
|
-
interface SessionRecord {
|
|
204
|
-
id: string;
|
|
205
|
-
userId: string;
|
|
206
|
-
expiresAt: number;
|
|
207
|
-
}
|
|
208
|
-
interface SessionStore {
|
|
209
|
-
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
210
|
-
/** Returns null for unknown or expired sessions. */
|
|
211
|
-
find(id: string): Promise<SessionRecord | null>;
|
|
212
|
-
delete(id: string): Promise<boolean>;
|
|
213
|
-
/**
|
|
214
|
-
* Deletes every session for a user — fired on password reset so a reset logs
|
|
215
|
-
* out all of the user's active sessions, not just token-based clients.
|
|
216
|
-
* Optional so existing stores keep compiling; implement it to close the gap.
|
|
217
|
-
*/
|
|
218
|
-
deleteAllForUser?(userId: string): Promise<void>;
|
|
219
|
-
}
|
|
220
|
-
declare class MemorySessionStore implements SessionStore {
|
|
221
|
-
private readonly sessions;
|
|
222
|
-
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
223
|
-
find(id: string): Promise<SessionRecord | null>;
|
|
224
|
-
delete(id: string): Promise<boolean>;
|
|
225
|
-
deleteAllForUser(userId: string): Promise<void>;
|
|
226
|
-
}
|
|
227
|
-
interface RefreshRecord {
|
|
228
|
-
token: string;
|
|
229
|
-
familyId: string;
|
|
230
|
-
userId: string;
|
|
231
|
-
expiresAt: number;
|
|
232
|
-
usedAt?: number;
|
|
233
|
-
}
|
|
234
|
-
interface RefreshTokenStore {
|
|
235
|
-
create(record: RefreshRecord): Promise<void>;
|
|
236
|
-
find(token: string): Promise<RefreshRecord | null>;
|
|
237
|
-
markUsed(token: string): Promise<void>;
|
|
238
|
-
/** Revokes every token of a family — fired on reuse detection. */
|
|
239
|
-
revokeFamily(familyId: string): Promise<void>;
|
|
240
|
-
/** Revokes every token of a user — fired on password reset. Optional. */
|
|
241
|
-
revokeAllForUser?(userId: string): Promise<void>;
|
|
242
|
-
}
|
|
243
|
-
declare class MemoryRefreshTokenStore implements RefreshTokenStore {
|
|
244
|
-
private readonly records;
|
|
245
|
-
create(record: RefreshRecord): Promise<void>;
|
|
246
|
-
find(token: string): Promise<RefreshRecord | null>;
|
|
247
|
-
markUsed(token: string): Promise<void>;
|
|
248
|
-
revokeFamily(familyId: string): Promise<void>;
|
|
249
|
-
revokeAllForUser(userId: string): Promise<void>;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** Raised when an identifier has exceeded the failed-login budget. */
|
|
253
|
-
declare class AccountLockedError extends BasaltError {
|
|
254
|
-
readonly retryAfterMs: number;
|
|
255
|
-
readonly status = 429;
|
|
256
|
-
constructor(retryAfterMs: number);
|
|
257
|
-
}
|
|
258
|
-
interface LoginThrottleOptions {
|
|
259
|
-
/** Failed attempts allowed within the window. Default 5. */
|
|
260
|
-
maxAttempts?: number;
|
|
261
|
-
/** Rolling window in ms. Default 15 minutes. */
|
|
262
|
-
windowMs?: number;
|
|
263
|
-
/** Injectable clock for tests. */
|
|
264
|
-
clock?: () => number;
|
|
265
|
-
}
|
|
266
|
-
/**
|
|
267
|
-
* Brute-force guard: counts failed logins per identifier (email) within a
|
|
268
|
-
* rolling window and locks the account once the budget is spent. A successful
|
|
269
|
-
* login clears the counter. In-memory per process; back it with Redis for a
|
|
270
|
-
* cluster by supplying the same behavior.
|
|
271
|
-
*/
|
|
272
|
-
declare class LoginThrottle {
|
|
273
|
-
private readonly failures;
|
|
274
|
-
private readonly maxAttempts;
|
|
275
|
-
private readonly windowMs;
|
|
276
|
-
private readonly clock;
|
|
277
|
-
constructor(options?: LoginThrottleOptions);
|
|
278
|
-
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
279
|
-
assertAllowed(key: string): void;
|
|
280
|
-
recordFailure(key: string): void;
|
|
281
|
-
reset(key: string): void;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
declare class InvalidCredentialsError extends BasaltError {
|
|
285
|
-
readonly status = 401;
|
|
286
|
-
constructor();
|
|
287
|
-
}
|
|
288
|
-
declare class EmailTakenError extends BasaltError {
|
|
289
|
-
readonly status = 409;
|
|
290
|
-
constructor();
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Thrown at construction when the JWT signing secret is missing or too weak. A
|
|
294
|
-
* short/low-entropy HS256 key can be brute-forced offline, letting an attacker
|
|
295
|
-
* forge access tokens for any account — so this fails closed rather than boot
|
|
296
|
-
* with a guessable key. Use `@basaltkit/env`'s `secret({ minLength: 32 })`.
|
|
297
|
-
*/
|
|
298
|
-
declare class WeakJwtSecretError extends BasaltError {
|
|
299
|
-
constructor(reason: string);
|
|
300
|
-
}
|
|
301
|
-
declare class RefreshInvalidError extends BasaltError {
|
|
302
|
-
readonly status = 401;
|
|
303
|
-
constructor();
|
|
304
|
-
}
|
|
305
|
-
/** A used refresh token came back — the whole family is revoked. */
|
|
306
|
-
declare class RefreshReusedError extends BasaltError {
|
|
307
|
-
readonly status = 401;
|
|
308
|
-
constructor();
|
|
309
|
-
}
|
|
310
|
-
declare class AuthRequiredError extends BasaltError {
|
|
311
|
-
readonly status = 401;
|
|
312
|
-
constructor();
|
|
313
|
-
}
|
|
314
|
-
/** A verification / reset token was unknown, already used, or expired. */
|
|
315
|
-
declare class AuthTokenInvalidError extends BasaltError {
|
|
316
|
-
readonly status = 400;
|
|
317
|
-
constructor();
|
|
318
|
-
}
|
|
319
|
-
/** The configured UserSource can't be updated (needed for verification/reset). */
|
|
320
|
-
declare class UserUpdateUnsupportedError extends BasaltError {
|
|
321
|
-
readonly status = 500;
|
|
322
|
-
constructor();
|
|
323
|
-
}
|
|
324
|
-
/** Credentials were correct but the account has MFA — a code is required. */
|
|
325
|
-
declare class MfaRequiredError extends BasaltError {
|
|
326
|
-
readonly status = 401;
|
|
327
|
-
constructor();
|
|
328
|
-
}
|
|
329
|
-
/** The supplied MFA (or recovery) code was wrong. */
|
|
330
|
-
declare class MfaInvalidCodeError extends BasaltError {
|
|
331
|
-
readonly status = 401;
|
|
332
|
-
constructor();
|
|
333
|
-
}
|
|
334
|
-
/** An MFA action needed an enrollment that doesn't exist. */
|
|
335
|
-
declare class MfaNotEnrolledError extends BasaltError {
|
|
336
|
-
readonly status = 400;
|
|
337
|
-
constructor();
|
|
338
|
-
}
|
|
339
|
-
interface TokenPair {
|
|
340
|
-
accessToken: string;
|
|
341
|
-
refreshToken: string;
|
|
342
|
-
}
|
|
343
|
-
interface AuthOptions {
|
|
344
|
-
users: UserSource;
|
|
345
|
-
secret: string;
|
|
346
|
-
hasher?: PasswordHasher;
|
|
347
|
-
sessions?: SessionStore;
|
|
348
|
-
refreshTokens?: RefreshTokenStore;
|
|
349
|
-
accessTtl?: DurationInput;
|
|
350
|
-
refreshTtl?: DurationInput;
|
|
351
|
-
sessionTtl?: DurationInput;
|
|
352
|
-
hooks?: HookBus;
|
|
353
|
-
/** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
|
|
354
|
-
loginThrottle?: LoginThrottle | false;
|
|
355
|
-
/**
|
|
356
|
-
* Per-IP login throttle — blunts password spraying (1 attempt across many
|
|
357
|
-
* accounts) and lockout-DoS that a per-email counter alone misses. Enabled by
|
|
358
|
-
* default with a higher budget than the per-email one; pass `false` to disable.
|
|
359
|
-
* Only applies when the caller passes the client ip to `login`.
|
|
360
|
-
*/
|
|
361
|
-
ipLoginThrottle?: LoginThrottle | false;
|
|
362
|
-
/**
|
|
363
|
-
* Make the public registration endpoint enumeration-safe: a request for an
|
|
364
|
-
* email that already exists returns the same response (and does equivalent
|
|
365
|
-
* work) as a fresh signup, instead of a 409 that reveals the account exists.
|
|
366
|
-
* Applies to {@link Auth.registerSafely} (used by the register route); the
|
|
367
|
-
* lower-level {@link Auth.register} always throws on a duplicate. Default true.
|
|
368
|
-
*/
|
|
369
|
-
enumerationSafeRegister?: boolean;
|
|
370
|
-
/** Store for verification/reset tokens. Default: in-memory. */
|
|
371
|
-
tokens?: AuthTokenStore;
|
|
372
|
-
/** Email-verification link lifetime. Default 24h. */
|
|
373
|
-
verificationTtl?: DurationInput;
|
|
374
|
-
/** Password-reset link lifetime. Default 1h. */
|
|
375
|
-
resetTtl?: DurationInput;
|
|
376
|
-
/** Store for MFA (TOTP) enrollment state. Default: in-memory. */
|
|
377
|
-
mfa?: MfaStore;
|
|
378
|
-
/**
|
|
379
|
-
* Enables access-token revocation. When set, access tokens carry a version
|
|
380
|
-
* (`tv`) and `resetPassword`/`revokeAllTokens` bump it — invalidating every
|
|
381
|
-
* token issued before the bump, even before its TTL expires. Opt-in; access
|
|
382
|
-
* verification then costs one store read per request. Default: off.
|
|
383
|
-
*/
|
|
384
|
-
tokenVersions?: TokenVersionStore;
|
|
385
|
-
/**
|
|
386
|
-
* Key for encrypting TOTP secrets at rest (AES-256-GCM). When set, secrets are
|
|
387
|
-
* stored as `v1:` envelopes so a database leak can't recover a live second
|
|
388
|
-
* factor; existing plaintext records keep working and are encrypted on next
|
|
389
|
-
* write. Any length — derived to 32 bytes. Omit to store secrets in plaintext.
|
|
390
|
-
*/
|
|
391
|
-
mfaEncryptionKey?: string | Buffer;
|
|
392
|
-
/** Issuer name shown in authenticator apps. Default 'Basalt'. */
|
|
393
|
-
mfaIssuer?: string;
|
|
394
|
-
}
|
|
395
|
-
declare const publicUser: (user: AuthUser) => PublicUser;
|
|
396
|
-
declare class Auth {
|
|
397
|
-
readonly users: UserSource;
|
|
398
|
-
private readonly hasher;
|
|
399
|
-
private readonly sessions;
|
|
400
|
-
private readonly refreshTokens;
|
|
401
|
-
private readonly secret;
|
|
402
|
-
private readonly accessTtl;
|
|
403
|
-
private readonly refreshTtl;
|
|
404
|
-
private readonly sessionTtl;
|
|
405
|
-
private readonly hooks;
|
|
406
|
-
private readonly throttle;
|
|
407
|
-
private readonly ipThrottle;
|
|
408
|
-
private readonly tokens;
|
|
409
|
-
private readonly verificationTtl;
|
|
410
|
-
private readonly resetTtl;
|
|
411
|
-
private readonly mfa;
|
|
412
|
-
private readonly mfaIssuer;
|
|
413
|
-
private readonly mfaKey;
|
|
414
|
-
private readonly tokenVersions;
|
|
415
|
-
private readonly enumerationSafeRegister;
|
|
416
|
-
constructor(options: AuthOptions);
|
|
417
|
-
register(email: string, password: string): Promise<PublicUser>;
|
|
418
|
-
/**
|
|
419
|
-
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
420
|
-
* matched by email — find-or-create. A new account is created **passwordless**
|
|
421
|
-
* (a random, unusable password hash), so password login won't work for it
|
|
422
|
-
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
423
|
-
* Returns the tokens and whether the account was just created.
|
|
424
|
-
*/
|
|
425
|
-
socialLogin(email: string, options?: {
|
|
426
|
-
emailVerified?: boolean;
|
|
427
|
-
}): Promise<{
|
|
428
|
-
user: PublicUser;
|
|
429
|
-
tokens: TokenPair;
|
|
430
|
-
created: boolean;
|
|
431
|
-
}>;
|
|
432
|
-
/**
|
|
433
|
-
* Enumeration-safe registration for the public endpoint: creates the account
|
|
434
|
-
* for a new email, or — when the email is already taken — does equivalent work
|
|
435
|
-
* (so timing doesn't leak) and emits `auth:register_existing_email` so the app
|
|
436
|
-
* can send an out-of-band "you already have an account" email. Returns nothing
|
|
437
|
-
* either way, so the response can't reveal whether the account existed.
|
|
438
|
-
*
|
|
439
|
-
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
440
|
-
* duplicate instead (the classic, enumerable behavior).
|
|
441
|
-
*/
|
|
442
|
-
registerSafely(email: string, password: string): Promise<void>;
|
|
443
|
-
/** Verifies credentials without side effects. Null on failure. */
|
|
444
|
-
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
445
|
-
private dummyHashPromise?;
|
|
446
|
-
/** A valid hash of a throwaway secret, produced once by the configured hasher. */
|
|
447
|
-
private dummyHash;
|
|
448
|
-
/**
|
|
449
|
-
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
450
|
-
* account after too many failures (see {@link LoginThrottle}); a success
|
|
451
|
-
* clears the counter.
|
|
452
|
-
*
|
|
453
|
-
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
454
|
-
* required: a correct password with a missing code throws
|
|
455
|
-
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
456
|
-
* wrong code throws {@link MfaInvalidCodeError}.
|
|
457
|
-
*/
|
|
458
|
-
login(email: string, password: string, mfaCode?: string, context?: {
|
|
459
|
-
ip?: string;
|
|
460
|
-
}): Promise<{
|
|
461
|
-
user: PublicUser;
|
|
462
|
-
tokens: TokenPair;
|
|
463
|
-
}>;
|
|
464
|
-
/**
|
|
465
|
-
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
466
|
-
* and issues a new one in the same family. If a consumed token comes back
|
|
467
|
-
* (theft indicator), the whole family is revoked.
|
|
468
|
-
*/
|
|
469
|
-
refresh(refreshToken: string): Promise<TokenPair>;
|
|
470
|
-
/** Revokes a refresh family — logout for token-based clients. */
|
|
471
|
-
revoke(refreshToken: string): Promise<void>;
|
|
472
|
-
/** Structural JWT verification only (signature + expiry). */
|
|
473
|
-
verifyAccess(accessToken: string): JwtClaims;
|
|
474
|
-
/**
|
|
475
|
-
* Verifies the access token AND, when token-version revocation is enabled,
|
|
476
|
-
* rejects a token minted before the user's version was last bumped (i.e.
|
|
477
|
-
* revoked by a password reset / `revokeAllTokens`). Prefer this over
|
|
478
|
-
* {@link verifyAccess} on the request path.
|
|
479
|
-
*/
|
|
480
|
-
verifyAccessToken(accessToken: string): Promise<JwtClaims>;
|
|
481
|
-
/**
|
|
482
|
-
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
483
|
-
* by bumping the token version. No-op unless a {@link TokenVersionStore} is
|
|
484
|
-
* configured. Pair with refresh/session revocation for a full logout.
|
|
485
|
-
*/
|
|
486
|
-
revokeAllTokens(userId: string): Promise<void>;
|
|
487
|
-
createSession(userId: string): Promise<SessionRecord>;
|
|
488
|
-
sessionUser(sessionId: string): Promise<AuthUser | null>;
|
|
489
|
-
logout(sessionId: string): Promise<void>;
|
|
490
|
-
/**
|
|
491
|
-
* Starts email verification: mints a single-use token and emits
|
|
492
|
-
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
493
|
-
* caller can build the link) or null if no account matches — never reveals
|
|
494
|
-
* whether the email exists.
|
|
495
|
-
*/
|
|
496
|
-
requestEmailVerification(email: string): Promise<{
|
|
497
|
-
user: PublicUser;
|
|
498
|
-
token: string;
|
|
499
|
-
} | null>;
|
|
500
|
-
/** Consumes a verification token and marks the user's email verified. */
|
|
501
|
-
verifyEmail(token: string): Promise<PublicUser>;
|
|
502
|
-
/**
|
|
503
|
-
* Starts a password reset: mints a single-use token and emits
|
|
504
|
-
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
505
|
-
* the caller always responds 200 (no account enumeration).
|
|
506
|
-
*/
|
|
507
|
-
requestPasswordReset(email: string): Promise<{
|
|
508
|
-
user: PublicUser;
|
|
509
|
-
token: string;
|
|
510
|
-
} | null>;
|
|
511
|
-
/**
|
|
512
|
-
* Consumes a reset token, sets the new password, and revokes every existing
|
|
513
|
-
* session/refresh token for the user (a reset logs everyone else out).
|
|
514
|
-
*/
|
|
515
|
-
resetPassword(token: string, newPassword: string): Promise<PublicUser>;
|
|
516
|
-
isMfaEnabled(userId: string): Promise<boolean>;
|
|
517
|
-
mfaStatus(userId: string): Promise<{
|
|
518
|
-
enabled: boolean;
|
|
519
|
-
pending: boolean;
|
|
520
|
-
}>;
|
|
521
|
-
/**
|
|
522
|
-
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
523
|
-
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
524
|
-
* {@link activateMfa} with a code from the app to switch it on.
|
|
525
|
-
*/
|
|
526
|
-
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
527
|
-
private encryptMfaSecret;
|
|
528
|
-
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
529
|
-
private decryptMfaSecret;
|
|
530
|
-
enrollMfa(userId: string): Promise<{
|
|
531
|
-
secret: string;
|
|
532
|
-
otpauthUri: string;
|
|
533
|
-
}>;
|
|
534
|
-
/**
|
|
535
|
-
* Confirms enrollment by checking a code against the pending secret, enables
|
|
536
|
-
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
537
|
-
*/
|
|
538
|
-
activateMfa(userId: string, code: string): Promise<{
|
|
539
|
-
recoveryCodes: string[];
|
|
540
|
-
}>;
|
|
541
|
-
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
542
|
-
disableMfa(userId: string, code: string): Promise<void>;
|
|
543
|
-
/**
|
|
544
|
-
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
545
|
-
* is consumed on success). Returns false unless MFA is enabled.
|
|
546
|
-
*/
|
|
547
|
-
verifyMfaCode(userId: string, code: string): Promise<boolean>;
|
|
548
|
-
private generateRecoveryCode;
|
|
549
|
-
private hashRecoveryCode;
|
|
550
|
-
/** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
|
|
551
|
-
* persisted, so a leak of the token/session table can't be replayed. */
|
|
552
|
-
private hashToken;
|
|
553
|
-
private issueOneTimeToken;
|
|
554
|
-
private consumeToken;
|
|
555
|
-
private updateUser;
|
|
556
|
-
private issueTokens;
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/** RFC 4648 base32 encode (no padding, uppercase) — the format authenticator apps expect. */
|
|
560
|
-
declare function base32Encode(bytes: Uint8Array): string;
|
|
561
|
-
/** RFC 4648 base32 decode — tolerant of lowercase, spaces, and `=` padding. */
|
|
562
|
-
declare function base32Decode(input: string): Buffer;
|
|
563
|
-
/** A fresh, random base32 TOTP secret (default 20 bytes = 160 bits). */
|
|
564
|
-
declare function generateTotpSecret(bytes?: number): string;
|
|
565
|
-
interface TotpOptions {
|
|
566
|
-
/** Seconds per code. Default 30. */
|
|
567
|
-
period?: number;
|
|
568
|
-
/** Code length. Default 6. */
|
|
569
|
-
digits?: number;
|
|
570
|
-
/** Milliseconds since epoch. Default Date.now(). */
|
|
571
|
-
now?: number;
|
|
572
|
-
}
|
|
573
|
-
/** The current TOTP code (RFC 6238) for a base32 secret. */
|
|
574
|
-
declare function totp(secret: string, options?: TotpOptions): string;
|
|
575
|
-
interface VerifyTotpOptions extends TotpOptions {
|
|
576
|
-
/** Accept codes ±`window` steps to absorb clock drift. Default 1. */
|
|
577
|
-
window?: number;
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* The TOTP step (counter) that `token` matches within the allowed window, or
|
|
581
|
-
* null. Constant-time over the window (no early exit → no timing side channel).
|
|
582
|
-
* The step is what enables replay prevention: persist the last-accepted step and
|
|
583
|
-
* reject any code whose step is ≤ it (RFC 6238 §5.2).
|
|
584
|
-
*/
|
|
585
|
-
declare function matchTotpStep(secret: string, token: string, options?: VerifyTotpOptions): number | null;
|
|
586
|
-
/** True when `token` matches the TOTP within the allowed time window (constant-time). */
|
|
587
|
-
declare function verifyTotp(secret: string, token: string, options?: VerifyTotpOptions): boolean;
|
|
588
|
-
interface OtpauthUriInput {
|
|
589
|
-
secret: string;
|
|
590
|
-
/** The account label, typically the user's email. */
|
|
591
|
-
account: string;
|
|
592
|
-
/** The issuer shown in the authenticator app. */
|
|
593
|
-
issuer: string;
|
|
594
|
-
digits?: number;
|
|
595
|
-
period?: number;
|
|
596
|
-
}
|
|
597
|
-
/** Builds an `otpauth://totp/...` URI to render as a QR code. */
|
|
598
|
-
declare function otpauthUri(input: OtpauthUriInput): string;
|
|
599
|
-
|
|
600
|
-
declare module '@basaltkit/core' {
|
|
601
|
-
interface RequestContext {
|
|
602
|
-
/** The authenticated user of the current request, set by auth. */
|
|
603
|
-
user?: PublicUser;
|
|
604
|
-
}
|
|
605
|
-
interface BasaltHooks {
|
|
606
|
-
'auth:registered': {
|
|
607
|
-
user: PublicUser;
|
|
608
|
-
};
|
|
609
|
-
/**
|
|
610
|
-
* Someone tried to register an email that already has an account. Emitted by
|
|
611
|
-
* the enumeration-safe register endpoint so the app can email the address
|
|
612
|
-
* ("you already have an account — sign in or reset your password") instead of
|
|
613
|
-
* revealing existence in the HTTP response. Only the email is provided.
|
|
614
|
-
*/
|
|
615
|
-
'auth:register_existing_email': {
|
|
616
|
-
email: string;
|
|
617
|
-
};
|
|
618
|
-
'auth:login': {
|
|
619
|
-
user: PublicUser;
|
|
620
|
-
};
|
|
621
|
-
'auth:login_failed': {
|
|
622
|
-
email: string;
|
|
623
|
-
};
|
|
624
|
-
'auth:logout': {
|
|
625
|
-
user: PublicUser;
|
|
626
|
-
};
|
|
627
|
-
/** Email verification requested — the app emails the token as a link. */
|
|
628
|
-
'auth:verify_requested': {
|
|
629
|
-
user: PublicUser;
|
|
630
|
-
token: string;
|
|
631
|
-
};
|
|
632
|
-
'auth:email_verified': {
|
|
633
|
-
user: PublicUser;
|
|
634
|
-
};
|
|
635
|
-
/** Password reset requested — the app emails the token as a link. */
|
|
636
|
-
'auth:password_reset_requested': {
|
|
637
|
-
user: PublicUser;
|
|
638
|
-
token: string;
|
|
639
|
-
};
|
|
640
|
-
'auth:password_reset': {
|
|
641
|
-
user: PublicUser;
|
|
642
|
-
};
|
|
643
|
-
'auth:mfa_enabled': {
|
|
644
|
-
user: PublicUser;
|
|
645
|
-
};
|
|
646
|
-
'auth:mfa_disabled': {
|
|
647
|
-
user: PublicUser;
|
|
648
|
-
};
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
declare const AUTH: _basaltkit_core.Token<Auth>;
|
|
652
|
-
type AuthPluginOptions = Omit<AuthOptions, 'hooks'>;
|
|
653
|
-
declare function authPlugin(options: AuthPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
654
|
-
|
|
655
|
-
/** A route required a scope the presented key does not hold. */
|
|
656
|
-
declare class ScopeRequiredError extends BasaltError {
|
|
657
|
-
readonly status = 403;
|
|
658
|
-
constructor(scope: string);
|
|
659
|
-
}
|
|
660
|
-
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
661
|
-
declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
|
|
662
|
-
interface IssueApiKeyInput {
|
|
663
|
-
name: string;
|
|
664
|
-
scopes?: string[] | undefined;
|
|
665
|
-
tenantId?: string;
|
|
666
|
-
userId?: string;
|
|
667
|
-
}
|
|
668
|
-
interface ApiKeysOptions {
|
|
669
|
-
store?: ApiKeyStore;
|
|
670
|
-
hooks?: HookBus;
|
|
671
|
-
/** Injectable clock — tests and deterministic runs override it. */
|
|
672
|
-
now?: () => number;
|
|
673
|
-
}
|
|
674
|
-
/**
|
|
675
|
-
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
676
|
-
* {@link issue}; only its SHA-256 hash is stored, so a leaked database never
|
|
677
|
-
* yields usable keys.
|
|
678
|
-
*/
|
|
679
|
-
declare class ApiKeys {
|
|
680
|
-
private readonly store;
|
|
681
|
-
private readonly hooks;
|
|
682
|
-
private readonly now;
|
|
683
|
-
constructor(options?: ApiKeysOptions);
|
|
684
|
-
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
685
|
-
issue(input: IssueApiKeyInput): Promise<{
|
|
686
|
-
record: ApiKeyInfo;
|
|
687
|
-
key: string;
|
|
688
|
-
}>;
|
|
689
|
-
/**
|
|
690
|
-
* Resolves a presented key to its record, or null if it's malformed,
|
|
691
|
-
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
692
|
-
*/
|
|
693
|
-
verify(presented: string): Promise<ApiKeyRecord | null>;
|
|
694
|
-
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
695
|
-
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
696
|
-
revoke(id: string): Promise<void>;
|
|
697
|
-
/** Reads a single key's public info (used to authorize a revoke). */
|
|
698
|
-
get(id: string): Promise<ApiKeyInfo | null>;
|
|
699
|
-
}
|
|
700
|
-
/** The value stashed on `ctx().apiKey` after a request authenticates with a key. */
|
|
701
|
-
interface ApiKeyContext {
|
|
702
|
-
id: string;
|
|
703
|
-
scopes: string[];
|
|
704
|
-
tenantId?: string;
|
|
705
|
-
userId?: string;
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
declare module '@basaltkit/core' {
|
|
709
|
-
interface RequestContext {
|
|
710
|
-
/** Set when the request authenticated with an API key instead of a session. */
|
|
711
|
-
apiKey?: ApiKeyContext;
|
|
712
|
-
}
|
|
713
|
-
interface BasaltHooks {
|
|
714
|
-
'auth:apikey_issued': {
|
|
715
|
-
id: string;
|
|
716
|
-
tenantId?: string;
|
|
717
|
-
userId?: string;
|
|
718
|
-
};
|
|
719
|
-
'auth:apikey_revoked': {
|
|
720
|
-
id: string;
|
|
721
|
-
};
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
declare const API_KEYS: _basaltkit_core.Token<ApiKeys>;
|
|
725
|
-
interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
726
|
-
/**
|
|
727
|
-
* Header carrying the key, besides `Authorization: Bearer mk_...`.
|
|
728
|
-
* Default `x-api-key`.
|
|
729
|
-
*/
|
|
730
|
-
header?: string;
|
|
731
|
-
/**
|
|
732
|
-
* When provided, a key that carries a `userId` also populates `ctx().user`,
|
|
733
|
-
* so scope-guarded routes can read the acting user.
|
|
734
|
-
*/
|
|
735
|
-
users?: UserSource;
|
|
736
|
-
}
|
|
737
|
-
/**
|
|
738
|
-
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
739
|
-
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
740
|
-
* `meta.scopes` on routes. Pair with {@link apiKeyRoutes} for CRUD endpoints.
|
|
741
|
-
*/
|
|
742
|
-
declare function apiKeysPlugin(options?: ApiKeysPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
743
|
-
|
|
744
|
-
/**
|
|
745
|
-
* Ready-made auth routes — register them in fastifyPlugin({ routes }):
|
|
746
|
-
* register · login · refresh · logout · me, plus email verification
|
|
747
|
-
* (`/auth/verify/request`, `/auth/verify`) and password reset
|
|
748
|
-
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
749
|
-
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
750
|
-
*/
|
|
751
|
-
declare function authRoutes(): BasaltRoute[];
|
|
752
|
-
/**
|
|
753
|
-
* CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
|
|
754
|
-
* are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
|
|
755
|
-
* ever sees or revokes keys within that scope. Register alongside
|
|
756
|
-
* {@link authRoutes} and pair with `apiKeysPlugin`.
|
|
757
|
-
*/
|
|
758
|
-
declare function apiKeyRoutes(): BasaltRoute[];
|
|
759
|
-
/**
|
|
760
|
-
* MFA (TOTP) self-service routes, all requiring a logged-in user: enroll,
|
|
761
|
-
* activate (returns one-time recovery codes), status, and disable. Register
|
|
762
|
-
* alongside {@link authRoutes} and enable MFA at login via the optional
|
|
763
|
-
* `mfaCode` field on `POST /auth/login`.
|
|
764
|
-
*/
|
|
765
|
-
declare function mfaRoutes(): BasaltRoute[];
|
|
766
|
-
|
|
767
|
-
declare class OAuthProviderUnknownError extends BasaltError {
|
|
768
|
-
readonly status = 404;
|
|
769
|
-
constructor(name: string);
|
|
770
|
-
}
|
|
771
|
-
declare class OAuthStateInvalidError extends BasaltError {
|
|
772
|
-
readonly status = 400;
|
|
773
|
-
constructor();
|
|
774
|
-
}
|
|
775
|
-
declare class OAuthExchangeError extends BasaltError {
|
|
776
|
-
readonly status = 502;
|
|
777
|
-
constructor(detail: string);
|
|
778
|
-
}
|
|
779
|
-
/** The normalized profile a provider returns after a successful login. */
|
|
780
|
-
interface OAuthProfile {
|
|
781
|
-
/** Stable id at the provider (the `sub` / user id). */
|
|
782
|
-
subject: string;
|
|
783
|
-
email: string;
|
|
784
|
-
emailVerified?: boolean;
|
|
785
|
-
name?: string;
|
|
786
|
-
}
|
|
787
|
-
interface OAuthProvider {
|
|
788
|
-
name: string;
|
|
789
|
-
authorizeUrl: string;
|
|
790
|
-
tokenUrl: string;
|
|
791
|
-
clientId: string;
|
|
792
|
-
clientSecret: string;
|
|
793
|
-
scopes: string[];
|
|
794
|
-
/** Fetches and normalizes the user profile from an access token. */
|
|
795
|
-
fetchProfile(accessToken: string, doFetch: typeof fetch): Promise<OAuthProfile>;
|
|
796
|
-
}
|
|
797
|
-
interface ProviderKeys {
|
|
798
|
-
clientId: string;
|
|
799
|
-
clientSecret: string;
|
|
800
|
-
scopes?: string[];
|
|
801
|
-
}
|
|
802
|
-
/** Google (OpenID Connect). Default scopes: `openid email profile`. */
|
|
803
|
-
declare function googleProvider(keys: ProviderKeys): OAuthProvider;
|
|
804
|
-
/** GitHub. Default scopes: `read:user user:email` (needed for a verified email). */
|
|
805
|
-
declare function githubProvider(keys: ProviderKeys): OAuthProvider;
|
|
806
|
-
interface OidcConfig extends ProviderKeys {
|
|
807
|
-
/** Display name for this provider. Default: 'oidc'. */
|
|
808
|
-
name?: string;
|
|
809
|
-
authorizeUrl: string;
|
|
810
|
-
tokenUrl: string;
|
|
811
|
-
userInfoUrl: string;
|
|
812
|
-
}
|
|
813
|
-
/**
|
|
814
|
-
* A generic **OIDC** provider — enterprise SSO for any OpenID Connect IdP
|
|
815
|
-
* (Okta, Azure AD / Entra ID, Auth0, Google Workspace, Keycloak…). Pass the
|
|
816
|
-
* three endpoints from the IdP's `.well-known/openid-configuration`, or use
|
|
817
|
-
* {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
|
|
818
|
-
* `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
|
|
819
|
-
*/
|
|
820
|
-
declare function oidcProvider(config: OidcConfig): OAuthProvider;
|
|
821
|
-
/**
|
|
822
|
-
* Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
|
|
823
|
-
* (`${issuer}/.well-known/openid-configuration`). Await it at startup.
|
|
824
|
-
*/
|
|
825
|
-
declare function discoverOidcProvider(config: {
|
|
826
|
-
name?: string;
|
|
827
|
-
/** The IdP issuer URL, e.g. `https://acme.okta.com` or `https://login.microsoftonline.com/<tenant>/v2.0`. */
|
|
828
|
-
issuer: string;
|
|
829
|
-
clientId: string;
|
|
830
|
-
clientSecret: string;
|
|
831
|
-
scopes?: string[];
|
|
832
|
-
fetch?: typeof fetch;
|
|
833
|
-
}): Promise<OAuthProvider>;
|
|
834
|
-
interface OAuthOptions {
|
|
835
|
-
/** Secret used to sign the CSRF `state` (typically your APP_SECRET). */
|
|
836
|
-
secret: string;
|
|
837
|
-
/** Injected fetch (tests). Default: global fetch. */
|
|
838
|
-
fetch?: typeof fetch;
|
|
839
|
-
/** Clock in ms (tests). Default: Date.now. */
|
|
840
|
-
now?: () => number;
|
|
841
|
-
/** How long a signed `state` stays valid, in ms. Default: 10 minutes. */
|
|
842
|
-
stateTtlMs?: number;
|
|
843
|
-
}
|
|
844
|
-
/**
|
|
845
|
-
* OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
|
|
846
|
-
* build an authorize URL with a signed, expiring `state`, then exchange the code
|
|
847
|
-
* for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
|
|
848
|
-
* The `state` is HMAC-signed and stateless — no server storage, works cookieless.
|
|
849
|
-
*/
|
|
850
|
-
declare class OAuth {
|
|
851
|
-
private readonly auth;
|
|
852
|
-
private readonly options;
|
|
853
|
-
private readonly providers;
|
|
854
|
-
private readonly doFetch;
|
|
855
|
-
private readonly now;
|
|
856
|
-
private readonly stateTtl;
|
|
857
|
-
constructor(auth: Auth, providers: OAuthProvider[], options: OAuthOptions);
|
|
858
|
-
names(): string[];
|
|
859
|
-
private provider;
|
|
860
|
-
/** The provider's authorization URL to redirect the browser to. */
|
|
861
|
-
authorizeUrl(name: string, redirectUri: string): string;
|
|
862
|
-
/** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
|
|
863
|
-
callback(name: string, input: {
|
|
864
|
-
code: string;
|
|
865
|
-
state: string | undefined;
|
|
866
|
-
redirectUri: string;
|
|
867
|
-
}): Promise<{
|
|
868
|
-
user: PublicUser;
|
|
869
|
-
tokens: TokenPair;
|
|
870
|
-
created: boolean;
|
|
871
|
-
}>;
|
|
872
|
-
private exchangeCode;
|
|
873
|
-
private signState;
|
|
874
|
-
private verifyState;
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
declare const OAUTH: _basaltkit_core.Token<OAuth>;
|
|
878
|
-
interface OAuthPluginOptions extends Omit<OAuthOptions, never> {
|
|
879
|
-
providers: OAuthProvider[];
|
|
880
|
-
}
|
|
881
|
-
/**
|
|
882
|
-
* Registers the {@link OAuth} service (token {@link OAUTH}). Pair it with
|
|
883
|
-
* {@link oauthRoutes} and register both AFTER `authPlugin` — the service resolves
|
|
884
|
-
* `AUTH` to log users in.
|
|
885
|
-
*/
|
|
886
|
-
declare function oauthPlugin(options: OAuthPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
887
|
-
interface OAuthRoutesOptions {
|
|
888
|
-
/**
|
|
889
|
-
* Base URL of your deployed app. The provider redirect_uri is built as
|
|
890
|
-
* `${callbackBaseUrl}/auth/oauth/:provider/callback` and must be registered
|
|
891
|
-
* with each provider.
|
|
892
|
-
*/
|
|
893
|
-
callbackBaseUrl: string;
|
|
894
|
-
/**
|
|
895
|
-
* When set, the callback redirects the browser here after a successful login
|
|
896
|
-
* with `#access_token=…&refresh_token=…` in the fragment (for SPA flows).
|
|
897
|
-
* When omitted, the callback responds with JSON `{ user, accessToken, refreshToken }`.
|
|
898
|
-
*/
|
|
899
|
-
successRedirect?: string;
|
|
900
|
-
}
|
|
901
|
-
/**
|
|
902
|
-
* Ready-made OAuth routes:
|
|
903
|
-
* - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
|
|
904
|
-
* - `GET /auth/oauth/:provider/callback` → exchanges the code and logs in.
|
|
905
|
-
*/
|
|
906
|
-
declare function oauthRoutes(options: OAuthRoutesOptions): BasaltRoute[];
|
|
907
|
-
|
|
908
|
-
/**
|
|
909
|
-
* WebAuthn / passkeys ceremony orchestration. The framework owns everything that
|
|
910
|
-
* is NOT cryptography — issuing challenges, assembling the browser options,
|
|
911
|
-
* storing credentials, and the counter/clone check — and delegates the actual
|
|
912
|
-
* attestation/assertion verification to a pluggable {@link WebAuthnVerifier}
|
|
913
|
-
* (implement it over `@simplewebauthn/server` or similar). This keeps the
|
|
914
|
-
* framework free of a crypto dependency while still driving the full flow.
|
|
915
|
-
*/
|
|
916
|
-
interface PasskeyCredential {
|
|
917
|
-
/** base64url credential id. */
|
|
918
|
-
id: string;
|
|
919
|
-
userId: string;
|
|
920
|
-
/** base64url COSE public key (opaque to the framework; the verifier reads it). */
|
|
921
|
-
publicKey: string;
|
|
922
|
-
/** Signature counter for clone detection. */
|
|
923
|
-
counter: number;
|
|
924
|
-
transports?: string[];
|
|
925
|
-
deviceName?: string;
|
|
926
|
-
createdAt: number;
|
|
927
|
-
lastUsedAt?: number;
|
|
928
|
-
}
|
|
929
|
-
interface PasskeyStore {
|
|
930
|
-
add(credential: PasskeyCredential): Promise<void>;
|
|
931
|
-
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
932
|
-
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
933
|
-
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
934
|
-
remove(credentialId: string): Promise<void>;
|
|
935
|
-
}
|
|
936
|
-
declare class MemoryPasskeyStore implements PasskeyStore {
|
|
937
|
-
private readonly byId;
|
|
938
|
-
add(credential: PasskeyCredential): Promise<void>;
|
|
939
|
-
get(credentialId: string): Promise<PasskeyCredential | null>;
|
|
940
|
-
forUser(userId: string): Promise<PasskeyCredential[]>;
|
|
941
|
-
updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
|
|
942
|
-
remove(credentialId: string): Promise<void>;
|
|
943
|
-
}
|
|
944
|
-
interface WebAuthnChallengeStore {
|
|
945
|
-
save(key: string, challenge: string, expiresAt: number): Promise<void>;
|
|
946
|
-
/** Return AND consume the challenge (single-use), or null if missing/expired. */
|
|
947
|
-
take(key: string): Promise<string | null>;
|
|
948
|
-
}
|
|
949
|
-
declare class MemoryWebAuthnChallengeStore implements WebAuthnChallengeStore {
|
|
950
|
-
private readonly entries;
|
|
951
|
-
private readonly now;
|
|
952
|
-
constructor(options?: {
|
|
953
|
-
now?: () => number;
|
|
954
|
-
});
|
|
955
|
-
save(key: string, challenge: string, expiresAt: number): Promise<void>;
|
|
956
|
-
take(key: string): Promise<string | null>;
|
|
957
|
-
}
|
|
958
|
-
interface VerifyRegistrationInput {
|
|
959
|
-
/** The `RegistrationResponseJSON` from `@simplewebauthn/browser`. */
|
|
960
|
-
response: unknown;
|
|
961
|
-
expectedChallenge: string;
|
|
962
|
-
expectedOrigin: string | string[];
|
|
963
|
-
expectedRpId: string;
|
|
964
|
-
requireUserVerification: boolean;
|
|
965
|
-
}
|
|
966
|
-
interface VerifiedRegistration {
|
|
967
|
-
verified: boolean;
|
|
968
|
-
credential?: {
|
|
969
|
-
id: string;
|
|
970
|
-
publicKey: string;
|
|
971
|
-
counter: number;
|
|
972
|
-
transports?: string[];
|
|
973
|
-
};
|
|
974
|
-
}
|
|
975
|
-
interface VerifyAuthenticationInput {
|
|
976
|
-
/** The `AuthenticationResponseJSON` from `@simplewebauthn/browser`. */
|
|
977
|
-
response: unknown;
|
|
978
|
-
expectedChallenge: string;
|
|
979
|
-
expectedOrigin: string | string[];
|
|
980
|
-
expectedRpId: string;
|
|
981
|
-
requireUserVerification: boolean;
|
|
982
|
-
credential: {
|
|
983
|
-
id: string;
|
|
984
|
-
publicKey: string;
|
|
985
|
-
counter: number;
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
interface VerifiedAuthentication {
|
|
989
|
-
verified: boolean;
|
|
990
|
-
newCounter: number;
|
|
991
|
-
}
|
|
992
|
-
/** The cryptographic boundary — implement over a WebAuthn library. */
|
|
993
|
-
interface WebAuthnVerifier {
|
|
994
|
-
verifyRegistration(input: VerifyRegistrationInput): Promise<VerifiedRegistration>;
|
|
995
|
-
verifyAuthentication(input: VerifyAuthenticationInput): Promise<VerifiedAuthentication>;
|
|
996
|
-
}
|
|
997
|
-
interface PublicKeyParam {
|
|
998
|
-
type: 'public-key';
|
|
999
|
-
alg: number;
|
|
1000
|
-
}
|
|
1001
|
-
interface CredentialDescriptor {
|
|
1002
|
-
type: 'public-key';
|
|
1003
|
-
id: string;
|
|
1004
|
-
transports?: string[];
|
|
1005
|
-
}
|
|
1006
|
-
interface RegistrationOptions {
|
|
1007
|
-
challenge: string;
|
|
1008
|
-
rp: {
|
|
1009
|
-
id: string;
|
|
1010
|
-
name: string;
|
|
1011
|
-
};
|
|
1012
|
-
user: {
|
|
1013
|
-
id: string;
|
|
1014
|
-
name: string;
|
|
1015
|
-
displayName: string;
|
|
1016
|
-
};
|
|
1017
|
-
pubKeyCredParams: PublicKeyParam[];
|
|
1018
|
-
timeout: number;
|
|
1019
|
-
attestation: 'none';
|
|
1020
|
-
excludeCredentials: CredentialDescriptor[];
|
|
1021
|
-
authenticatorSelection: {
|
|
1022
|
-
userVerification: string;
|
|
1023
|
-
residentKey: 'preferred';
|
|
1024
|
-
};
|
|
1025
|
-
}
|
|
1026
|
-
interface AuthenticationOptions {
|
|
1027
|
-
challenge: string;
|
|
1028
|
-
timeout: number;
|
|
1029
|
-
rpId: string;
|
|
1030
|
-
userVerification: string;
|
|
1031
|
-
allowCredentials: CredentialDescriptor[];
|
|
1032
|
-
}
|
|
1033
|
-
declare class WebAuthnChallengeError extends BasaltError {
|
|
1034
|
-
readonly status = 400;
|
|
1035
|
-
constructor();
|
|
1036
|
-
}
|
|
1037
|
-
declare class WebAuthnVerificationError extends BasaltError {
|
|
1038
|
-
readonly status = 400;
|
|
1039
|
-
constructor();
|
|
1040
|
-
}
|
|
1041
|
-
declare class PasskeyNotFoundError extends BasaltError {
|
|
1042
|
-
readonly status = 404;
|
|
1043
|
-
constructor();
|
|
1044
|
-
}
|
|
1045
|
-
declare class PasskeyClonedError extends BasaltError {
|
|
1046
|
-
readonly status = 401;
|
|
1047
|
-
constructor();
|
|
1048
|
-
}
|
|
1049
|
-
interface WebAuthnConfig {
|
|
1050
|
-
/** Relying Party ID — your registrable domain, e.g. 'example.com'. */
|
|
1051
|
-
rpId: string;
|
|
1052
|
-
/** Human-readable RP name shown in the OS prompt. */
|
|
1053
|
-
rpName: string;
|
|
1054
|
-
/** Expected origin(s), e.g. 'https://example.com'. */
|
|
1055
|
-
origin: string | string[];
|
|
1056
|
-
/** Challenge TTL in ms. Default 5 minutes. */
|
|
1057
|
-
challengeTtlMs?: number;
|
|
1058
|
-
/** User-verification requirement. Default 'preferred'. */
|
|
1059
|
-
userVerification?: 'required' | 'preferred' | 'discouraged';
|
|
1060
|
-
/** Ceremony timeout advertised to the browser, ms. Default 60s. */
|
|
1061
|
-
timeoutMs?: number;
|
|
1062
|
-
/** Override the accepted algorithms. Default ES256 + RS256. */
|
|
1063
|
-
pubKeyCredParams?: PublicKeyParam[];
|
|
1064
|
-
}
|
|
1065
|
-
interface WebAuthnServiceOptions {
|
|
1066
|
-
config: WebAuthnConfig;
|
|
1067
|
-
credentials: PasskeyStore;
|
|
1068
|
-
challenges: WebAuthnChallengeStore;
|
|
1069
|
-
verifier: WebAuthnVerifier;
|
|
1070
|
-
now?: () => number;
|
|
1071
|
-
/** Challenge generator (tests). Default: 32 random bytes, base64url. */
|
|
1072
|
-
randomChallenge?: () => string;
|
|
1073
|
-
}
|
|
1074
|
-
declare class WebAuthnService {
|
|
1075
|
-
private readonly config;
|
|
1076
|
-
private readonly credentials;
|
|
1077
|
-
private readonly challenges;
|
|
1078
|
-
private readonly verifier;
|
|
1079
|
-
private readonly now;
|
|
1080
|
-
private readonly randomChallenge;
|
|
1081
|
-
constructor(options: WebAuthnServiceOptions);
|
|
1082
|
-
private get uv();
|
|
1083
|
-
private get timeout();
|
|
1084
|
-
private issueChallenge;
|
|
1085
|
-
/** Registration options for a known user; stores the challenge under `sessionKey`. */
|
|
1086
|
-
startRegistration(sessionKey: string, user: {
|
|
1087
|
-
id: string;
|
|
1088
|
-
name: string;
|
|
1089
|
-
displayName?: string;
|
|
1090
|
-
}): Promise<RegistrationOptions>;
|
|
1091
|
-
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1092
|
-
finishRegistration(sessionKey: string, userId: string, response: unknown, deviceName?: string): Promise<PasskeyCredential>;
|
|
1093
|
-
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1094
|
-
startAuthentication(sessionKey: string, userId?: string): Promise<AuthenticationOptions>;
|
|
1095
|
-
/**
|
|
1096
|
-
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1097
|
-
* the signature counter increased (clone detection), persists the new counter,
|
|
1098
|
-
* and returns whose passkey authenticated. Throws on any failure.
|
|
1099
|
-
*/
|
|
1100
|
-
finishAuthentication(sessionKey: string, response: unknown): Promise<{
|
|
1101
|
-
userId: string;
|
|
1102
|
-
credentialId: string;
|
|
1103
|
-
}>;
|
|
1104
|
-
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1105
|
-
list(userId: string): Promise<PasskeyCredential[]>;
|
|
1106
|
-
/** Remove a passkey (revoke a device). */
|
|
1107
|
-
remove(credentialId: string): Promise<void>;
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
declare const WEBAUTHN: _basaltkit_core.Token<WebAuthnService>;
|
|
1111
|
-
interface WebAuthnPluginOptions {
|
|
1112
|
-
config: WebAuthnConfig;
|
|
1113
|
-
/** The crypto boundary — implement over `@simplewebauthn/server`. Required. */
|
|
1114
|
-
verifier: WebAuthnVerifier;
|
|
1115
|
-
/** Passkey storage. Default: in-memory (swap for a durable store). */
|
|
1116
|
-
credentials?: PasskeyStore;
|
|
1117
|
-
/** Challenge storage. Default: in-memory. */
|
|
1118
|
-
challenges?: WebAuthnChallengeStore;
|
|
1119
|
-
}
|
|
1120
|
-
/** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
|
|
1121
|
-
declare function webauthnPlugin(options: WebAuthnPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
1122
|
-
|
|
1123
|
-
export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, type AuthenticationOptions, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryPasskeyStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MemoryWebAuthnChallengeStore, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, OAUTH, OAuth, OAuthExchangeError, type OAuthOptions, type OAuthPluginOptions, type OAuthProfile, type OAuthProvider, OAuthProviderUnknownError, type OAuthRoutesOptions, OAuthStateInvalidError, type OtpauthUriInput, PasskeyClonedError, type PasskeyCredential, PasskeyNotFoundError, type PasskeyStore, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, type RegistrationOptions, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifiedAuthentication, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifyRegistrationInput, type VerifyTotpOptions, WEBAUTHN, WeakJwtSecretError, WebAuthnChallengeError, type WebAuthnChallengeStore, type WebAuthnConfig, type WebAuthnPluginOptions, WebAuthnService, type WebAuthnServiceOptions, WebAuthnVerificationError, type WebAuthnVerifier, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, discoverOidcProvider, generateTotpSecret, githubProvider, googleProvider, matchTotpStep, mfaRoutes, oauthPlugin, oauthRoutes, oidcProvider, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp, webauthnPlugin };
|
|
1
|
+
export { ScryptPasswordHasher, type PasswordHasher } from './hashing.js';
|
|
2
|
+
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, type JwtClaims, } from './jwt.js';
|
|
3
|
+
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
|
|
4
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type TokenPair, } from './auth.js';
|
|
5
|
+
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
6
|
+
export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
|
|
7
|
+
export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
8
|
+
export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
|
|
9
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
10
|
+
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
11
|
+
export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
|
|
12
|
+
export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
|
|
13
|
+
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, type PasskeyCredential, type StoredChallenge, type PasskeyStore, type WebAuthnChallengeStore, type WebAuthnVerifier, type VerifyRegistrationInput, type VerifiedRegistration, type VerifyAuthenticationInput, type VerifiedAuthentication, type WebAuthnConfig, type WebAuthnServiceOptions, type RegistrationOptions, type AuthenticationOptions, } from './webauthn.js';
|
|
14
|
+
export { webauthnPlugin, WEBAUTHN, type WebAuthnPluginOptions } from './webauthn-plugin.js';
|