@basaltkit/auth 1.0.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.
- package/LICENSE +21 -0
- package/README.md +335 -0
- package/dist/index.d.ts +622 -0
- package/dist/index.js +1073 -0
- package/package.json +53 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import * as _basaltkit_core from '@basaltkit/core';
|
|
2
|
+
import { BasaltError, DurationInput, HookBus } from '@basaltkit/core';
|
|
3
|
+
import { BasaltRoute } from '@basaltkit/fastify';
|
|
4
|
+
|
|
5
|
+
interface PasswordHasher {
|
|
6
|
+
hash(plain: string): Promise<string>;
|
|
7
|
+
verify(plain: string, hashed: string): Promise<boolean>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Default hasher: scrypt from node:crypto — memory-hard, zero dependencies.
|
|
11
|
+
* An argon2id driver can be swapped in via the same contract (native module,
|
|
12
|
+
* left out of the core install).
|
|
13
|
+
*/
|
|
14
|
+
declare class ScryptPasswordHasher implements PasswordHasher {
|
|
15
|
+
private readonly params;
|
|
16
|
+
constructor(params?: {
|
|
17
|
+
N: number;
|
|
18
|
+
r: number;
|
|
19
|
+
p: number;
|
|
20
|
+
});
|
|
21
|
+
hash(plain: string): Promise<string>;
|
|
22
|
+
verify(plain: string, hashed: string): Promise<boolean>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
declare class TokenInvalidError extends BasaltError {
|
|
26
|
+
readonly status = 401;
|
|
27
|
+
constructor();
|
|
28
|
+
}
|
|
29
|
+
declare class TokenExpiredError extends BasaltError {
|
|
30
|
+
readonly status = 401;
|
|
31
|
+
constructor();
|
|
32
|
+
}
|
|
33
|
+
interface JwtClaims {
|
|
34
|
+
sub: string;
|
|
35
|
+
iat: number;
|
|
36
|
+
exp?: number;
|
|
37
|
+
[claim: string]: unknown;
|
|
38
|
+
}
|
|
39
|
+
/** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
|
|
40
|
+
declare function signJwt(claims: Record<string, unknown> & {
|
|
41
|
+
sub: string;
|
|
42
|
+
}, options: {
|
|
43
|
+
secret: string;
|
|
44
|
+
expiresIn?: DurationInput;
|
|
45
|
+
}): string;
|
|
46
|
+
/** Verifies signature and expiry; returns the claims. */
|
|
47
|
+
declare function verifyJwt(token: string, secret: string): JwtClaims;
|
|
48
|
+
|
|
49
|
+
/** The stored user record. Apps map this onto their own user table. */
|
|
50
|
+
interface AuthUser {
|
|
51
|
+
id: string;
|
|
52
|
+
email: string;
|
|
53
|
+
passwordHash: string;
|
|
54
|
+
emailVerified?: boolean;
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
}
|
|
57
|
+
/** What lands in ctx().user — never carries the password hash. */
|
|
58
|
+
interface PublicUser {
|
|
59
|
+
id: string;
|
|
60
|
+
email: string;
|
|
61
|
+
emailVerified?: boolean;
|
|
62
|
+
}
|
|
63
|
+
/** Fields the email-verification / password-reset flows update on a user. */
|
|
64
|
+
type UserPatch = Partial<Pick<AuthUser, 'passwordHash' | 'emailVerified'>>;
|
|
65
|
+
interface UserSource {
|
|
66
|
+
findByEmail(email: string): Promise<AuthUser | null>;
|
|
67
|
+
findById(id: string): Promise<AuthUser | null>;
|
|
68
|
+
create(data: {
|
|
69
|
+
email: string;
|
|
70
|
+
passwordHash: string;
|
|
71
|
+
}): Promise<AuthUser>;
|
|
72
|
+
/** Required for email verification and password reset. Returns the updated user. */
|
|
73
|
+
update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
74
|
+
}
|
|
75
|
+
declare class MemoryUserSource implements UserSource {
|
|
76
|
+
private readonly users;
|
|
77
|
+
findByEmail(email: string): Promise<AuthUser | null>;
|
|
78
|
+
findById(id: string): Promise<AuthUser | null>;
|
|
79
|
+
create(data: {
|
|
80
|
+
email: string;
|
|
81
|
+
passwordHash: string;
|
|
82
|
+
}): Promise<AuthUser>;
|
|
83
|
+
update(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
84
|
+
}
|
|
85
|
+
type AuthTokenPurpose = 'verify_email' | 'reset_password';
|
|
86
|
+
interface AuthTokenRecord {
|
|
87
|
+
token: string;
|
|
88
|
+
userId: string;
|
|
89
|
+
purpose: AuthTokenPurpose;
|
|
90
|
+
expiresAt: number;
|
|
91
|
+
usedAt?: number;
|
|
92
|
+
}
|
|
93
|
+
/** Stores single-use, expiring tokens for verification and reset flows. */
|
|
94
|
+
interface AuthTokenStore {
|
|
95
|
+
create(record: AuthTokenRecord): Promise<void>;
|
|
96
|
+
find(token: string): Promise<AuthTokenRecord | null>;
|
|
97
|
+
markUsed(token: string): Promise<void>;
|
|
98
|
+
/** Invalidate outstanding tokens of a purpose for a user before issuing a new one. */
|
|
99
|
+
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
100
|
+
}
|
|
101
|
+
declare class MemoryAuthTokenStore implements AuthTokenStore {
|
|
102
|
+
private readonly records;
|
|
103
|
+
create(record: AuthTokenRecord): Promise<void>;
|
|
104
|
+
find(token: string): Promise<AuthTokenRecord | null>;
|
|
105
|
+
markUsed(token: string): Promise<void>;
|
|
106
|
+
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A stored API key. The plaintext key is never persisted — only its SHA-256
|
|
110
|
+
* `hash` (for O(1) lookup) and a short `prefix` (for display in listings).
|
|
111
|
+
*/
|
|
112
|
+
interface ApiKeyRecord {
|
|
113
|
+
id: string;
|
|
114
|
+
/** Human label, e.g. "CI pipeline". */
|
|
115
|
+
name: string;
|
|
116
|
+
/** Visible portion shown in listings, e.g. `mk_live_ab12cd`. */
|
|
117
|
+
prefix: string;
|
|
118
|
+
/** SHA-256 of the full presented key. */
|
|
119
|
+
hash: string;
|
|
120
|
+
/** Owning tenant, when created inside a tenant context. */
|
|
121
|
+
tenantId?: string;
|
|
122
|
+
/** User who created the key, when created by a logged-in user. */
|
|
123
|
+
userId?: string;
|
|
124
|
+
/** Granted scopes; `*` means all. */
|
|
125
|
+
scopes: string[];
|
|
126
|
+
createdAt: number;
|
|
127
|
+
lastUsedAt?: number;
|
|
128
|
+
revokedAt?: number;
|
|
129
|
+
}
|
|
130
|
+
/** What a listing exposes — never the hash. */
|
|
131
|
+
type ApiKeyInfo = Omit<ApiKeyRecord, 'hash'>;
|
|
132
|
+
interface ApiKeyFilter {
|
|
133
|
+
tenantId?: string;
|
|
134
|
+
userId?: string;
|
|
135
|
+
}
|
|
136
|
+
interface ApiKeyStore {
|
|
137
|
+
create(record: ApiKeyRecord): Promise<void>;
|
|
138
|
+
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
139
|
+
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
140
|
+
/** Active (non-revoked) keys matching the filter. */
|
|
141
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
142
|
+
touch(id: string, at: number): Promise<void>;
|
|
143
|
+
revoke(id: string, at: number): Promise<void>;
|
|
144
|
+
}
|
|
145
|
+
declare class MemoryApiKeyStore implements ApiKeyStore {
|
|
146
|
+
private readonly records;
|
|
147
|
+
create(record: ApiKeyRecord): Promise<void>;
|
|
148
|
+
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
149
|
+
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
150
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
151
|
+
touch(id: string, at: number): Promise<void>;
|
|
152
|
+
revoke(id: string, at: number): Promise<void>;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Per-user MFA state. `secret` is the base32 TOTP secret; `recoveryCodes`
|
|
156
|
+
* holds SHA-256 hashes of single-use backup codes (never the plaintext).
|
|
157
|
+
*/
|
|
158
|
+
interface MfaRecord {
|
|
159
|
+
secret: string;
|
|
160
|
+
enabled: boolean;
|
|
161
|
+
recoveryCodes: string[];
|
|
162
|
+
}
|
|
163
|
+
interface MfaStore {
|
|
164
|
+
get(userId: string): Promise<MfaRecord | null>;
|
|
165
|
+
set(userId: string, record: MfaRecord): Promise<void>;
|
|
166
|
+
delete(userId: string): Promise<void>;
|
|
167
|
+
}
|
|
168
|
+
declare class MemoryMfaStore implements MfaStore {
|
|
169
|
+
private readonly records;
|
|
170
|
+
get(userId: string): Promise<MfaRecord | null>;
|
|
171
|
+
set(userId: string, record: MfaRecord): Promise<void>;
|
|
172
|
+
delete(userId: string): Promise<void>;
|
|
173
|
+
}
|
|
174
|
+
interface SessionRecord {
|
|
175
|
+
id: string;
|
|
176
|
+
userId: string;
|
|
177
|
+
expiresAt: number;
|
|
178
|
+
}
|
|
179
|
+
interface SessionStore {
|
|
180
|
+
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
181
|
+
/** Returns null for unknown or expired sessions. */
|
|
182
|
+
find(id: string): Promise<SessionRecord | null>;
|
|
183
|
+
delete(id: string): Promise<boolean>;
|
|
184
|
+
}
|
|
185
|
+
declare class MemorySessionStore implements SessionStore {
|
|
186
|
+
private readonly sessions;
|
|
187
|
+
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
188
|
+
find(id: string): Promise<SessionRecord | null>;
|
|
189
|
+
delete(id: string): Promise<boolean>;
|
|
190
|
+
}
|
|
191
|
+
interface RefreshRecord {
|
|
192
|
+
token: string;
|
|
193
|
+
familyId: string;
|
|
194
|
+
userId: string;
|
|
195
|
+
expiresAt: number;
|
|
196
|
+
usedAt?: number;
|
|
197
|
+
}
|
|
198
|
+
interface RefreshTokenStore {
|
|
199
|
+
create(record: RefreshRecord): Promise<void>;
|
|
200
|
+
find(token: string): Promise<RefreshRecord | null>;
|
|
201
|
+
markUsed(token: string): Promise<void>;
|
|
202
|
+
/** Revokes every token of a family — fired on reuse detection. */
|
|
203
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
204
|
+
/** Revokes every token of a user — fired on password reset. Optional. */
|
|
205
|
+
revokeAllForUser?(userId: string): Promise<void>;
|
|
206
|
+
}
|
|
207
|
+
declare class MemoryRefreshTokenStore implements RefreshTokenStore {
|
|
208
|
+
private readonly records;
|
|
209
|
+
create(record: RefreshRecord): Promise<void>;
|
|
210
|
+
find(token: string): Promise<RefreshRecord | null>;
|
|
211
|
+
markUsed(token: string): Promise<void>;
|
|
212
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
213
|
+
revokeAllForUser(userId: string): Promise<void>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Raised when an identifier has exceeded the failed-login budget. */
|
|
217
|
+
declare class AccountLockedError extends BasaltError {
|
|
218
|
+
readonly retryAfterMs: number;
|
|
219
|
+
readonly status = 429;
|
|
220
|
+
constructor(retryAfterMs: number);
|
|
221
|
+
}
|
|
222
|
+
interface LoginThrottleOptions {
|
|
223
|
+
/** Failed attempts allowed within the window. Default 5. */
|
|
224
|
+
maxAttempts?: number;
|
|
225
|
+
/** Rolling window in ms. Default 15 minutes. */
|
|
226
|
+
windowMs?: number;
|
|
227
|
+
/** Injectable clock for tests. */
|
|
228
|
+
clock?: () => number;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Brute-force guard: counts failed logins per identifier (email) within a
|
|
232
|
+
* rolling window and locks the account once the budget is spent. A successful
|
|
233
|
+
* login clears the counter. In-memory per process; back it with Redis for a
|
|
234
|
+
* cluster by supplying the same behavior.
|
|
235
|
+
*/
|
|
236
|
+
declare class LoginThrottle {
|
|
237
|
+
private readonly failures;
|
|
238
|
+
private readonly maxAttempts;
|
|
239
|
+
private readonly windowMs;
|
|
240
|
+
private readonly clock;
|
|
241
|
+
constructor(options?: LoginThrottleOptions);
|
|
242
|
+
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
243
|
+
assertAllowed(key: string): void;
|
|
244
|
+
recordFailure(key: string): void;
|
|
245
|
+
reset(key: string): void;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
declare class InvalidCredentialsError extends BasaltError {
|
|
249
|
+
readonly status = 401;
|
|
250
|
+
constructor();
|
|
251
|
+
}
|
|
252
|
+
declare class EmailTakenError extends BasaltError {
|
|
253
|
+
readonly status = 409;
|
|
254
|
+
constructor();
|
|
255
|
+
}
|
|
256
|
+
declare class RefreshInvalidError extends BasaltError {
|
|
257
|
+
readonly status = 401;
|
|
258
|
+
constructor();
|
|
259
|
+
}
|
|
260
|
+
/** A used refresh token came back — the whole family is revoked. */
|
|
261
|
+
declare class RefreshReusedError extends BasaltError {
|
|
262
|
+
readonly status = 401;
|
|
263
|
+
constructor();
|
|
264
|
+
}
|
|
265
|
+
declare class AuthRequiredError extends BasaltError {
|
|
266
|
+
readonly status = 401;
|
|
267
|
+
constructor();
|
|
268
|
+
}
|
|
269
|
+
/** A verification / reset token was unknown, already used, or expired. */
|
|
270
|
+
declare class AuthTokenInvalidError extends BasaltError {
|
|
271
|
+
readonly status = 400;
|
|
272
|
+
constructor();
|
|
273
|
+
}
|
|
274
|
+
/** The configured UserSource can't be updated (needed for verification/reset). */
|
|
275
|
+
declare class UserUpdateUnsupportedError extends BasaltError {
|
|
276
|
+
readonly status = 500;
|
|
277
|
+
constructor();
|
|
278
|
+
}
|
|
279
|
+
/** Credentials were correct but the account has MFA — a code is required. */
|
|
280
|
+
declare class MfaRequiredError extends BasaltError {
|
|
281
|
+
readonly status = 401;
|
|
282
|
+
constructor();
|
|
283
|
+
}
|
|
284
|
+
/** The supplied MFA (or recovery) code was wrong. */
|
|
285
|
+
declare class MfaInvalidCodeError extends BasaltError {
|
|
286
|
+
readonly status = 401;
|
|
287
|
+
constructor();
|
|
288
|
+
}
|
|
289
|
+
/** An MFA action needed an enrollment that doesn't exist. */
|
|
290
|
+
declare class MfaNotEnrolledError extends BasaltError {
|
|
291
|
+
readonly status = 400;
|
|
292
|
+
constructor();
|
|
293
|
+
}
|
|
294
|
+
interface TokenPair {
|
|
295
|
+
accessToken: string;
|
|
296
|
+
refreshToken: string;
|
|
297
|
+
}
|
|
298
|
+
interface AuthOptions {
|
|
299
|
+
users: UserSource;
|
|
300
|
+
secret: string;
|
|
301
|
+
hasher?: PasswordHasher;
|
|
302
|
+
sessions?: SessionStore;
|
|
303
|
+
refreshTokens?: RefreshTokenStore;
|
|
304
|
+
accessTtl?: DurationInput;
|
|
305
|
+
refreshTtl?: DurationInput;
|
|
306
|
+
sessionTtl?: DurationInput;
|
|
307
|
+
hooks?: HookBus;
|
|
308
|
+
/** Brute-force lockout. Enabled by default; pass `false` to disable. */
|
|
309
|
+
loginThrottle?: LoginThrottle | false;
|
|
310
|
+
/** Store for verification/reset tokens. Default: in-memory. */
|
|
311
|
+
tokens?: AuthTokenStore;
|
|
312
|
+
/** Email-verification link lifetime. Default 24h. */
|
|
313
|
+
verificationTtl?: DurationInput;
|
|
314
|
+
/** Password-reset link lifetime. Default 1h. */
|
|
315
|
+
resetTtl?: DurationInput;
|
|
316
|
+
/** Store for MFA (TOTP) enrollment state. Default: in-memory. */
|
|
317
|
+
mfa?: MfaStore;
|
|
318
|
+
/** Issuer name shown in authenticator apps. Default 'Basalt'. */
|
|
319
|
+
mfaIssuer?: string;
|
|
320
|
+
}
|
|
321
|
+
declare const publicUser: (user: AuthUser) => PublicUser;
|
|
322
|
+
declare class Auth {
|
|
323
|
+
readonly users: UserSource;
|
|
324
|
+
private readonly hasher;
|
|
325
|
+
private readonly sessions;
|
|
326
|
+
private readonly refreshTokens;
|
|
327
|
+
private readonly secret;
|
|
328
|
+
private readonly accessTtl;
|
|
329
|
+
private readonly refreshTtl;
|
|
330
|
+
private readonly sessionTtl;
|
|
331
|
+
private readonly hooks;
|
|
332
|
+
private readonly throttle;
|
|
333
|
+
private readonly tokens;
|
|
334
|
+
private readonly verificationTtl;
|
|
335
|
+
private readonly resetTtl;
|
|
336
|
+
private readonly mfa;
|
|
337
|
+
private readonly mfaIssuer;
|
|
338
|
+
constructor(options: AuthOptions);
|
|
339
|
+
register(email: string, password: string): Promise<PublicUser>;
|
|
340
|
+
/** Verifies credentials without side effects. Null on failure. */
|
|
341
|
+
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
342
|
+
/**
|
|
343
|
+
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
344
|
+
* account after too many failures (see {@link LoginThrottle}); a success
|
|
345
|
+
* clears the counter.
|
|
346
|
+
*
|
|
347
|
+
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
348
|
+
* required: a correct password with a missing code throws
|
|
349
|
+
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
350
|
+
* wrong code throws {@link MfaInvalidCodeError}.
|
|
351
|
+
*/
|
|
352
|
+
login(email: string, password: string, mfaCode?: string): Promise<{
|
|
353
|
+
user: PublicUser;
|
|
354
|
+
tokens: TokenPair;
|
|
355
|
+
}>;
|
|
356
|
+
/**
|
|
357
|
+
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
358
|
+
* and issues a new one in the same family. If a consumed token comes back
|
|
359
|
+
* (theft indicator), the whole family is revoked.
|
|
360
|
+
*/
|
|
361
|
+
refresh(refreshToken: string): Promise<TokenPair>;
|
|
362
|
+
/** Revokes a refresh family — logout for token-based clients. */
|
|
363
|
+
revoke(refreshToken: string): Promise<void>;
|
|
364
|
+
verifyAccess(accessToken: string): JwtClaims;
|
|
365
|
+
createSession(userId: string): Promise<SessionRecord>;
|
|
366
|
+
sessionUser(sessionId: string): Promise<AuthUser | null>;
|
|
367
|
+
logout(sessionId: string): Promise<void>;
|
|
368
|
+
/**
|
|
369
|
+
* Starts email verification: mints a single-use token and emits
|
|
370
|
+
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
371
|
+
* caller can build the link) or null if no account matches — never reveals
|
|
372
|
+
* whether the email exists.
|
|
373
|
+
*/
|
|
374
|
+
requestEmailVerification(email: string): Promise<{
|
|
375
|
+
user: PublicUser;
|
|
376
|
+
token: string;
|
|
377
|
+
} | null>;
|
|
378
|
+
/** Consumes a verification token and marks the user's email verified. */
|
|
379
|
+
verifyEmail(token: string): Promise<PublicUser>;
|
|
380
|
+
/**
|
|
381
|
+
* Starts a password reset: mints a single-use token and emits
|
|
382
|
+
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
383
|
+
* the caller always responds 200 (no account enumeration).
|
|
384
|
+
*/
|
|
385
|
+
requestPasswordReset(email: string): Promise<{
|
|
386
|
+
user: PublicUser;
|
|
387
|
+
token: string;
|
|
388
|
+
} | null>;
|
|
389
|
+
/**
|
|
390
|
+
* Consumes a reset token, sets the new password, and revokes every existing
|
|
391
|
+
* session/refresh token for the user (a reset logs everyone else out).
|
|
392
|
+
*/
|
|
393
|
+
resetPassword(token: string, newPassword: string): Promise<PublicUser>;
|
|
394
|
+
isMfaEnabled(userId: string): Promise<boolean>;
|
|
395
|
+
mfaStatus(userId: string): Promise<{
|
|
396
|
+
enabled: boolean;
|
|
397
|
+
pending: boolean;
|
|
398
|
+
}>;
|
|
399
|
+
/**
|
|
400
|
+
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
401
|
+
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
402
|
+
* {@link activateMfa} with a code from the app to switch it on.
|
|
403
|
+
*/
|
|
404
|
+
enrollMfa(userId: string): Promise<{
|
|
405
|
+
secret: string;
|
|
406
|
+
otpauthUri: string;
|
|
407
|
+
}>;
|
|
408
|
+
/**
|
|
409
|
+
* Confirms enrollment by checking a code against the pending secret, enables
|
|
410
|
+
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
411
|
+
*/
|
|
412
|
+
activateMfa(userId: string, code: string): Promise<{
|
|
413
|
+
recoveryCodes: string[];
|
|
414
|
+
}>;
|
|
415
|
+
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
416
|
+
disableMfa(userId: string, code: string): Promise<void>;
|
|
417
|
+
/**
|
|
418
|
+
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
419
|
+
* is consumed on success). Returns false unless MFA is enabled.
|
|
420
|
+
*/
|
|
421
|
+
verifyMfaCode(userId: string, code: string): Promise<boolean>;
|
|
422
|
+
private generateRecoveryCode;
|
|
423
|
+
private hashRecoveryCode;
|
|
424
|
+
private issueOneTimeToken;
|
|
425
|
+
private consumeToken;
|
|
426
|
+
private updateUser;
|
|
427
|
+
private issueTokens;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** RFC 4648 base32 encode (no padding, uppercase) — the format authenticator apps expect. */
|
|
431
|
+
declare function base32Encode(bytes: Uint8Array): string;
|
|
432
|
+
/** RFC 4648 base32 decode — tolerant of lowercase, spaces, and `=` padding. */
|
|
433
|
+
declare function base32Decode(input: string): Buffer;
|
|
434
|
+
/** A fresh, random base32 TOTP secret (default 20 bytes = 160 bits). */
|
|
435
|
+
declare function generateTotpSecret(bytes?: number): string;
|
|
436
|
+
interface TotpOptions {
|
|
437
|
+
/** Seconds per code. Default 30. */
|
|
438
|
+
period?: number;
|
|
439
|
+
/** Code length. Default 6. */
|
|
440
|
+
digits?: number;
|
|
441
|
+
/** Milliseconds since epoch. Default Date.now(). */
|
|
442
|
+
now?: number;
|
|
443
|
+
}
|
|
444
|
+
/** The current TOTP code (RFC 6238) for a base32 secret. */
|
|
445
|
+
declare function totp(secret: string, options?: TotpOptions): string;
|
|
446
|
+
interface VerifyTotpOptions extends TotpOptions {
|
|
447
|
+
/** Accept codes ±`window` steps to absorb clock drift. Default 1. */
|
|
448
|
+
window?: number;
|
|
449
|
+
}
|
|
450
|
+
/** True when `token` matches the TOTP within the allowed time window (constant-time). */
|
|
451
|
+
declare function verifyTotp(secret: string, token: string, options?: VerifyTotpOptions): boolean;
|
|
452
|
+
interface OtpauthUriInput {
|
|
453
|
+
secret: string;
|
|
454
|
+
/** The account label, typically the user's email. */
|
|
455
|
+
account: string;
|
|
456
|
+
/** The issuer shown in the authenticator app. */
|
|
457
|
+
issuer: string;
|
|
458
|
+
digits?: number;
|
|
459
|
+
period?: number;
|
|
460
|
+
}
|
|
461
|
+
/** Builds an `otpauth://totp/...` URI to render as a QR code. */
|
|
462
|
+
declare function otpauthUri(input: OtpauthUriInput): string;
|
|
463
|
+
|
|
464
|
+
declare module '@basaltkit/core' {
|
|
465
|
+
interface RequestContext {
|
|
466
|
+
/** The authenticated user of the current request, set by auth. */
|
|
467
|
+
user?: PublicUser;
|
|
468
|
+
}
|
|
469
|
+
interface BasaltHooks {
|
|
470
|
+
'auth:registered': {
|
|
471
|
+
user: PublicUser;
|
|
472
|
+
};
|
|
473
|
+
'auth:login': {
|
|
474
|
+
user: PublicUser;
|
|
475
|
+
};
|
|
476
|
+
'auth:login_failed': {
|
|
477
|
+
email: string;
|
|
478
|
+
};
|
|
479
|
+
'auth:logout': {
|
|
480
|
+
user: PublicUser;
|
|
481
|
+
};
|
|
482
|
+
/** Email verification requested — the app emails the token as a link. */
|
|
483
|
+
'auth:verify_requested': {
|
|
484
|
+
user: PublicUser;
|
|
485
|
+
token: string;
|
|
486
|
+
};
|
|
487
|
+
'auth:email_verified': {
|
|
488
|
+
user: PublicUser;
|
|
489
|
+
};
|
|
490
|
+
/** Password reset requested — the app emails the token as a link. */
|
|
491
|
+
'auth:password_reset_requested': {
|
|
492
|
+
user: PublicUser;
|
|
493
|
+
token: string;
|
|
494
|
+
};
|
|
495
|
+
'auth:password_reset': {
|
|
496
|
+
user: PublicUser;
|
|
497
|
+
};
|
|
498
|
+
'auth:mfa_enabled': {
|
|
499
|
+
user: PublicUser;
|
|
500
|
+
};
|
|
501
|
+
'auth:mfa_disabled': {
|
|
502
|
+
user: PublicUser;
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
declare const AUTH: _basaltkit_core.Token<Auth>;
|
|
507
|
+
type AuthPluginOptions = Omit<AuthOptions, 'hooks'>;
|
|
508
|
+
declare function authPlugin(options: AuthPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
509
|
+
|
|
510
|
+
/** A route required a scope the presented key does not hold. */
|
|
511
|
+
declare class ScopeRequiredError extends BasaltError {
|
|
512
|
+
readonly status = 403;
|
|
513
|
+
constructor(scope: string);
|
|
514
|
+
}
|
|
515
|
+
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
516
|
+
declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
|
|
517
|
+
interface IssueApiKeyInput {
|
|
518
|
+
name: string;
|
|
519
|
+
scopes?: string[] | undefined;
|
|
520
|
+
tenantId?: string;
|
|
521
|
+
userId?: string;
|
|
522
|
+
}
|
|
523
|
+
interface ApiKeysOptions {
|
|
524
|
+
store?: ApiKeyStore;
|
|
525
|
+
hooks?: HookBus;
|
|
526
|
+
/** Injectable clock — tests and deterministic runs override it. */
|
|
527
|
+
now?: () => number;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
531
|
+
* {@link issue}; only its SHA-256 hash is stored, so a leaked database never
|
|
532
|
+
* yields usable keys.
|
|
533
|
+
*/
|
|
534
|
+
declare class ApiKeys {
|
|
535
|
+
private readonly store;
|
|
536
|
+
private readonly hooks;
|
|
537
|
+
private readonly now;
|
|
538
|
+
constructor(options?: ApiKeysOptions);
|
|
539
|
+
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
540
|
+
issue(input: IssueApiKeyInput): Promise<{
|
|
541
|
+
record: ApiKeyInfo;
|
|
542
|
+
key: string;
|
|
543
|
+
}>;
|
|
544
|
+
/**
|
|
545
|
+
* Resolves a presented key to its record, or null if it's malformed,
|
|
546
|
+
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
547
|
+
*/
|
|
548
|
+
verify(presented: string): Promise<ApiKeyRecord | null>;
|
|
549
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
550
|
+
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
551
|
+
revoke(id: string): Promise<void>;
|
|
552
|
+
/** Reads a single key's public info (used to authorize a revoke). */
|
|
553
|
+
get(id: string): Promise<ApiKeyInfo | null>;
|
|
554
|
+
}
|
|
555
|
+
/** The value stashed on `ctx().apiKey` after a request authenticates with a key. */
|
|
556
|
+
interface ApiKeyContext {
|
|
557
|
+
id: string;
|
|
558
|
+
scopes: string[];
|
|
559
|
+
tenantId?: string;
|
|
560
|
+
userId?: string;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
declare module '@basaltkit/core' {
|
|
564
|
+
interface RequestContext {
|
|
565
|
+
/** Set when the request authenticated with an API key instead of a session. */
|
|
566
|
+
apiKey?: ApiKeyContext;
|
|
567
|
+
}
|
|
568
|
+
interface BasaltHooks {
|
|
569
|
+
'auth:apikey_issued': {
|
|
570
|
+
id: string;
|
|
571
|
+
tenantId?: string;
|
|
572
|
+
userId?: string;
|
|
573
|
+
};
|
|
574
|
+
'auth:apikey_revoked': {
|
|
575
|
+
id: string;
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
declare const API_KEYS: _basaltkit_core.Token<ApiKeys>;
|
|
580
|
+
interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
581
|
+
/**
|
|
582
|
+
* Header carrying the key, besides `Authorization: Bearer mk_...`.
|
|
583
|
+
* Default `x-api-key`.
|
|
584
|
+
*/
|
|
585
|
+
header?: string;
|
|
586
|
+
/**
|
|
587
|
+
* When provided, a key that carries a `userId` also populates `ctx().user`,
|
|
588
|
+
* so scope-guarded routes can read the acting user.
|
|
589
|
+
*/
|
|
590
|
+
users?: UserSource;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
594
|
+
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
595
|
+
* `meta.scopes` on routes. Pair with {@link apiKeyRoutes} for CRUD endpoints.
|
|
596
|
+
*/
|
|
597
|
+
declare function apiKeysPlugin(options?: ApiKeysPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Ready-made auth routes — register them in fastifyPlugin({ routes }):
|
|
601
|
+
* register · login · refresh · logout · me, plus email verification
|
|
602
|
+
* (`/auth/verify/request`, `/auth/verify`) and password reset
|
|
603
|
+
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
604
|
+
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
605
|
+
*/
|
|
606
|
+
declare function authRoutes(): BasaltRoute[];
|
|
607
|
+
/**
|
|
608
|
+
* CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
|
|
609
|
+
* are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
|
|
610
|
+
* ever sees or revokes keys within that scope. Register alongside
|
|
611
|
+
* {@link authRoutes} and pair with `apiKeysPlugin`.
|
|
612
|
+
*/
|
|
613
|
+
declare function apiKeyRoutes(): BasaltRoute[];
|
|
614
|
+
/**
|
|
615
|
+
* MFA (TOTP) self-service routes, all requiring a logged-in user: enroll,
|
|
616
|
+
* activate (returns one-time recovery codes), status, and disable. Register
|
|
617
|
+
* alongside {@link authRoutes} and enable MFA at login via the optional
|
|
618
|
+
* `mfaCode` field on `POST /auth/login`.
|
|
619
|
+
*/
|
|
620
|
+
declare function mfaRoutes(): BasaltRoute[];
|
|
621
|
+
|
|
622
|
+
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, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryUserSource, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, type OtpauthUriInput, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifyTotpOptions, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, generateTotpSecret, mfaRoutes, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp };
|