@basaltkit/auth 1.6.0 → 1.6.2
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 -1140
- package/dist/index.js +14 -1798
- 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/routes.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { ctx, BasaltError } from '@basaltkit/core';
|
|
2
|
+
import { route } from '@basaltkit/fastify';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { AUTH } from './plugin.js';
|
|
5
|
+
import { API_KEYS } from './apikeys-plugin.js';
|
|
6
|
+
const credentials = z.object({ email: z.string().email(), password: z.string().min(8) });
|
|
7
|
+
const auth = () => ctx().container.get(AUTH);
|
|
8
|
+
const apiKeys = () => ctx().container.get(API_KEYS);
|
|
9
|
+
/**
|
|
10
|
+
* Ready-made auth routes — register them in fastifyPlugin({ routes }):
|
|
11
|
+
* register · login · refresh · logout · me, plus email verification
|
|
12
|
+
* (`/auth/verify/request`, `/auth/verify`) and password reset
|
|
13
|
+
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
14
|
+
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
15
|
+
*/
|
|
16
|
+
export function authRoutes() {
|
|
17
|
+
return [
|
|
18
|
+
route({
|
|
19
|
+
method: 'POST',
|
|
20
|
+
url: '/auth/register',
|
|
21
|
+
body: credentials,
|
|
22
|
+
// Enumeration-safe: the same 202 whether the email is new or already taken
|
|
23
|
+
// (a collision is signalled out-of-band via auth:register_existing_email).
|
|
24
|
+
async handler({ body, reply }) {
|
|
25
|
+
await auth().registerSafely(body.email, body.password);
|
|
26
|
+
return reply.code(202).send({ ok: true });
|
|
27
|
+
},
|
|
28
|
+
}),
|
|
29
|
+
route({
|
|
30
|
+
method: 'POST',
|
|
31
|
+
url: '/auth/login',
|
|
32
|
+
body: credentials.extend({ mfaCode: z.string().optional() }),
|
|
33
|
+
async handler({ body, request }) {
|
|
34
|
+
const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
|
|
35
|
+
return { user, ...tokens };
|
|
36
|
+
},
|
|
37
|
+
}),
|
|
38
|
+
route({
|
|
39
|
+
method: 'POST',
|
|
40
|
+
url: '/auth/refresh',
|
|
41
|
+
body: z.object({ refreshToken: z.string() }),
|
|
42
|
+
async handler({ body }) {
|
|
43
|
+
return auth().refresh(body.refreshToken);
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
route({
|
|
47
|
+
method: 'POST',
|
|
48
|
+
url: '/auth/logout',
|
|
49
|
+
body: z.object({ refreshToken: z.string() }),
|
|
50
|
+
async handler({ body, reply }) {
|
|
51
|
+
await auth().revoke(body.refreshToken);
|
|
52
|
+
return reply.code(204).send();
|
|
53
|
+
},
|
|
54
|
+
}),
|
|
55
|
+
route({
|
|
56
|
+
method: 'GET',
|
|
57
|
+
url: '/auth/me',
|
|
58
|
+
meta: { auth: true },
|
|
59
|
+
async handler() {
|
|
60
|
+
return ctx().user;
|
|
61
|
+
},
|
|
62
|
+
}),
|
|
63
|
+
// --- email verification ------------------------------------------------
|
|
64
|
+
route({
|
|
65
|
+
method: 'POST',
|
|
66
|
+
url: '/auth/verify/request',
|
|
67
|
+
body: z.object({ email: z.string().email() }),
|
|
68
|
+
async handler({ body }) {
|
|
69
|
+
// The app emails the token (via the auth:verify_requested hook). Always
|
|
70
|
+
// 200, so the response never reveals whether the email has an account.
|
|
71
|
+
await auth().requestEmailVerification(body.email);
|
|
72
|
+
return { ok: true };
|
|
73
|
+
},
|
|
74
|
+
}),
|
|
75
|
+
route({
|
|
76
|
+
method: 'POST',
|
|
77
|
+
url: '/auth/verify',
|
|
78
|
+
body: z.object({ token: z.string() }),
|
|
79
|
+
async handler({ body }) {
|
|
80
|
+
return { user: await auth().verifyEmail(body.token) };
|
|
81
|
+
},
|
|
82
|
+
}),
|
|
83
|
+
// --- password reset ----------------------------------------------------
|
|
84
|
+
route({
|
|
85
|
+
method: 'POST',
|
|
86
|
+
url: '/auth/password/forgot',
|
|
87
|
+
body: z.object({ email: z.string().email() }),
|
|
88
|
+
async handler({ body }) {
|
|
89
|
+
await auth().requestPasswordReset(body.email);
|
|
90
|
+
return { ok: true };
|
|
91
|
+
},
|
|
92
|
+
}),
|
|
93
|
+
route({
|
|
94
|
+
method: 'POST',
|
|
95
|
+
url: '/auth/password/reset',
|
|
96
|
+
body: z.object({ token: z.string(), password: z.string().min(8) }),
|
|
97
|
+
async handler({ body }) {
|
|
98
|
+
await auth().resetPassword(body.token, body.password);
|
|
99
|
+
return { ok: true };
|
|
100
|
+
},
|
|
101
|
+
}),
|
|
102
|
+
];
|
|
103
|
+
}
|
|
104
|
+
class ApiKeyForbiddenError extends BasaltError {
|
|
105
|
+
status = 404;
|
|
106
|
+
constructor() {
|
|
107
|
+
super('AUTH_APIKEY_NOT_FOUND', 'API key not found.');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
|
|
112
|
+
* are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
|
|
113
|
+
* ever sees or revokes keys within that scope. Register alongside
|
|
114
|
+
* {@link authRoutes} and pair with `apiKeysPlugin`.
|
|
115
|
+
*/
|
|
116
|
+
export function apiKeyRoutes() {
|
|
117
|
+
// `tenant` is set by @basaltkit/tenancy when present; read it without a hard
|
|
118
|
+
// dependency on that package's type augmentation.
|
|
119
|
+
const scope = () => {
|
|
120
|
+
const c = ctx();
|
|
121
|
+
return {
|
|
122
|
+
...(c.tenant ? { tenantId: c.tenant.id } : {}),
|
|
123
|
+
...(c.user ? { userId: c.user.id } : {}),
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
return [
|
|
127
|
+
route({
|
|
128
|
+
method: 'POST',
|
|
129
|
+
url: '/apikeys',
|
|
130
|
+
meta: { auth: true },
|
|
131
|
+
body: z.object({
|
|
132
|
+
name: z.string().min(1).max(100),
|
|
133
|
+
scopes: z.array(z.string().min(1)).optional(),
|
|
134
|
+
}),
|
|
135
|
+
async handler({ body, reply }) {
|
|
136
|
+
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
|
137
|
+
// `key` is returned exactly once — it is never retrievable again.
|
|
138
|
+
return reply.code(201).send({ ...record, key });
|
|
139
|
+
},
|
|
140
|
+
}),
|
|
141
|
+
route({
|
|
142
|
+
method: 'GET',
|
|
143
|
+
url: '/apikeys',
|
|
144
|
+
meta: { auth: true },
|
|
145
|
+
async handler() {
|
|
146
|
+
return apiKeys().list(scope());
|
|
147
|
+
},
|
|
148
|
+
}),
|
|
149
|
+
route({
|
|
150
|
+
method: 'DELETE',
|
|
151
|
+
url: '/apikeys/:id',
|
|
152
|
+
meta: { auth: true },
|
|
153
|
+
params: z.object({ id: z.string() }),
|
|
154
|
+
async handler({ params, reply }) {
|
|
155
|
+
const record = await apiKeys().get(params.id);
|
|
156
|
+
const { tenantId, userId } = scope();
|
|
157
|
+
// Only expose/act on keys within the caller's scope; otherwise 404.
|
|
158
|
+
if (!record || record.tenantId !== tenantId || record.userId !== userId) {
|
|
159
|
+
throw new ApiKeyForbiddenError();
|
|
160
|
+
}
|
|
161
|
+
await apiKeys().revoke(params.id);
|
|
162
|
+
return reply.code(204).send();
|
|
163
|
+
},
|
|
164
|
+
}),
|
|
165
|
+
];
|
|
166
|
+
}
|
|
167
|
+
class MfaAuthRequiredError extends BasaltError {
|
|
168
|
+
status = 401;
|
|
169
|
+
constructor() {
|
|
170
|
+
super('AUTH_REQUIRED', 'Authentication required.');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const currentUserId = () => {
|
|
174
|
+
const id = ctx().user?.id;
|
|
175
|
+
if (!id)
|
|
176
|
+
throw new MfaAuthRequiredError();
|
|
177
|
+
return id;
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* MFA (TOTP) self-service routes, all requiring a logged-in user: enroll,
|
|
181
|
+
* activate (returns one-time recovery codes), status, and disable. Register
|
|
182
|
+
* alongside {@link authRoutes} and enable MFA at login via the optional
|
|
183
|
+
* `mfaCode` field on `POST /auth/login`.
|
|
184
|
+
*/
|
|
185
|
+
export function mfaRoutes() {
|
|
186
|
+
return [
|
|
187
|
+
route({
|
|
188
|
+
method: 'POST',
|
|
189
|
+
url: '/auth/mfa/enroll',
|
|
190
|
+
meta: { auth: true },
|
|
191
|
+
async handler() {
|
|
192
|
+
return auth().enrollMfa(currentUserId());
|
|
193
|
+
},
|
|
194
|
+
}),
|
|
195
|
+
route({
|
|
196
|
+
method: 'POST',
|
|
197
|
+
url: '/auth/mfa/activate',
|
|
198
|
+
meta: { auth: true },
|
|
199
|
+
body: z.object({ code: z.string().min(6) }),
|
|
200
|
+
async handler({ body }) {
|
|
201
|
+
return auth().activateMfa(currentUserId(), body.code);
|
|
202
|
+
},
|
|
203
|
+
}),
|
|
204
|
+
route({
|
|
205
|
+
method: 'GET',
|
|
206
|
+
url: '/auth/mfa/status',
|
|
207
|
+
meta: { auth: true },
|
|
208
|
+
async handler() {
|
|
209
|
+
return auth().mfaStatus(currentUserId());
|
|
210
|
+
},
|
|
211
|
+
}),
|
|
212
|
+
route({
|
|
213
|
+
method: 'POST',
|
|
214
|
+
url: '/auth/mfa/disable',
|
|
215
|
+
meta: { auth: true },
|
|
216
|
+
body: z.object({ code: z.string().min(6) }),
|
|
217
|
+
async handler({ body, reply }) {
|
|
218
|
+
await auth().disableMfa(currentUserId(), body.code);
|
|
219
|
+
return reply.code(204).send();
|
|
220
|
+
},
|
|
221
|
+
}),
|
|
222
|
+
];
|
|
223
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Derive a 32-byte AES key from an arbitrary-length passphrase/key material. */
|
|
2
|
+
export declare function deriveKey(key: string | Buffer): Buffer;
|
|
3
|
+
/** Encrypt `plaintext` with AES-256-GCM. Returns the `v1:` envelope string. */
|
|
4
|
+
export declare function encryptSecret(plaintext: string, key: Buffer): string;
|
|
5
|
+
/**
|
|
6
|
+
* Decrypt a `v1:` envelope. A value without the prefix is returned unchanged
|
|
7
|
+
* (legacy plaintext, or encryption not configured). Throws if an enveloped
|
|
8
|
+
* value fails authentication (tampering / wrong key).
|
|
9
|
+
*/
|
|
10
|
+
export declare function decryptSecret(value: string, key: Buffer): string;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Authenticated encryption (AES-256-GCM) for secrets stored at rest — used to
|
|
4
|
+
* encrypt TOTP secrets so a database leak doesn't hand the attacker every
|
|
5
|
+
* user's live second factor.
|
|
6
|
+
*
|
|
7
|
+
* The wire format is `v1:<iv>:<tag>:<ciphertext>` (each base64). A value with no
|
|
8
|
+
* `v1:` prefix is treated as legacy plaintext and returned as-is on decrypt, so
|
|
9
|
+
* existing records keep working and get encrypted the next time they're written.
|
|
10
|
+
*/
|
|
11
|
+
const PREFIX = 'v1:';
|
|
12
|
+
/** Derive a 32-byte AES key from an arbitrary-length passphrase/key material. */
|
|
13
|
+
export function deriveKey(key) {
|
|
14
|
+
return createHash('sha256').update(key).digest();
|
|
15
|
+
}
|
|
16
|
+
/** Encrypt `plaintext` with AES-256-GCM. Returns the `v1:` envelope string. */
|
|
17
|
+
export function encryptSecret(plaintext, key) {
|
|
18
|
+
const iv = randomBytes(12);
|
|
19
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
|
20
|
+
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
|
21
|
+
const tag = cipher.getAuthTag();
|
|
22
|
+
return `${PREFIX}${iv.toString('base64')}:${tag.toString('base64')}:${ct.toString('base64')}`;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Decrypt a `v1:` envelope. A value without the prefix is returned unchanged
|
|
26
|
+
* (legacy plaintext, or encryption not configured). Throws if an enveloped
|
|
27
|
+
* value fails authentication (tampering / wrong key).
|
|
28
|
+
*/
|
|
29
|
+
export function decryptSecret(value, key) {
|
|
30
|
+
if (!value.startsWith(PREFIX))
|
|
31
|
+
return value;
|
|
32
|
+
const [, ivB64, tagB64, ctB64] = value.split(':');
|
|
33
|
+
if (!ivB64 || !tagB64 || !ctB64)
|
|
34
|
+
throw new Error('Malformed encrypted secret.');
|
|
35
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64'));
|
|
36
|
+
decipher.setAuthTag(Buffer.from(tagB64, 'base64'));
|
|
37
|
+
return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64')), decipher.final()]).toString('utf8');
|
|
38
|
+
}
|
package/dist/stores.d.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/** The stored user record. Apps map this onto their own user table. */
|
|
2
|
+
export interface AuthUser {
|
|
3
|
+
id: string;
|
|
4
|
+
email: string;
|
|
5
|
+
passwordHash: string;
|
|
6
|
+
emailVerified?: boolean;
|
|
7
|
+
[key: string]: unknown;
|
|
8
|
+
}
|
|
9
|
+
/** What lands in ctx().user — never carries the password hash. */
|
|
10
|
+
export interface PublicUser {
|
|
11
|
+
id: string;
|
|
12
|
+
email: string;
|
|
13
|
+
emailVerified?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/** Fields the email-verification / password-reset flows update on a user. */
|
|
16
|
+
export type UserPatch = Partial<Pick<AuthUser, 'passwordHash' | 'emailVerified'>>;
|
|
17
|
+
export interface UserSource {
|
|
18
|
+
findByEmail(email: string): Promise<AuthUser | null>;
|
|
19
|
+
findById(id: string): Promise<AuthUser | null>;
|
|
20
|
+
create(data: {
|
|
21
|
+
email: string;
|
|
22
|
+
passwordHash: string;
|
|
23
|
+
}): Promise<AuthUser>;
|
|
24
|
+
/** Required for email verification and password reset. Returns the updated user. */
|
|
25
|
+
update?(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
26
|
+
}
|
|
27
|
+
export declare class MemoryUserSource implements UserSource {
|
|
28
|
+
private readonly users;
|
|
29
|
+
findByEmail(email: string): Promise<AuthUser | null>;
|
|
30
|
+
findById(id: string): Promise<AuthUser | null>;
|
|
31
|
+
create(data: {
|
|
32
|
+
email: string;
|
|
33
|
+
passwordHash: string;
|
|
34
|
+
}): Promise<AuthUser>;
|
|
35
|
+
update(id: string, patch: UserPatch): Promise<AuthUser | null>;
|
|
36
|
+
}
|
|
37
|
+
export type AuthTokenPurpose = 'verify_email' | 'reset_password';
|
|
38
|
+
export interface AuthTokenRecord {
|
|
39
|
+
token: string;
|
|
40
|
+
userId: string;
|
|
41
|
+
purpose: AuthTokenPurpose;
|
|
42
|
+
expiresAt: number;
|
|
43
|
+
usedAt?: number;
|
|
44
|
+
}
|
|
45
|
+
/** Stores single-use, expiring tokens for verification and reset flows. */
|
|
46
|
+
export interface AuthTokenStore {
|
|
47
|
+
create(record: AuthTokenRecord): Promise<void>;
|
|
48
|
+
find(token: string): Promise<AuthTokenRecord | null>;
|
|
49
|
+
markUsed(token: string): Promise<void>;
|
|
50
|
+
/** Invalidate outstanding tokens of a purpose for a user before issuing a new one. */
|
|
51
|
+
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
export declare class MemoryAuthTokenStore implements AuthTokenStore {
|
|
54
|
+
private readonly records;
|
|
55
|
+
create(record: AuthTokenRecord): Promise<void>;
|
|
56
|
+
find(token: string): Promise<AuthTokenRecord | null>;
|
|
57
|
+
markUsed(token: string): Promise<void>;
|
|
58
|
+
deleteForUser(userId: string, purpose: AuthTokenPurpose): Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A stored API key. The plaintext key is never persisted — only its SHA-256
|
|
62
|
+
* `hash` (for O(1) lookup) and a short `prefix` (for display in listings).
|
|
63
|
+
*/
|
|
64
|
+
export interface ApiKeyRecord {
|
|
65
|
+
id: string;
|
|
66
|
+
/** Human label, e.g. "CI pipeline". */
|
|
67
|
+
name: string;
|
|
68
|
+
/** Visible portion shown in listings, e.g. `mk_live_ab12cd`. */
|
|
69
|
+
prefix: string;
|
|
70
|
+
/** SHA-256 of the full presented key. */
|
|
71
|
+
hash: string;
|
|
72
|
+
/** Owning tenant, when created inside a tenant context. */
|
|
73
|
+
tenantId?: string;
|
|
74
|
+
/** User who created the key, when created by a logged-in user. */
|
|
75
|
+
userId?: string;
|
|
76
|
+
/** Granted scopes; `*` means all. */
|
|
77
|
+
scopes: string[];
|
|
78
|
+
createdAt: number;
|
|
79
|
+
lastUsedAt?: number;
|
|
80
|
+
revokedAt?: number;
|
|
81
|
+
}
|
|
82
|
+
/** What a listing exposes — never the hash. */
|
|
83
|
+
export type ApiKeyInfo = Omit<ApiKeyRecord, 'hash'>;
|
|
84
|
+
export interface ApiKeyFilter {
|
|
85
|
+
tenantId?: string;
|
|
86
|
+
userId?: string;
|
|
87
|
+
}
|
|
88
|
+
export interface ApiKeyStore {
|
|
89
|
+
create(record: ApiKeyRecord): Promise<void>;
|
|
90
|
+
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
91
|
+
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
92
|
+
/** Active (non-revoked) keys matching the filter. */
|
|
93
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
94
|
+
touch(id: string, at: number): Promise<void>;
|
|
95
|
+
revoke(id: string, at: number): Promise<void>;
|
|
96
|
+
}
|
|
97
|
+
export declare class MemoryApiKeyStore implements ApiKeyStore {
|
|
98
|
+
private readonly records;
|
|
99
|
+
create(record: ApiKeyRecord): Promise<void>;
|
|
100
|
+
findByHash(hash: string): Promise<ApiKeyRecord | null>;
|
|
101
|
+
findById(id: string): Promise<ApiKeyRecord | null>;
|
|
102
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyRecord[]>;
|
|
103
|
+
touch(id: string, at: number): Promise<void>;
|
|
104
|
+
revoke(id: string, at: number): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Per-user MFA state. `secret` is the base32 TOTP secret; `recoveryCodes`
|
|
108
|
+
* holds SHA-256 hashes of single-use backup codes (never the plaintext).
|
|
109
|
+
*/
|
|
110
|
+
export interface MfaRecord {
|
|
111
|
+
secret: string;
|
|
112
|
+
enabled: boolean;
|
|
113
|
+
recoveryCodes: string[];
|
|
114
|
+
/**
|
|
115
|
+
* The last TOTP step (counter) accepted for this user. Codes at a step ≤ this
|
|
116
|
+
* are rejected, so an intercepted 6-digit code cannot be replayed within its
|
|
117
|
+
* validity window (RFC 6238 §5.2). Undefined until the first accepted code.
|
|
118
|
+
*/
|
|
119
|
+
lastUsedStep?: number;
|
|
120
|
+
}
|
|
121
|
+
export interface MfaStore {
|
|
122
|
+
get(userId: string): Promise<MfaRecord | null>;
|
|
123
|
+
set(userId: string, record: MfaRecord): Promise<void>;
|
|
124
|
+
delete(userId: string): Promise<void>;
|
|
125
|
+
}
|
|
126
|
+
export declare class MemoryMfaStore implements MfaStore {
|
|
127
|
+
private readonly records;
|
|
128
|
+
get(userId: string): Promise<MfaRecord | null>;
|
|
129
|
+
set(userId: string, record: MfaRecord): Promise<void>;
|
|
130
|
+
delete(userId: string): Promise<void>;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Per-user access-token version. Access tokens carry the version they were
|
|
134
|
+
* minted at; bumping it (on password reset or an explicit "log out everywhere")
|
|
135
|
+
* invalidates every access token issued before the bump — the missing piece for
|
|
136
|
+
* revoking stateless JWTs before they expire. Opt-in via `authPlugin`.
|
|
137
|
+
*/
|
|
138
|
+
export interface TokenVersionStore {
|
|
139
|
+
/** Current version for the user (0 if never bumped). */
|
|
140
|
+
get(userId: string): Promise<number>;
|
|
141
|
+
/** Bump the version and return the new value. */
|
|
142
|
+
increment(userId: string): Promise<number>;
|
|
143
|
+
}
|
|
144
|
+
export declare class MemoryTokenVersionStore implements TokenVersionStore {
|
|
145
|
+
private readonly versions;
|
|
146
|
+
get(userId: string): Promise<number>;
|
|
147
|
+
increment(userId: string): Promise<number>;
|
|
148
|
+
}
|
|
149
|
+
export interface SessionRecord {
|
|
150
|
+
id: string;
|
|
151
|
+
userId: string;
|
|
152
|
+
expiresAt: number;
|
|
153
|
+
}
|
|
154
|
+
export interface SessionStore {
|
|
155
|
+
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
156
|
+
/** Returns null for unknown or expired sessions. */
|
|
157
|
+
find(id: string): Promise<SessionRecord | null>;
|
|
158
|
+
delete(id: string): Promise<boolean>;
|
|
159
|
+
/**
|
|
160
|
+
* Deletes every session for a user — fired on password reset so a reset logs
|
|
161
|
+
* out all of the user's active sessions, not just token-based clients.
|
|
162
|
+
* Optional so existing stores keep compiling; implement it to close the gap.
|
|
163
|
+
*/
|
|
164
|
+
deleteAllForUser?(userId: string): Promise<void>;
|
|
165
|
+
}
|
|
166
|
+
export declare class MemorySessionStore implements SessionStore {
|
|
167
|
+
private readonly sessions;
|
|
168
|
+
create(userId: string, ttlMs: number): Promise<SessionRecord>;
|
|
169
|
+
find(id: string): Promise<SessionRecord | null>;
|
|
170
|
+
delete(id: string): Promise<boolean>;
|
|
171
|
+
deleteAllForUser(userId: string): Promise<void>;
|
|
172
|
+
}
|
|
173
|
+
export interface RefreshRecord {
|
|
174
|
+
token: string;
|
|
175
|
+
familyId: string;
|
|
176
|
+
userId: string;
|
|
177
|
+
expiresAt: number;
|
|
178
|
+
usedAt?: number;
|
|
179
|
+
}
|
|
180
|
+
export interface RefreshTokenStore {
|
|
181
|
+
create(record: RefreshRecord): Promise<void>;
|
|
182
|
+
find(token: string): Promise<RefreshRecord | null>;
|
|
183
|
+
markUsed(token: string): Promise<void>;
|
|
184
|
+
/** Revokes every token of a family — fired on reuse detection. */
|
|
185
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
186
|
+
/** Revokes every token of a user — fired on password reset. Optional. */
|
|
187
|
+
revokeAllForUser?(userId: string): Promise<void>;
|
|
188
|
+
}
|
|
189
|
+
export declare class MemoryRefreshTokenStore implements RefreshTokenStore {
|
|
190
|
+
private readonly records;
|
|
191
|
+
create(record: RefreshRecord): Promise<void>;
|
|
192
|
+
find(token: string): Promise<RefreshRecord | null>;
|
|
193
|
+
markUsed(token: string): Promise<void>;
|
|
194
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
195
|
+
revokeAllForUser(userId: string): Promise<void>;
|
|
196
|
+
}
|
package/dist/stores.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
/** SHA-256 of a session id — only this is persisted, never the raw cookie value. */
|
|
3
|
+
const hashSessionId = (id) => createHash('sha256').update(id).digest('hex');
|
|
4
|
+
export class MemoryUserSource {
|
|
5
|
+
users = new Map();
|
|
6
|
+
async findByEmail(email) {
|
|
7
|
+
for (const user of this.users.values()) {
|
|
8
|
+
if (user.email === email)
|
|
9
|
+
return user;
|
|
10
|
+
}
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
async findById(id) {
|
|
14
|
+
return this.users.get(id) ?? null;
|
|
15
|
+
}
|
|
16
|
+
async create(data) {
|
|
17
|
+
const user = { id: randomUUID(), emailVerified: false, ...data };
|
|
18
|
+
this.users.set(user.id, user);
|
|
19
|
+
return user;
|
|
20
|
+
}
|
|
21
|
+
async update(id, patch) {
|
|
22
|
+
const user = this.users.get(id);
|
|
23
|
+
if (!user)
|
|
24
|
+
return null;
|
|
25
|
+
Object.assign(user, patch);
|
|
26
|
+
return user;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export class MemoryAuthTokenStore {
|
|
30
|
+
records = new Map();
|
|
31
|
+
async create(record) {
|
|
32
|
+
this.records.set(record.token, record);
|
|
33
|
+
}
|
|
34
|
+
async find(token) {
|
|
35
|
+
return this.records.get(token) ?? null;
|
|
36
|
+
}
|
|
37
|
+
async markUsed(token) {
|
|
38
|
+
const record = this.records.get(token);
|
|
39
|
+
if (record)
|
|
40
|
+
record.usedAt = Date.now();
|
|
41
|
+
}
|
|
42
|
+
async deleteForUser(userId, purpose) {
|
|
43
|
+
for (const [token, record] of this.records) {
|
|
44
|
+
if (record.userId === userId && record.purpose === purpose)
|
|
45
|
+
this.records.delete(token);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export class MemoryApiKeyStore {
|
|
50
|
+
records = new Map();
|
|
51
|
+
async create(record) {
|
|
52
|
+
this.records.set(record.id, record);
|
|
53
|
+
}
|
|
54
|
+
async findByHash(hash) {
|
|
55
|
+
for (const record of this.records.values()) {
|
|
56
|
+
if (record.hash === hash)
|
|
57
|
+
return record;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
async findById(id) {
|
|
62
|
+
return this.records.get(id) ?? null;
|
|
63
|
+
}
|
|
64
|
+
async list(filter) {
|
|
65
|
+
const out = [];
|
|
66
|
+
for (const record of this.records.values()) {
|
|
67
|
+
if (record.revokedAt !== undefined)
|
|
68
|
+
continue;
|
|
69
|
+
if (filter.tenantId !== undefined && record.tenantId !== filter.tenantId)
|
|
70
|
+
continue;
|
|
71
|
+
if (filter.userId !== undefined && record.userId !== filter.userId)
|
|
72
|
+
continue;
|
|
73
|
+
out.push(record);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
async touch(id, at) {
|
|
78
|
+
const record = this.records.get(id);
|
|
79
|
+
if (record)
|
|
80
|
+
record.lastUsedAt = at;
|
|
81
|
+
}
|
|
82
|
+
async revoke(id, at) {
|
|
83
|
+
const record = this.records.get(id);
|
|
84
|
+
if (record)
|
|
85
|
+
record.revokedAt = at;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export class MemoryMfaStore {
|
|
89
|
+
records = new Map();
|
|
90
|
+
async get(userId) {
|
|
91
|
+
return this.records.get(userId) ?? null;
|
|
92
|
+
}
|
|
93
|
+
async set(userId, record) {
|
|
94
|
+
this.records.set(userId, record);
|
|
95
|
+
}
|
|
96
|
+
async delete(userId) {
|
|
97
|
+
this.records.delete(userId);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export class MemoryTokenVersionStore {
|
|
101
|
+
versions = new Map();
|
|
102
|
+
async get(userId) {
|
|
103
|
+
return this.versions.get(userId) ?? 0;
|
|
104
|
+
}
|
|
105
|
+
async increment(userId) {
|
|
106
|
+
const next = (this.versions.get(userId) ?? 0) + 1;
|
|
107
|
+
this.versions.set(userId, next);
|
|
108
|
+
return next;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
export class MemorySessionStore {
|
|
112
|
+
sessions = new Map();
|
|
113
|
+
async create(userId, ttlMs) {
|
|
114
|
+
// Mint a raw id for the client (cookie), but key/store by its hash so a leak
|
|
115
|
+
// of the session table can't be replayed as a live session.
|
|
116
|
+
const rawId = randomBytes(32).toString('base64url');
|
|
117
|
+
const hashed = hashSessionId(rawId);
|
|
118
|
+
const expiresAt = Date.now() + ttlMs;
|
|
119
|
+
this.sessions.set(hashed, { id: hashed, userId, expiresAt });
|
|
120
|
+
return { id: rawId, userId, expiresAt };
|
|
121
|
+
}
|
|
122
|
+
async find(id) {
|
|
123
|
+
const hashed = hashSessionId(id);
|
|
124
|
+
const record = this.sessions.get(hashed);
|
|
125
|
+
if (!record)
|
|
126
|
+
return null;
|
|
127
|
+
if (Date.now() >= record.expiresAt) {
|
|
128
|
+
this.sessions.delete(hashed);
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
// Echo the id the caller queried with (never the stored hash).
|
|
132
|
+
return { id, userId: record.userId, expiresAt: record.expiresAt };
|
|
133
|
+
}
|
|
134
|
+
async delete(id) {
|
|
135
|
+
return this.sessions.delete(hashSessionId(id));
|
|
136
|
+
}
|
|
137
|
+
async deleteAllForUser(userId) {
|
|
138
|
+
for (const [key, record] of this.sessions) {
|
|
139
|
+
if (record.userId === userId)
|
|
140
|
+
this.sessions.delete(key);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export class MemoryRefreshTokenStore {
|
|
145
|
+
records = new Map();
|
|
146
|
+
async create(record) {
|
|
147
|
+
this.records.set(record.token, record);
|
|
148
|
+
}
|
|
149
|
+
async find(token) {
|
|
150
|
+
return this.records.get(token) ?? null;
|
|
151
|
+
}
|
|
152
|
+
async markUsed(token) {
|
|
153
|
+
const record = this.records.get(token);
|
|
154
|
+
if (record)
|
|
155
|
+
record.usedAt = Date.now();
|
|
156
|
+
}
|
|
157
|
+
async revokeFamily(familyId) {
|
|
158
|
+
for (const [token, record] of this.records) {
|
|
159
|
+
if (record.familyId === familyId)
|
|
160
|
+
this.records.delete(token);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async revokeAllForUser(userId) {
|
|
164
|
+
for (const [token, record] of this.records) {
|
|
165
|
+
if (record.userId === userId)
|
|
166
|
+
this.records.delete(token);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { BasaltError } from '@basaltkit/core';
|
|
2
|
+
/** Raised when an identifier has exceeded the failed-login budget. */
|
|
3
|
+
export declare class AccountLockedError extends BasaltError {
|
|
4
|
+
readonly retryAfterMs: number;
|
|
5
|
+
readonly status = 429;
|
|
6
|
+
constructor(retryAfterMs: number);
|
|
7
|
+
}
|
|
8
|
+
export interface LoginThrottleOptions {
|
|
9
|
+
/** Failed attempts allowed within the window. Default 5. */
|
|
10
|
+
maxAttempts?: number;
|
|
11
|
+
/** Rolling window in ms. Default 15 minutes. */
|
|
12
|
+
windowMs?: number;
|
|
13
|
+
/** Injectable clock for tests. */
|
|
14
|
+
clock?: () => number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Brute-force guard: counts failed logins per identifier (email) within a
|
|
18
|
+
* rolling window and locks the account once the budget is spent. A successful
|
|
19
|
+
* login clears the counter. In-memory per process; back it with Redis for a
|
|
20
|
+
* cluster by supplying the same behavior.
|
|
21
|
+
*/
|
|
22
|
+
export declare class LoginThrottle {
|
|
23
|
+
private readonly failures;
|
|
24
|
+
private readonly maxAttempts;
|
|
25
|
+
private readonly windowMs;
|
|
26
|
+
private readonly clock;
|
|
27
|
+
constructor(options?: LoginThrottleOptions);
|
|
28
|
+
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
29
|
+
assertAllowed(key: string): void;
|
|
30
|
+
recordFailure(key: string): void;
|
|
31
|
+
reset(key: string): void;
|
|
32
|
+
}
|