@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.js
ADDED
|
@@ -0,0 +1,1073 @@
|
|
|
1
|
+
// src/hashing.ts
|
|
2
|
+
import { randomBytes, scrypt, timingSafeEqual } from "crypto";
|
|
3
|
+
import { promisify } from "util";
|
|
4
|
+
var scryptAsync = promisify(scrypt);
|
|
5
|
+
var ScryptPasswordHasher = class {
|
|
6
|
+
constructor(params = { N: 16384, r: 8, p: 1 }) {
|
|
7
|
+
this.params = params;
|
|
8
|
+
}
|
|
9
|
+
params;
|
|
10
|
+
async hash(plain) {
|
|
11
|
+
const salt = randomBytes(16);
|
|
12
|
+
const derived = await scryptAsync(plain, salt, 32, this.params);
|
|
13
|
+
const { N, r, p } = this.params;
|
|
14
|
+
return `scrypt$${N}$${r}$${p}$${salt.toString("base64url")}$${derived.toString("base64url")}`;
|
|
15
|
+
}
|
|
16
|
+
async verify(plain, hashed) {
|
|
17
|
+
const parts = hashed.split("$");
|
|
18
|
+
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
|
19
|
+
const [, n, r, p, salt, expected] = parts;
|
|
20
|
+
const derived = await scryptAsync(plain, Buffer.from(salt, "base64url"), 32, {
|
|
21
|
+
N: Number(n),
|
|
22
|
+
r: Number(r),
|
|
23
|
+
p: Number(p)
|
|
24
|
+
});
|
|
25
|
+
const expectedBuffer = Buffer.from(expected, "base64url");
|
|
26
|
+
return derived.length === expectedBuffer.length && timingSafeEqual(derived, expectedBuffer);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// src/jwt.ts
|
|
31
|
+
import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
32
|
+
import { BasaltError, parseDuration } from "@basaltkit/core";
|
|
33
|
+
var TokenInvalidError = class extends BasaltError {
|
|
34
|
+
status = 401;
|
|
35
|
+
constructor() {
|
|
36
|
+
super("AUTH_TOKEN_INVALID", "The token is invalid.");
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var TokenExpiredError = class extends BasaltError {
|
|
40
|
+
status = 401;
|
|
41
|
+
constructor() {
|
|
42
|
+
super("AUTH_TOKEN_EXPIRED", "The token has expired.");
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
46
|
+
function signJwt(claims, options) {
|
|
47
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
48
|
+
const payload = {
|
|
49
|
+
iat: now,
|
|
50
|
+
...options.expiresIn !== void 0 ? { exp: now + Math.ceil(parseDuration(options.expiresIn) / 1e3) } : {},
|
|
51
|
+
...claims
|
|
52
|
+
};
|
|
53
|
+
const head = encode({ alg: "HS256", typ: "JWT" });
|
|
54
|
+
const body = encode(payload);
|
|
55
|
+
const signature = createHmac("sha256", options.secret).update(`${head}.${body}`).digest("base64url");
|
|
56
|
+
return `${head}.${body}.${signature}`;
|
|
57
|
+
}
|
|
58
|
+
function verifyJwt(token, secret) {
|
|
59
|
+
const parts = token.split(".");
|
|
60
|
+
if (parts.length !== 3) throw new TokenInvalidError();
|
|
61
|
+
const [head, body, signature] = parts;
|
|
62
|
+
const expected = createHmac("sha256", secret).update(`${head}.${body}`).digest();
|
|
63
|
+
const received = Buffer.from(signature, "base64url");
|
|
64
|
+
if (expected.length !== received.length || !timingSafeEqual2(expected, received)) {
|
|
65
|
+
throw new TokenInvalidError();
|
|
66
|
+
}
|
|
67
|
+
let claims;
|
|
68
|
+
try {
|
|
69
|
+
claims = JSON.parse(Buffer.from(body, "base64url").toString());
|
|
70
|
+
} catch {
|
|
71
|
+
throw new TokenInvalidError();
|
|
72
|
+
}
|
|
73
|
+
if (typeof claims.sub !== "string") throw new TokenInvalidError();
|
|
74
|
+
if (claims.exp !== void 0 && claims.exp <= Math.floor(Date.now() / 1e3)) {
|
|
75
|
+
throw new TokenExpiredError();
|
|
76
|
+
}
|
|
77
|
+
return claims;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// src/stores.ts
|
|
81
|
+
import { randomBytes as randomBytes2, randomUUID } from "crypto";
|
|
82
|
+
var MemoryUserSource = class {
|
|
83
|
+
users = /* @__PURE__ */ new Map();
|
|
84
|
+
async findByEmail(email) {
|
|
85
|
+
for (const user of this.users.values()) {
|
|
86
|
+
if (user.email === email) return user;
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
async findById(id) {
|
|
91
|
+
return this.users.get(id) ?? null;
|
|
92
|
+
}
|
|
93
|
+
async create(data) {
|
|
94
|
+
const user = { id: randomUUID(), emailVerified: false, ...data };
|
|
95
|
+
this.users.set(user.id, user);
|
|
96
|
+
return user;
|
|
97
|
+
}
|
|
98
|
+
async update(id, patch) {
|
|
99
|
+
const user = this.users.get(id);
|
|
100
|
+
if (!user) return null;
|
|
101
|
+
Object.assign(user, patch);
|
|
102
|
+
return user;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var MemoryAuthTokenStore = class {
|
|
106
|
+
records = /* @__PURE__ */ new Map();
|
|
107
|
+
async create(record) {
|
|
108
|
+
this.records.set(record.token, record);
|
|
109
|
+
}
|
|
110
|
+
async find(token) {
|
|
111
|
+
return this.records.get(token) ?? null;
|
|
112
|
+
}
|
|
113
|
+
async markUsed(token) {
|
|
114
|
+
const record = this.records.get(token);
|
|
115
|
+
if (record) record.usedAt = Date.now();
|
|
116
|
+
}
|
|
117
|
+
async deleteForUser(userId, purpose) {
|
|
118
|
+
for (const [token, record] of this.records) {
|
|
119
|
+
if (record.userId === userId && record.purpose === purpose) this.records.delete(token);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
var MemoryApiKeyStore = class {
|
|
124
|
+
records = /* @__PURE__ */ new Map();
|
|
125
|
+
async create(record) {
|
|
126
|
+
this.records.set(record.id, record);
|
|
127
|
+
}
|
|
128
|
+
async findByHash(hash) {
|
|
129
|
+
for (const record of this.records.values()) {
|
|
130
|
+
if (record.hash === hash) return record;
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
async findById(id) {
|
|
135
|
+
return this.records.get(id) ?? null;
|
|
136
|
+
}
|
|
137
|
+
async list(filter) {
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const record of this.records.values()) {
|
|
140
|
+
if (record.revokedAt !== void 0) continue;
|
|
141
|
+
if (filter.tenantId !== void 0 && record.tenantId !== filter.tenantId) continue;
|
|
142
|
+
if (filter.userId !== void 0 && record.userId !== filter.userId) continue;
|
|
143
|
+
out.push(record);
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
async touch(id, at) {
|
|
148
|
+
const record = this.records.get(id);
|
|
149
|
+
if (record) record.lastUsedAt = at;
|
|
150
|
+
}
|
|
151
|
+
async revoke(id, at) {
|
|
152
|
+
const record = this.records.get(id);
|
|
153
|
+
if (record) record.revokedAt = at;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
var MemoryMfaStore = class {
|
|
157
|
+
records = /* @__PURE__ */ new Map();
|
|
158
|
+
async get(userId) {
|
|
159
|
+
return this.records.get(userId) ?? null;
|
|
160
|
+
}
|
|
161
|
+
async set(userId, record) {
|
|
162
|
+
this.records.set(userId, record);
|
|
163
|
+
}
|
|
164
|
+
async delete(userId) {
|
|
165
|
+
this.records.delete(userId);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
var MemorySessionStore = class {
|
|
169
|
+
sessions = /* @__PURE__ */ new Map();
|
|
170
|
+
async create(userId, ttlMs) {
|
|
171
|
+
const record = {
|
|
172
|
+
id: randomBytes2(32).toString("base64url"),
|
|
173
|
+
userId,
|
|
174
|
+
expiresAt: Date.now() + ttlMs
|
|
175
|
+
};
|
|
176
|
+
this.sessions.set(record.id, record);
|
|
177
|
+
return record;
|
|
178
|
+
}
|
|
179
|
+
async find(id) {
|
|
180
|
+
const record = this.sessions.get(id);
|
|
181
|
+
if (!record) return null;
|
|
182
|
+
if (Date.now() >= record.expiresAt) {
|
|
183
|
+
this.sessions.delete(id);
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
return record;
|
|
187
|
+
}
|
|
188
|
+
async delete(id) {
|
|
189
|
+
return this.sessions.delete(id);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var MemoryRefreshTokenStore = class {
|
|
193
|
+
records = /* @__PURE__ */ new Map();
|
|
194
|
+
async create(record) {
|
|
195
|
+
this.records.set(record.token, record);
|
|
196
|
+
}
|
|
197
|
+
async find(token) {
|
|
198
|
+
return this.records.get(token) ?? null;
|
|
199
|
+
}
|
|
200
|
+
async markUsed(token) {
|
|
201
|
+
const record = this.records.get(token);
|
|
202
|
+
if (record) record.usedAt = Date.now();
|
|
203
|
+
}
|
|
204
|
+
async revokeFamily(familyId) {
|
|
205
|
+
for (const [token, record] of this.records) {
|
|
206
|
+
if (record.familyId === familyId) this.records.delete(token);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async revokeAllForUser(userId) {
|
|
210
|
+
for (const [token, record] of this.records) {
|
|
211
|
+
if (record.userId === userId) this.records.delete(token);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// src/auth.ts
|
|
217
|
+
import { createHash, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
218
|
+
import { BasaltError as BasaltError3, parseDuration as parseDuration2 } from "@basaltkit/core";
|
|
219
|
+
|
|
220
|
+
// src/throttle.ts
|
|
221
|
+
import { BasaltError as BasaltError2 } from "@basaltkit/core";
|
|
222
|
+
var AccountLockedError = class extends BasaltError2 {
|
|
223
|
+
constructor(retryAfterMs) {
|
|
224
|
+
super(
|
|
225
|
+
"AUTH_LOCKED",
|
|
226
|
+
`Too many failed login attempts. Try again in ${Math.ceil(retryAfterMs / 1e3)}s.`
|
|
227
|
+
);
|
|
228
|
+
this.retryAfterMs = retryAfterMs;
|
|
229
|
+
}
|
|
230
|
+
retryAfterMs;
|
|
231
|
+
status = 429;
|
|
232
|
+
};
|
|
233
|
+
var LoginThrottle = class {
|
|
234
|
+
failures = /* @__PURE__ */ new Map();
|
|
235
|
+
maxAttempts;
|
|
236
|
+
windowMs;
|
|
237
|
+
clock;
|
|
238
|
+
constructor(options = {}) {
|
|
239
|
+
this.maxAttempts = options.maxAttempts ?? 5;
|
|
240
|
+
this.windowMs = options.windowMs ?? 15 * 6e4;
|
|
241
|
+
this.clock = options.clock ?? (() => Date.now());
|
|
242
|
+
}
|
|
243
|
+
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
244
|
+
assertAllowed(key) {
|
|
245
|
+
const entry = this.failures.get(key);
|
|
246
|
+
if (entry && this.clock() < entry.resetAt && entry.count >= this.maxAttempts) {
|
|
247
|
+
throw new AccountLockedError(entry.resetAt - this.clock());
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
recordFailure(key) {
|
|
251
|
+
const now = this.clock();
|
|
252
|
+
let entry = this.failures.get(key);
|
|
253
|
+
if (!entry || now >= entry.resetAt) entry = { count: 0, resetAt: now + this.windowMs };
|
|
254
|
+
entry.count += 1;
|
|
255
|
+
this.failures.set(key, entry);
|
|
256
|
+
}
|
|
257
|
+
reset(key) {
|
|
258
|
+
this.failures.delete(key);
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
// src/totp.ts
|
|
263
|
+
import { createHmac as createHmac2, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
264
|
+
var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
265
|
+
function base32Encode(bytes) {
|
|
266
|
+
let bits = 0;
|
|
267
|
+
let value = 0;
|
|
268
|
+
let out = "";
|
|
269
|
+
for (const byte of bytes) {
|
|
270
|
+
value = value << 8 | byte;
|
|
271
|
+
bits += 8;
|
|
272
|
+
while (bits >= 5) {
|
|
273
|
+
out += BASE32_ALPHABET[value >>> bits - 5 & 31];
|
|
274
|
+
bits -= 5;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
function base32Decode(input) {
|
|
281
|
+
const clean = input.toUpperCase().replace(/[\s=]/g, "");
|
|
282
|
+
let bits = 0;
|
|
283
|
+
let value = 0;
|
|
284
|
+
const out = [];
|
|
285
|
+
for (const char of clean) {
|
|
286
|
+
const idx = BASE32_ALPHABET.indexOf(char);
|
|
287
|
+
if (idx === -1) throw new Error("Invalid base32 character");
|
|
288
|
+
value = value << 5 | idx;
|
|
289
|
+
bits += 5;
|
|
290
|
+
if (bits >= 8) {
|
|
291
|
+
out.push(value >>> bits - 8 & 255);
|
|
292
|
+
bits -= 8;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return Buffer.from(out);
|
|
296
|
+
}
|
|
297
|
+
function generateTotpSecret(bytes = 20) {
|
|
298
|
+
return base32Encode(randomBytes3(bytes));
|
|
299
|
+
}
|
|
300
|
+
function hotp(secret, counter, digits) {
|
|
301
|
+
const buf = Buffer.alloc(8);
|
|
302
|
+
buf.writeUInt32BE(Math.floor(counter / 4294967296), 0);
|
|
303
|
+
buf.writeUInt32BE(counter >>> 0, 4);
|
|
304
|
+
const digest = createHmac2("sha1", secret).update(buf).digest();
|
|
305
|
+
const offset = digest[digest.length - 1] & 15;
|
|
306
|
+
const binary = (digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255;
|
|
307
|
+
return (binary % 10 ** digits).toString().padStart(digits, "0");
|
|
308
|
+
}
|
|
309
|
+
function totp(secret, options = {}) {
|
|
310
|
+
const period = options.period ?? 30;
|
|
311
|
+
const digits = options.digits ?? 6;
|
|
312
|
+
const now = options.now ?? Date.now();
|
|
313
|
+
const counter = Math.floor(now / 1e3 / period);
|
|
314
|
+
return hotp(base32Decode(secret), counter, digits);
|
|
315
|
+
}
|
|
316
|
+
function verifyTotp(secret, token, options = {}) {
|
|
317
|
+
const period = options.period ?? 30;
|
|
318
|
+
const digits = options.digits ?? 6;
|
|
319
|
+
const now = options.now ?? Date.now();
|
|
320
|
+
const window = options.window ?? 1;
|
|
321
|
+
const cleaned = token.replace(/\s/g, "");
|
|
322
|
+
if (cleaned.length !== digits) return false;
|
|
323
|
+
const key = base32Decode(secret);
|
|
324
|
+
const base = Math.floor(now / 1e3 / period);
|
|
325
|
+
let ok = false;
|
|
326
|
+
for (let error = -window; error <= window; error++) {
|
|
327
|
+
const candidate = hotp(key, base + error, digits);
|
|
328
|
+
if (candidate.length === cleaned.length && timingSafeEqual3(Buffer.from(candidate), Buffer.from(cleaned))) {
|
|
329
|
+
ok = true;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return ok;
|
|
333
|
+
}
|
|
334
|
+
function otpauthUri(input) {
|
|
335
|
+
const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;
|
|
336
|
+
const params = new URLSearchParams({
|
|
337
|
+
secret: input.secret,
|
|
338
|
+
issuer: input.issuer,
|
|
339
|
+
algorithm: "SHA1",
|
|
340
|
+
digits: String(input.digits ?? 6),
|
|
341
|
+
period: String(input.period ?? 30)
|
|
342
|
+
});
|
|
343
|
+
return `otpauth://totp/${label}?${params.toString()}`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// src/auth.ts
|
|
347
|
+
var InvalidCredentialsError = class extends BasaltError3 {
|
|
348
|
+
status = 401;
|
|
349
|
+
constructor() {
|
|
350
|
+
super("AUTH_INVALID_CREDENTIALS", "Invalid email or password.");
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
var EmailTakenError = class extends BasaltError3 {
|
|
354
|
+
status = 409;
|
|
355
|
+
constructor() {
|
|
356
|
+
super("AUTH_EMAIL_TAKEN", "An account with this email already exists.");
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
var RefreshInvalidError = class extends BasaltError3 {
|
|
360
|
+
status = 401;
|
|
361
|
+
constructor() {
|
|
362
|
+
super("AUTH_REFRESH_INVALID", "The refresh token is invalid or expired.");
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
var RefreshReusedError = class extends BasaltError3 {
|
|
366
|
+
status = 401;
|
|
367
|
+
constructor() {
|
|
368
|
+
super("AUTH_REFRESH_REUSED", "Refresh token reuse detected. All sessions of this family were revoked.");
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
var AuthRequiredError = class extends BasaltError3 {
|
|
372
|
+
status = 401;
|
|
373
|
+
constructor() {
|
|
374
|
+
super("AUTH_REQUIRED", "Authentication required.");
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
var AuthTokenInvalidError = class extends BasaltError3 {
|
|
378
|
+
status = 400;
|
|
379
|
+
constructor() {
|
|
380
|
+
super("AUTH_TOKEN_INVALID", "The link is invalid or has expired. Request a new one.");
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
var UserUpdateUnsupportedError = class extends BasaltError3 {
|
|
384
|
+
status = 500;
|
|
385
|
+
constructor() {
|
|
386
|
+
super("AUTH_UPDATE_UNSUPPORTED", "The UserSource does not implement update() \u2014 required for this flow.");
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
var MfaRequiredError = class extends BasaltError3 {
|
|
390
|
+
status = 401;
|
|
391
|
+
constructor() {
|
|
392
|
+
super("AUTH_MFA_REQUIRED", "A multi-factor authentication code is required.");
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
var MfaInvalidCodeError = class extends BasaltError3 {
|
|
396
|
+
status = 401;
|
|
397
|
+
constructor() {
|
|
398
|
+
super("AUTH_MFA_INVALID", "The authentication code is incorrect.");
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
var MfaNotEnrolledError = class extends BasaltError3 {
|
|
402
|
+
status = 400;
|
|
403
|
+
constructor() {
|
|
404
|
+
super("AUTH_MFA_NOT_ENROLLED", "No MFA enrollment is in progress for this account.");
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
var publicUser = (user) => ({
|
|
408
|
+
id: user.id,
|
|
409
|
+
email: user.email,
|
|
410
|
+
emailVerified: user.emailVerified ?? false
|
|
411
|
+
});
|
|
412
|
+
var Auth = class {
|
|
413
|
+
users;
|
|
414
|
+
hasher;
|
|
415
|
+
sessions;
|
|
416
|
+
refreshTokens;
|
|
417
|
+
secret;
|
|
418
|
+
accessTtl;
|
|
419
|
+
refreshTtl;
|
|
420
|
+
sessionTtl;
|
|
421
|
+
hooks;
|
|
422
|
+
throttle;
|
|
423
|
+
tokens;
|
|
424
|
+
verificationTtl;
|
|
425
|
+
resetTtl;
|
|
426
|
+
mfa;
|
|
427
|
+
mfaIssuer;
|
|
428
|
+
constructor(options) {
|
|
429
|
+
this.users = options.users;
|
|
430
|
+
this.secret = options.secret;
|
|
431
|
+
this.hasher = options.hasher ?? new ScryptPasswordHasher();
|
|
432
|
+
this.sessions = options.sessions ?? new MemorySessionStore();
|
|
433
|
+
this.refreshTokens = options.refreshTokens ?? new MemoryRefreshTokenStore();
|
|
434
|
+
this.accessTtl = options.accessTtl ?? "15m";
|
|
435
|
+
this.refreshTtl = options.refreshTtl ?? "30d";
|
|
436
|
+
this.sessionTtl = options.sessionTtl ?? "30d";
|
|
437
|
+
this.hooks = options.hooks;
|
|
438
|
+
this.throttle = options.loginThrottle === false ? void 0 : options.loginThrottle ?? new LoginThrottle();
|
|
439
|
+
this.tokens = options.tokens ?? new MemoryAuthTokenStore();
|
|
440
|
+
this.verificationTtl = options.verificationTtl ?? "24h";
|
|
441
|
+
this.resetTtl = options.resetTtl ?? "1h";
|
|
442
|
+
this.mfa = options.mfa ?? new MemoryMfaStore();
|
|
443
|
+
this.mfaIssuer = options.mfaIssuer ?? "Basalt";
|
|
444
|
+
}
|
|
445
|
+
async register(email, password) {
|
|
446
|
+
if (await this.users.findByEmail(email)) throw new EmailTakenError();
|
|
447
|
+
const user = await this.users.create({
|
|
448
|
+
email,
|
|
449
|
+
passwordHash: await this.hasher.hash(password)
|
|
450
|
+
});
|
|
451
|
+
await this.hooks?.emit("auth:registered", { user: publicUser(user) });
|
|
452
|
+
return publicUser(user);
|
|
453
|
+
}
|
|
454
|
+
/** Verifies credentials without side effects. Null on failure. */
|
|
455
|
+
async attempt(email, password) {
|
|
456
|
+
const user = await this.users.findByEmail(email);
|
|
457
|
+
if (!user) return null;
|
|
458
|
+
return await this.hasher.verify(password, user.passwordHash) ? user : null;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
462
|
+
* account after too many failures (see {@link LoginThrottle}); a success
|
|
463
|
+
* clears the counter.
|
|
464
|
+
*
|
|
465
|
+
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
466
|
+
* required: a correct password with a missing code throws
|
|
467
|
+
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
468
|
+
* wrong code throws {@link MfaInvalidCodeError}.
|
|
469
|
+
*/
|
|
470
|
+
async login(email, password, mfaCode) {
|
|
471
|
+
const key = email.toLowerCase();
|
|
472
|
+
this.throttle?.assertAllowed(key);
|
|
473
|
+
const user = await this.attempt(email, password);
|
|
474
|
+
if (!user) {
|
|
475
|
+
this.throttle?.recordFailure(key);
|
|
476
|
+
await this.hooks?.emit("auth:login_failed", { email });
|
|
477
|
+
throw new InvalidCredentialsError();
|
|
478
|
+
}
|
|
479
|
+
if (await this.isMfaEnabled(user.id)) {
|
|
480
|
+
if (!mfaCode) throw new MfaRequiredError();
|
|
481
|
+
if (!await this.verifyMfaCode(user.id, mfaCode)) {
|
|
482
|
+
this.throttle?.recordFailure(key);
|
|
483
|
+
throw new MfaInvalidCodeError();
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
this.throttle?.reset(key);
|
|
487
|
+
const tokens = await this.issueTokens(user.id);
|
|
488
|
+
await this.hooks?.emit("auth:login", { user: publicUser(user) });
|
|
489
|
+
return { user: publicUser(user), tokens };
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
493
|
+
* and issues a new one in the same family. If a consumed token comes back
|
|
494
|
+
* (theft indicator), the whole family is revoked.
|
|
495
|
+
*/
|
|
496
|
+
async refresh(refreshToken) {
|
|
497
|
+
const record = await this.refreshTokens.find(refreshToken);
|
|
498
|
+
if (!record) throw new RefreshInvalidError();
|
|
499
|
+
if (record.usedAt !== void 0) {
|
|
500
|
+
await this.refreshTokens.revokeFamily(record.familyId);
|
|
501
|
+
throw new RefreshReusedError();
|
|
502
|
+
}
|
|
503
|
+
if (Date.now() >= record.expiresAt) throw new RefreshInvalidError();
|
|
504
|
+
await this.refreshTokens.markUsed(refreshToken);
|
|
505
|
+
return this.issueTokens(record.userId, record.familyId);
|
|
506
|
+
}
|
|
507
|
+
/** Revokes a refresh family — logout for token-based clients. */
|
|
508
|
+
async revoke(refreshToken) {
|
|
509
|
+
const record = await this.refreshTokens.find(refreshToken);
|
|
510
|
+
if (record) await this.refreshTokens.revokeFamily(record.familyId);
|
|
511
|
+
}
|
|
512
|
+
verifyAccess(accessToken) {
|
|
513
|
+
return verifyJwt(accessToken, this.secret);
|
|
514
|
+
}
|
|
515
|
+
async createSession(userId) {
|
|
516
|
+
return this.sessions.create(userId, parseDuration2(this.sessionTtl));
|
|
517
|
+
}
|
|
518
|
+
async sessionUser(sessionId) {
|
|
519
|
+
const session = await this.sessions.find(sessionId);
|
|
520
|
+
return session ? this.users.findById(session.userId) : null;
|
|
521
|
+
}
|
|
522
|
+
async logout(sessionId) {
|
|
523
|
+
const session = await this.sessions.find(sessionId);
|
|
524
|
+
await this.sessions.delete(sessionId);
|
|
525
|
+
if (session) {
|
|
526
|
+
const user = await this.users.findById(session.userId);
|
|
527
|
+
if (user) await this.hooks?.emit("auth:logout", { user: publicUser(user) });
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
// --- email verification --------------------------------------------------
|
|
531
|
+
/**
|
|
532
|
+
* Starts email verification: mints a single-use token and emits
|
|
533
|
+
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
534
|
+
* caller can build the link) or null if no account matches — never reveals
|
|
535
|
+
* whether the email exists.
|
|
536
|
+
*/
|
|
537
|
+
async requestEmailVerification(email) {
|
|
538
|
+
const user = await this.users.findByEmail(email);
|
|
539
|
+
if (!user) return null;
|
|
540
|
+
const token = await this.issueOneTimeToken(user.id, "verify_email", this.verificationTtl);
|
|
541
|
+
await this.hooks?.emit("auth:verify_requested", { user: publicUser(user), token });
|
|
542
|
+
return { user: publicUser(user), token };
|
|
543
|
+
}
|
|
544
|
+
/** Consumes a verification token and marks the user's email verified. */
|
|
545
|
+
async verifyEmail(token) {
|
|
546
|
+
const record = await this.consumeToken(token, "verify_email");
|
|
547
|
+
const user = await this.updateUser(record.userId, { emailVerified: true });
|
|
548
|
+
await this.hooks?.emit("auth:email_verified", { user: publicUser(user) });
|
|
549
|
+
return publicUser(user);
|
|
550
|
+
}
|
|
551
|
+
// --- password reset ------------------------------------------------------
|
|
552
|
+
/**
|
|
553
|
+
* Starts a password reset: mints a single-use token and emits
|
|
554
|
+
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
555
|
+
* the caller always responds 200 (no account enumeration).
|
|
556
|
+
*/
|
|
557
|
+
async requestPasswordReset(email) {
|
|
558
|
+
const user = await this.users.findByEmail(email);
|
|
559
|
+
if (!user) return null;
|
|
560
|
+
const token = await this.issueOneTimeToken(user.id, "reset_password", this.resetTtl);
|
|
561
|
+
await this.hooks?.emit("auth:password_reset_requested", { user: publicUser(user), token });
|
|
562
|
+
return { user: publicUser(user), token };
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* Consumes a reset token, sets the new password, and revokes every existing
|
|
566
|
+
* session/refresh token for the user (a reset logs everyone else out).
|
|
567
|
+
*/
|
|
568
|
+
async resetPassword(token, newPassword) {
|
|
569
|
+
const record = await this.consumeToken(token, "reset_password");
|
|
570
|
+
const user = await this.updateUser(record.userId, {
|
|
571
|
+
passwordHash: await this.hasher.hash(newPassword)
|
|
572
|
+
});
|
|
573
|
+
await this.refreshTokens.revokeAllForUser?.(user.id);
|
|
574
|
+
await this.hooks?.emit("auth:password_reset", { user: publicUser(user) });
|
|
575
|
+
return publicUser(user);
|
|
576
|
+
}
|
|
577
|
+
// --- MFA (TOTP) ----------------------------------------------------------
|
|
578
|
+
async isMfaEnabled(userId) {
|
|
579
|
+
return (await this.mfa.get(userId))?.enabled ?? false;
|
|
580
|
+
}
|
|
581
|
+
async mfaStatus(userId) {
|
|
582
|
+
const record = await this.mfa.get(userId);
|
|
583
|
+
return { enabled: record?.enabled ?? false, pending: record !== null && !record.enabled };
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
587
|
+
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
588
|
+
* {@link activateMfa} with a code from the app to switch it on.
|
|
589
|
+
*/
|
|
590
|
+
async enrollMfa(userId) {
|
|
591
|
+
const user = await this.users.findById(userId);
|
|
592
|
+
if (!user) throw new AuthRequiredError();
|
|
593
|
+
const secret = generateTotpSecret();
|
|
594
|
+
await this.mfa.set(userId, { secret, enabled: false, recoveryCodes: [] });
|
|
595
|
+
return {
|
|
596
|
+
secret,
|
|
597
|
+
otpauthUri: otpauthUri({ secret, account: user.email, issuer: this.mfaIssuer })
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Confirms enrollment by checking a code against the pending secret, enables
|
|
602
|
+
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
603
|
+
*/
|
|
604
|
+
async activateMfa(userId, code) {
|
|
605
|
+
const record = await this.mfa.get(userId);
|
|
606
|
+
if (!record || record.enabled) throw new MfaNotEnrolledError();
|
|
607
|
+
if (!verifyTotp(record.secret, code)) throw new MfaInvalidCodeError();
|
|
608
|
+
const recoveryCodes = Array.from({ length: 10 }, () => this.generateRecoveryCode());
|
|
609
|
+
await this.mfa.set(userId, {
|
|
610
|
+
secret: record.secret,
|
|
611
|
+
enabled: true,
|
|
612
|
+
recoveryCodes: recoveryCodes.map((c) => this.hashRecoveryCode(c))
|
|
613
|
+
});
|
|
614
|
+
const user = await this.users.findById(userId);
|
|
615
|
+
if (user) await this.hooks?.emit("auth:mfa_enabled", { user: publicUser(user) });
|
|
616
|
+
return { recoveryCodes };
|
|
617
|
+
}
|
|
618
|
+
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
619
|
+
async disableMfa(userId, code) {
|
|
620
|
+
if (!await this.isMfaEnabled(userId)) throw new MfaNotEnrolledError();
|
|
621
|
+
if (!await this.verifyMfaCode(userId, code)) throw new MfaInvalidCodeError();
|
|
622
|
+
await this.mfa.delete(userId);
|
|
623
|
+
const user = await this.users.findById(userId);
|
|
624
|
+
if (user) await this.hooks?.emit("auth:mfa_disabled", { user: publicUser(user) });
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
628
|
+
* is consumed on success). Returns false unless MFA is enabled.
|
|
629
|
+
*/
|
|
630
|
+
async verifyMfaCode(userId, code) {
|
|
631
|
+
const record = await this.mfa.get(userId);
|
|
632
|
+
if (!record || !record.enabled) return false;
|
|
633
|
+
if (verifyTotp(record.secret, code)) return true;
|
|
634
|
+
const hash = this.hashRecoveryCode(code);
|
|
635
|
+
const index = record.recoveryCodes.indexOf(hash);
|
|
636
|
+
if (index === -1) return false;
|
|
637
|
+
record.recoveryCodes.splice(index, 1);
|
|
638
|
+
await this.mfa.set(userId, record);
|
|
639
|
+
return true;
|
|
640
|
+
}
|
|
641
|
+
generateRecoveryCode() {
|
|
642
|
+
const raw = randomBytes4(5).toString("hex");
|
|
643
|
+
return `${raw.slice(0, 5)}-${raw.slice(5)}`;
|
|
644
|
+
}
|
|
645
|
+
hashRecoveryCode(code) {
|
|
646
|
+
return createHash("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
|
|
647
|
+
}
|
|
648
|
+
// --- token helpers -------------------------------------------------------
|
|
649
|
+
async issueOneTimeToken(userId, purpose, ttl) {
|
|
650
|
+
await this.tokens.deleteForUser(userId, purpose);
|
|
651
|
+
const token = randomBytes4(32).toString("base64url");
|
|
652
|
+
await this.tokens.create({ token, userId, purpose, expiresAt: Date.now() + parseDuration2(ttl) });
|
|
653
|
+
return token;
|
|
654
|
+
}
|
|
655
|
+
async consumeToken(token, purpose) {
|
|
656
|
+
const record = await this.tokens.find(token);
|
|
657
|
+
if (!record || record.purpose !== purpose || record.usedAt !== void 0 || Date.now() >= record.expiresAt) {
|
|
658
|
+
throw new AuthTokenInvalidError();
|
|
659
|
+
}
|
|
660
|
+
await this.tokens.markUsed(token);
|
|
661
|
+
return record;
|
|
662
|
+
}
|
|
663
|
+
async updateUser(id, patch) {
|
|
664
|
+
if (!this.users.update) throw new UserUpdateUnsupportedError();
|
|
665
|
+
const user = await this.users.update(id, patch);
|
|
666
|
+
if (!user) throw new AuthTokenInvalidError();
|
|
667
|
+
return user;
|
|
668
|
+
}
|
|
669
|
+
async issueTokens(userId, familyId = randomUUID2()) {
|
|
670
|
+
const refreshToken = randomBytes4(32).toString("base64url");
|
|
671
|
+
await this.refreshTokens.create({
|
|
672
|
+
token: refreshToken,
|
|
673
|
+
familyId,
|
|
674
|
+
userId,
|
|
675
|
+
expiresAt: Date.now() + parseDuration2(this.refreshTtl)
|
|
676
|
+
});
|
|
677
|
+
return {
|
|
678
|
+
accessToken: signJwt({ sub: userId }, { secret: this.secret, expiresIn: this.accessTtl }),
|
|
679
|
+
refreshToken
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
// src/plugin.ts
|
|
685
|
+
import { createToken, definePlugin, ensureMetadata } from "@basaltkit/core";
|
|
686
|
+
var AUTH = createToken("auth");
|
|
687
|
+
function authPlugin(options) {
|
|
688
|
+
return definePlugin({
|
|
689
|
+
name: "basalt:auth",
|
|
690
|
+
register({ container, hooks }) {
|
|
691
|
+
container.singleton(AUTH, () => new Auth({ ...options, hooks }));
|
|
692
|
+
const metadata = ensureMetadata(container);
|
|
693
|
+
const enricher = async ({ request, context, container: c }) => {
|
|
694
|
+
const auth2 = c.get(AUTH);
|
|
695
|
+
const header = request.headers.authorization;
|
|
696
|
+
const bearer = typeof header === "string" && header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
|
|
697
|
+
if (bearer && !bearer.startsWith("mk_")) {
|
|
698
|
+
const claims = auth2.verifyAccess(bearer);
|
|
699
|
+
const user = await auth2.users.findById(claims.sub);
|
|
700
|
+
if (user) context.user = publicUser(user);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
const sessionId = request.headers["x-session-id"];
|
|
704
|
+
if (typeof sessionId === "string") {
|
|
705
|
+
const user = await auth2.sessionUser(sessionId);
|
|
706
|
+
if (user) context.user = publicUser(user);
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
metadata.add("http:enrichers", enricher);
|
|
710
|
+
const guard = ({ route: route2, context }) => {
|
|
711
|
+
if (route2.meta?.["auth"] === true && !context.user) throw new AuthRequiredError();
|
|
712
|
+
};
|
|
713
|
+
metadata.add("http:guards", guard);
|
|
714
|
+
}
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// src/apikeys.ts
|
|
719
|
+
import { createHash as createHash2, randomBytes as randomBytes5, randomUUID as randomUUID3 } from "crypto";
|
|
720
|
+
import { BasaltError as BasaltError4 } from "@basaltkit/core";
|
|
721
|
+
var ScopeRequiredError = class extends BasaltError4 {
|
|
722
|
+
status = 403;
|
|
723
|
+
constructor(scope) {
|
|
724
|
+
super("AUTH_SCOPE_REQUIRED", `This action requires the "${scope}" scope.`);
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
var KEY_PREFIX = "mk_live_";
|
|
728
|
+
var hashKey = (key) => createHash2("sha256").update(key).digest("hex");
|
|
729
|
+
var strip = (record) => {
|
|
730
|
+
const { hash: _hash, ...info } = record;
|
|
731
|
+
return info;
|
|
732
|
+
};
|
|
733
|
+
var scopesSatisfy = (granted, required) => granted.includes("*") || required.every((scope) => granted.includes(scope));
|
|
734
|
+
var ApiKeys = class {
|
|
735
|
+
store;
|
|
736
|
+
hooks;
|
|
737
|
+
now;
|
|
738
|
+
constructor(options = {}) {
|
|
739
|
+
this.store = options.store ?? new MemoryApiKeyStore();
|
|
740
|
+
this.hooks = options.hooks;
|
|
741
|
+
this.now = options.now ?? Date.now;
|
|
742
|
+
}
|
|
743
|
+
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
744
|
+
async issue(input) {
|
|
745
|
+
const secret = randomBytes5(24).toString("base64url");
|
|
746
|
+
const key = `${KEY_PREFIX}${secret}`;
|
|
747
|
+
const record = {
|
|
748
|
+
id: randomUUID3(),
|
|
749
|
+
name: input.name,
|
|
750
|
+
prefix: `${KEY_PREFIX}${secret.slice(0, 6)}`,
|
|
751
|
+
hash: hashKey(key),
|
|
752
|
+
scopes: input.scopes ?? ["*"],
|
|
753
|
+
createdAt: this.now(),
|
|
754
|
+
...input.tenantId !== void 0 ? { tenantId: input.tenantId } : {},
|
|
755
|
+
...input.userId !== void 0 ? { userId: input.userId } : {}
|
|
756
|
+
};
|
|
757
|
+
await this.store.create(record);
|
|
758
|
+
await this.hooks?.emit("auth:apikey_issued", {
|
|
759
|
+
id: record.id,
|
|
760
|
+
...record.tenantId !== void 0 ? { tenantId: record.tenantId } : {},
|
|
761
|
+
...record.userId !== void 0 ? { userId: record.userId } : {}
|
|
762
|
+
});
|
|
763
|
+
return { record: strip(record), key };
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Resolves a presented key to its record, or null if it's malformed,
|
|
767
|
+
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
768
|
+
*/
|
|
769
|
+
async verify(presented) {
|
|
770
|
+
if (!presented.startsWith(KEY_PREFIX)) return null;
|
|
771
|
+
const record = await this.store.findByHash(hashKey(presented));
|
|
772
|
+
if (!record || record.revokedAt !== void 0) return null;
|
|
773
|
+
await this.store.touch(record.id, this.now());
|
|
774
|
+
return record;
|
|
775
|
+
}
|
|
776
|
+
async list(filter) {
|
|
777
|
+
return (await this.store.list(filter)).map(strip);
|
|
778
|
+
}
|
|
779
|
+
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
780
|
+
async revoke(id) {
|
|
781
|
+
const record = await this.store.findById(id);
|
|
782
|
+
if (record && record.revokedAt === void 0) {
|
|
783
|
+
await this.store.revoke(id, this.now());
|
|
784
|
+
await this.hooks?.emit("auth:apikey_revoked", { id });
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
/** Reads a single key's public info (used to authorize a revoke). */
|
|
788
|
+
async get(id) {
|
|
789
|
+
const record = await this.store.findById(id);
|
|
790
|
+
return record ? strip(record) : null;
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
// src/apikeys-plugin.ts
|
|
795
|
+
import { createToken as createToken2, definePlugin as definePlugin2, ensureMetadata as ensureMetadata2 } from "@basaltkit/core";
|
|
796
|
+
var API_KEYS = createToken2("auth:apikeys");
|
|
797
|
+
function apiKeysPlugin(options = {}) {
|
|
798
|
+
const header = options.header ?? "x-api-key";
|
|
799
|
+
return definePlugin2({
|
|
800
|
+
name: "basalt:apikeys",
|
|
801
|
+
register({ container, hooks }) {
|
|
802
|
+
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
803
|
+
const metadata = ensureMetadata2(container);
|
|
804
|
+
const enricher = async ({ request, context, container: c }) => {
|
|
805
|
+
const authHeader = request.headers.authorization;
|
|
806
|
+
const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer mk_") ? authHeader.slice("Bearer ".length) : void 0;
|
|
807
|
+
const custom = request.headers[header];
|
|
808
|
+
const presented = bearer ?? (typeof custom === "string" ? custom : void 0);
|
|
809
|
+
if (!presented) return;
|
|
810
|
+
const record = await c.get(API_KEYS).verify(presented);
|
|
811
|
+
if (!record) return;
|
|
812
|
+
context.apiKey = {
|
|
813
|
+
id: record.id,
|
|
814
|
+
scopes: record.scopes,
|
|
815
|
+
...record.tenantId !== void 0 ? { tenantId: record.tenantId } : {},
|
|
816
|
+
...record.userId !== void 0 ? { userId: record.userId } : {}
|
|
817
|
+
};
|
|
818
|
+
if (record.userId && options.users) {
|
|
819
|
+
const user = await options.users.findById(record.userId);
|
|
820
|
+
if (user) context.user = publicUser(user);
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
metadata.add("http:enrichers", enricher);
|
|
824
|
+
const guard = ({ route: route2, context }) => {
|
|
825
|
+
const required = route2.meta?.["scopes"];
|
|
826
|
+
if (!Array.isArray(required) || required.length === 0) return;
|
|
827
|
+
const granted = context.apiKey?.scopes ?? [];
|
|
828
|
+
for (const scope of required) {
|
|
829
|
+
if (!scopesSatisfy(granted, [scope])) throw new ScopeRequiredError(scope);
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
metadata.add("http:guards", guard);
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// src/routes.ts
|
|
838
|
+
import { ctx, BasaltError as BasaltError5 } from "@basaltkit/core";
|
|
839
|
+
import { route } from "@basaltkit/fastify";
|
|
840
|
+
import { z } from "zod";
|
|
841
|
+
var credentials = z.object({ email: z.string().email(), password: z.string().min(8) });
|
|
842
|
+
var auth = () => ctx().container.get(AUTH);
|
|
843
|
+
var apiKeys = () => ctx().container.get(API_KEYS);
|
|
844
|
+
function authRoutes() {
|
|
845
|
+
return [
|
|
846
|
+
route({
|
|
847
|
+
method: "POST",
|
|
848
|
+
url: "/auth/register",
|
|
849
|
+
body: credentials,
|
|
850
|
+
async handler({ body, reply }) {
|
|
851
|
+
const user = await auth().register(body.email, body.password);
|
|
852
|
+
return reply.code(201).send(user);
|
|
853
|
+
}
|
|
854
|
+
}),
|
|
855
|
+
route({
|
|
856
|
+
method: "POST",
|
|
857
|
+
url: "/auth/login",
|
|
858
|
+
body: credentials.extend({ mfaCode: z.string().optional() }),
|
|
859
|
+
async handler({ body }) {
|
|
860
|
+
const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode);
|
|
861
|
+
return { user, ...tokens };
|
|
862
|
+
}
|
|
863
|
+
}),
|
|
864
|
+
route({
|
|
865
|
+
method: "POST",
|
|
866
|
+
url: "/auth/refresh",
|
|
867
|
+
body: z.object({ refreshToken: z.string() }),
|
|
868
|
+
async handler({ body }) {
|
|
869
|
+
return auth().refresh(body.refreshToken);
|
|
870
|
+
}
|
|
871
|
+
}),
|
|
872
|
+
route({
|
|
873
|
+
method: "POST",
|
|
874
|
+
url: "/auth/logout",
|
|
875
|
+
body: z.object({ refreshToken: z.string() }),
|
|
876
|
+
async handler({ body, reply }) {
|
|
877
|
+
await auth().revoke(body.refreshToken);
|
|
878
|
+
return reply.code(204).send();
|
|
879
|
+
}
|
|
880
|
+
}),
|
|
881
|
+
route({
|
|
882
|
+
method: "GET",
|
|
883
|
+
url: "/auth/me",
|
|
884
|
+
meta: { auth: true },
|
|
885
|
+
async handler() {
|
|
886
|
+
return ctx().user;
|
|
887
|
+
}
|
|
888
|
+
}),
|
|
889
|
+
// --- email verification ------------------------------------------------
|
|
890
|
+
route({
|
|
891
|
+
method: "POST",
|
|
892
|
+
url: "/auth/verify/request",
|
|
893
|
+
body: z.object({ email: z.string().email() }),
|
|
894
|
+
async handler({ body }) {
|
|
895
|
+
await auth().requestEmailVerification(body.email);
|
|
896
|
+
return { ok: true };
|
|
897
|
+
}
|
|
898
|
+
}),
|
|
899
|
+
route({
|
|
900
|
+
method: "POST",
|
|
901
|
+
url: "/auth/verify",
|
|
902
|
+
body: z.object({ token: z.string() }),
|
|
903
|
+
async handler({ body }) {
|
|
904
|
+
return { user: await auth().verifyEmail(body.token) };
|
|
905
|
+
}
|
|
906
|
+
}),
|
|
907
|
+
// --- password reset ----------------------------------------------------
|
|
908
|
+
route({
|
|
909
|
+
method: "POST",
|
|
910
|
+
url: "/auth/password/forgot",
|
|
911
|
+
body: z.object({ email: z.string().email() }),
|
|
912
|
+
async handler({ body }) {
|
|
913
|
+
await auth().requestPasswordReset(body.email);
|
|
914
|
+
return { ok: true };
|
|
915
|
+
}
|
|
916
|
+
}),
|
|
917
|
+
route({
|
|
918
|
+
method: "POST",
|
|
919
|
+
url: "/auth/password/reset",
|
|
920
|
+
body: z.object({ token: z.string(), password: z.string().min(8) }),
|
|
921
|
+
async handler({ body }) {
|
|
922
|
+
await auth().resetPassword(body.token, body.password);
|
|
923
|
+
return { ok: true };
|
|
924
|
+
}
|
|
925
|
+
})
|
|
926
|
+
];
|
|
927
|
+
}
|
|
928
|
+
var ApiKeyForbiddenError = class extends BasaltError5 {
|
|
929
|
+
status = 404;
|
|
930
|
+
constructor() {
|
|
931
|
+
super("AUTH_APIKEY_NOT_FOUND", "API key not found.");
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
function apiKeyRoutes() {
|
|
935
|
+
const scope = () => {
|
|
936
|
+
const c = ctx();
|
|
937
|
+
return {
|
|
938
|
+
...c.tenant ? { tenantId: c.tenant.id } : {},
|
|
939
|
+
...c.user ? { userId: c.user.id } : {}
|
|
940
|
+
};
|
|
941
|
+
};
|
|
942
|
+
return [
|
|
943
|
+
route({
|
|
944
|
+
method: "POST",
|
|
945
|
+
url: "/apikeys",
|
|
946
|
+
meta: { auth: true },
|
|
947
|
+
body: z.object({
|
|
948
|
+
name: z.string().min(1).max(100),
|
|
949
|
+
scopes: z.array(z.string().min(1)).optional()
|
|
950
|
+
}),
|
|
951
|
+
async handler({ body, reply }) {
|
|
952
|
+
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
|
953
|
+
return reply.code(201).send({ ...record, key });
|
|
954
|
+
}
|
|
955
|
+
}),
|
|
956
|
+
route({
|
|
957
|
+
method: "GET",
|
|
958
|
+
url: "/apikeys",
|
|
959
|
+
meta: { auth: true },
|
|
960
|
+
async handler() {
|
|
961
|
+
return apiKeys().list(scope());
|
|
962
|
+
}
|
|
963
|
+
}),
|
|
964
|
+
route({
|
|
965
|
+
method: "DELETE",
|
|
966
|
+
url: "/apikeys/:id",
|
|
967
|
+
meta: { auth: true },
|
|
968
|
+
params: z.object({ id: z.string() }),
|
|
969
|
+
async handler({ params, reply }) {
|
|
970
|
+
const record = await apiKeys().get(params.id);
|
|
971
|
+
const { tenantId, userId } = scope();
|
|
972
|
+
if (!record || record.tenantId !== tenantId || record.userId !== userId) {
|
|
973
|
+
throw new ApiKeyForbiddenError();
|
|
974
|
+
}
|
|
975
|
+
await apiKeys().revoke(params.id);
|
|
976
|
+
return reply.code(204).send();
|
|
977
|
+
}
|
|
978
|
+
})
|
|
979
|
+
];
|
|
980
|
+
}
|
|
981
|
+
var MfaAuthRequiredError = class extends BasaltError5 {
|
|
982
|
+
status = 401;
|
|
983
|
+
constructor() {
|
|
984
|
+
super("AUTH_REQUIRED", "Authentication required.");
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
var currentUserId = () => {
|
|
988
|
+
const id = ctx().user?.id;
|
|
989
|
+
if (!id) throw new MfaAuthRequiredError();
|
|
990
|
+
return id;
|
|
991
|
+
};
|
|
992
|
+
function mfaRoutes() {
|
|
993
|
+
return [
|
|
994
|
+
route({
|
|
995
|
+
method: "POST",
|
|
996
|
+
url: "/auth/mfa/enroll",
|
|
997
|
+
meta: { auth: true },
|
|
998
|
+
async handler() {
|
|
999
|
+
return auth().enrollMfa(currentUserId());
|
|
1000
|
+
}
|
|
1001
|
+
}),
|
|
1002
|
+
route({
|
|
1003
|
+
method: "POST",
|
|
1004
|
+
url: "/auth/mfa/activate",
|
|
1005
|
+
meta: { auth: true },
|
|
1006
|
+
body: z.object({ code: z.string().min(6) }),
|
|
1007
|
+
async handler({ body }) {
|
|
1008
|
+
return auth().activateMfa(currentUserId(), body.code);
|
|
1009
|
+
}
|
|
1010
|
+
}),
|
|
1011
|
+
route({
|
|
1012
|
+
method: "GET",
|
|
1013
|
+
url: "/auth/mfa/status",
|
|
1014
|
+
meta: { auth: true },
|
|
1015
|
+
async handler() {
|
|
1016
|
+
return auth().mfaStatus(currentUserId());
|
|
1017
|
+
}
|
|
1018
|
+
}),
|
|
1019
|
+
route({
|
|
1020
|
+
method: "POST",
|
|
1021
|
+
url: "/auth/mfa/disable",
|
|
1022
|
+
meta: { auth: true },
|
|
1023
|
+
body: z.object({ code: z.string().min(6) }),
|
|
1024
|
+
async handler({ body, reply }) {
|
|
1025
|
+
await auth().disableMfa(currentUserId(), body.code);
|
|
1026
|
+
return reply.code(204).send();
|
|
1027
|
+
}
|
|
1028
|
+
})
|
|
1029
|
+
];
|
|
1030
|
+
}
|
|
1031
|
+
export {
|
|
1032
|
+
API_KEYS,
|
|
1033
|
+
AUTH,
|
|
1034
|
+
AccountLockedError,
|
|
1035
|
+
ApiKeys,
|
|
1036
|
+
Auth,
|
|
1037
|
+
AuthRequiredError,
|
|
1038
|
+
AuthTokenInvalidError,
|
|
1039
|
+
EmailTakenError,
|
|
1040
|
+
InvalidCredentialsError,
|
|
1041
|
+
LoginThrottle,
|
|
1042
|
+
MemoryApiKeyStore,
|
|
1043
|
+
MemoryAuthTokenStore,
|
|
1044
|
+
MemoryMfaStore,
|
|
1045
|
+
MemoryRefreshTokenStore,
|
|
1046
|
+
MemorySessionStore,
|
|
1047
|
+
MemoryUserSource,
|
|
1048
|
+
MfaInvalidCodeError,
|
|
1049
|
+
MfaNotEnrolledError,
|
|
1050
|
+
MfaRequiredError,
|
|
1051
|
+
RefreshInvalidError,
|
|
1052
|
+
RefreshReusedError,
|
|
1053
|
+
ScopeRequiredError,
|
|
1054
|
+
ScryptPasswordHasher,
|
|
1055
|
+
TokenExpiredError,
|
|
1056
|
+
TokenInvalidError,
|
|
1057
|
+
UserUpdateUnsupportedError,
|
|
1058
|
+
apiKeyRoutes,
|
|
1059
|
+
apiKeysPlugin,
|
|
1060
|
+
authPlugin,
|
|
1061
|
+
authRoutes,
|
|
1062
|
+
base32Decode,
|
|
1063
|
+
base32Encode,
|
|
1064
|
+
generateTotpSecret,
|
|
1065
|
+
mfaRoutes,
|
|
1066
|
+
otpauthUri,
|
|
1067
|
+
publicUser,
|
|
1068
|
+
scopesSatisfy,
|
|
1069
|
+
signJwt,
|
|
1070
|
+
totp,
|
|
1071
|
+
verifyJwt,
|
|
1072
|
+
verifyTotp
|
|
1073
|
+
};
|