@basaltkit/auth 1.5.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/apikeys-plugin.d.ts +37 -0
- package/dist/apikeys-plugin.js +56 -0
- package/dist/apikeys.d.ts +54 -0
- package/dist/apikeys.js +86 -0
- package/dist/auth.d.ts +279 -0
- package/dist/auth.js +535 -0
- package/dist/hashing.d.ts +23 -0
- package/dist/hashing.js +42 -0
- package/dist/index.d.ts +14 -1123
- package/dist/index.js +14 -1753
- package/dist/jwt.d.ts +26 -0
- package/dist/jwt.js +57 -0
- package/dist/oauth-plugin.d.ts +32 -0
- package/dist/oauth-plugin.js +63 -0
- package/dist/oauth.d.ts +115 -0
- package/dist/oauth.js +242 -0
- package/dist/plugin.d.ts +56 -0
- package/dist/plugin.js +44 -0
- package/dist/routes.d.ts +23 -0
- package/dist/routes.js +223 -0
- package/dist/secret-box.d.ts +10 -0
- package/dist/secret-box.js +38 -0
- package/dist/stores.d.ts +196 -0
- package/dist/stores.js +169 -0
- package/dist/throttle.d.ts +32 -0
- package/dist/throttle.js +45 -0
- package/dist/totp.d.ts +40 -0
- package/dist/totp.js +108 -0
- package/dist/webauthn-plugin.d.ts +13 -0
- package/dist/webauthn-plugin.js +17 -0
- package/dist/webauthn.d.ts +219 -0
- package/dist/webauthn.js +248 -0
- package/package.json +11 -12
package/dist/index.js
CHANGED
|
@@ -1,1753 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
return `scrypt$${N}$${r}$${p}$${salt.toString("base64url")}$${derived.toString("base64url")}`;
|
|
16
|
-
}
|
|
17
|
-
async verify(plain, hashed) {
|
|
18
|
-
const parts = hashed.split("$");
|
|
19
|
-
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
|
20
|
-
const [, n, r, p, salt, expected] = parts;
|
|
21
|
-
const derived = await scryptAsync(plain, Buffer.from(salt, "base64url"), 32, {
|
|
22
|
-
N: Number(n),
|
|
23
|
-
r: Number(r),
|
|
24
|
-
p: Number(p),
|
|
25
|
-
maxmem: MAXMEM
|
|
26
|
-
});
|
|
27
|
-
const expectedBuffer = Buffer.from(expected, "base64url");
|
|
28
|
-
return derived.length === expectedBuffer.length && timingSafeEqual(derived, expectedBuffer);
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
// src/jwt.ts
|
|
33
|
-
import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
34
|
-
import { BasaltError, parseDuration } from "@basaltkit/core";
|
|
35
|
-
var TokenInvalidError = class extends BasaltError {
|
|
36
|
-
status = 401;
|
|
37
|
-
constructor() {
|
|
38
|
-
super("AUTH_TOKEN_INVALID", "The token is invalid.");
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
var TokenExpiredError = class extends BasaltError {
|
|
42
|
-
status = 401;
|
|
43
|
-
constructor() {
|
|
44
|
-
super("AUTH_TOKEN_EXPIRED", "The token has expired.");
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
var encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
48
|
-
function signJwt(claims, options) {
|
|
49
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
50
|
-
const payload = {
|
|
51
|
-
iat: now,
|
|
52
|
-
...options.expiresIn !== void 0 ? { exp: now + Math.ceil(parseDuration(options.expiresIn) / 1e3) } : {},
|
|
53
|
-
...claims
|
|
54
|
-
};
|
|
55
|
-
const head = encode({ alg: "HS256", typ: "JWT" });
|
|
56
|
-
const body = encode(payload);
|
|
57
|
-
const signature = createHmac("sha256", options.secret).update(`${head}.${body}`).digest("base64url");
|
|
58
|
-
return `${head}.${body}.${signature}`;
|
|
59
|
-
}
|
|
60
|
-
function verifyJwt(token, secret) {
|
|
61
|
-
const parts = token.split(".");
|
|
62
|
-
if (parts.length !== 3) throw new TokenInvalidError();
|
|
63
|
-
const [head, body, signature] = parts;
|
|
64
|
-
const expected = createHmac("sha256", secret).update(`${head}.${body}`).digest();
|
|
65
|
-
const received = Buffer.from(signature, "base64url");
|
|
66
|
-
if (expected.length !== received.length || !timingSafeEqual2(expected, received)) {
|
|
67
|
-
throw new TokenInvalidError();
|
|
68
|
-
}
|
|
69
|
-
let claims;
|
|
70
|
-
try {
|
|
71
|
-
claims = JSON.parse(Buffer.from(body, "base64url").toString());
|
|
72
|
-
} catch {
|
|
73
|
-
throw new TokenInvalidError();
|
|
74
|
-
}
|
|
75
|
-
if (typeof claims.sub !== "string") throw new TokenInvalidError();
|
|
76
|
-
if (claims.exp !== void 0 && claims.exp <= Math.floor(Date.now() / 1e3)) {
|
|
77
|
-
throw new TokenExpiredError();
|
|
78
|
-
}
|
|
79
|
-
return claims;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// src/stores.ts
|
|
83
|
-
import { createHash, randomBytes as randomBytes2, randomUUID } from "crypto";
|
|
84
|
-
var hashSessionId = (id) => createHash("sha256").update(id).digest("hex");
|
|
85
|
-
var MemoryUserSource = class {
|
|
86
|
-
users = /* @__PURE__ */ new Map();
|
|
87
|
-
async findByEmail(email) {
|
|
88
|
-
for (const user of this.users.values()) {
|
|
89
|
-
if (user.email === email) return user;
|
|
90
|
-
}
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
async findById(id) {
|
|
94
|
-
return this.users.get(id) ?? null;
|
|
95
|
-
}
|
|
96
|
-
async create(data) {
|
|
97
|
-
const user = { id: randomUUID(), emailVerified: false, ...data };
|
|
98
|
-
this.users.set(user.id, user);
|
|
99
|
-
return user;
|
|
100
|
-
}
|
|
101
|
-
async update(id, patch) {
|
|
102
|
-
const user = this.users.get(id);
|
|
103
|
-
if (!user) return null;
|
|
104
|
-
Object.assign(user, patch);
|
|
105
|
-
return user;
|
|
106
|
-
}
|
|
107
|
-
};
|
|
108
|
-
var MemoryAuthTokenStore = class {
|
|
109
|
-
records = /* @__PURE__ */ new Map();
|
|
110
|
-
async create(record) {
|
|
111
|
-
this.records.set(record.token, record);
|
|
112
|
-
}
|
|
113
|
-
async find(token) {
|
|
114
|
-
return this.records.get(token) ?? null;
|
|
115
|
-
}
|
|
116
|
-
async markUsed(token) {
|
|
117
|
-
const record = this.records.get(token);
|
|
118
|
-
if (record) record.usedAt = Date.now();
|
|
119
|
-
}
|
|
120
|
-
async deleteForUser(userId, purpose) {
|
|
121
|
-
for (const [token, record] of this.records) {
|
|
122
|
-
if (record.userId === userId && record.purpose === purpose) this.records.delete(token);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
var MemoryApiKeyStore = class {
|
|
127
|
-
records = /* @__PURE__ */ new Map();
|
|
128
|
-
async create(record) {
|
|
129
|
-
this.records.set(record.id, record);
|
|
130
|
-
}
|
|
131
|
-
async findByHash(hash) {
|
|
132
|
-
for (const record of this.records.values()) {
|
|
133
|
-
if (record.hash === hash) return record;
|
|
134
|
-
}
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
async findById(id) {
|
|
138
|
-
return this.records.get(id) ?? null;
|
|
139
|
-
}
|
|
140
|
-
async list(filter) {
|
|
141
|
-
const out = [];
|
|
142
|
-
for (const record of this.records.values()) {
|
|
143
|
-
if (record.revokedAt !== void 0) continue;
|
|
144
|
-
if (filter.tenantId !== void 0 && record.tenantId !== filter.tenantId) continue;
|
|
145
|
-
if (filter.userId !== void 0 && record.userId !== filter.userId) continue;
|
|
146
|
-
out.push(record);
|
|
147
|
-
}
|
|
148
|
-
return out;
|
|
149
|
-
}
|
|
150
|
-
async touch(id, at) {
|
|
151
|
-
const record = this.records.get(id);
|
|
152
|
-
if (record) record.lastUsedAt = at;
|
|
153
|
-
}
|
|
154
|
-
async revoke(id, at) {
|
|
155
|
-
const record = this.records.get(id);
|
|
156
|
-
if (record) record.revokedAt = at;
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
var MemoryMfaStore = class {
|
|
160
|
-
records = /* @__PURE__ */ new Map();
|
|
161
|
-
async get(userId) {
|
|
162
|
-
return this.records.get(userId) ?? null;
|
|
163
|
-
}
|
|
164
|
-
async set(userId, record) {
|
|
165
|
-
this.records.set(userId, record);
|
|
166
|
-
}
|
|
167
|
-
async delete(userId) {
|
|
168
|
-
this.records.delete(userId);
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
var MemoryTokenVersionStore = class {
|
|
172
|
-
versions = /* @__PURE__ */ new Map();
|
|
173
|
-
async get(userId) {
|
|
174
|
-
return this.versions.get(userId) ?? 0;
|
|
175
|
-
}
|
|
176
|
-
async increment(userId) {
|
|
177
|
-
const next = (this.versions.get(userId) ?? 0) + 1;
|
|
178
|
-
this.versions.set(userId, next);
|
|
179
|
-
return next;
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
var MemorySessionStore = class {
|
|
183
|
-
sessions = /* @__PURE__ */ new Map();
|
|
184
|
-
async create(userId, ttlMs) {
|
|
185
|
-
const rawId = randomBytes2(32).toString("base64url");
|
|
186
|
-
const hashed = hashSessionId(rawId);
|
|
187
|
-
const expiresAt = Date.now() + ttlMs;
|
|
188
|
-
this.sessions.set(hashed, { id: hashed, userId, expiresAt });
|
|
189
|
-
return { id: rawId, userId, expiresAt };
|
|
190
|
-
}
|
|
191
|
-
async find(id) {
|
|
192
|
-
const hashed = hashSessionId(id);
|
|
193
|
-
const record = this.sessions.get(hashed);
|
|
194
|
-
if (!record) return null;
|
|
195
|
-
if (Date.now() >= record.expiresAt) {
|
|
196
|
-
this.sessions.delete(hashed);
|
|
197
|
-
return null;
|
|
198
|
-
}
|
|
199
|
-
return { id, userId: record.userId, expiresAt: record.expiresAt };
|
|
200
|
-
}
|
|
201
|
-
async delete(id) {
|
|
202
|
-
return this.sessions.delete(hashSessionId(id));
|
|
203
|
-
}
|
|
204
|
-
async deleteAllForUser(userId) {
|
|
205
|
-
for (const [key, record] of this.sessions) {
|
|
206
|
-
if (record.userId === userId) this.sessions.delete(key);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
};
|
|
210
|
-
var MemoryRefreshTokenStore = class {
|
|
211
|
-
records = /* @__PURE__ */ new Map();
|
|
212
|
-
async create(record) {
|
|
213
|
-
this.records.set(record.token, record);
|
|
214
|
-
}
|
|
215
|
-
async find(token) {
|
|
216
|
-
return this.records.get(token) ?? null;
|
|
217
|
-
}
|
|
218
|
-
async markUsed(token) {
|
|
219
|
-
const record = this.records.get(token);
|
|
220
|
-
if (record) record.usedAt = Date.now();
|
|
221
|
-
}
|
|
222
|
-
async revokeFamily(familyId) {
|
|
223
|
-
for (const [token, record] of this.records) {
|
|
224
|
-
if (record.familyId === familyId) this.records.delete(token);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
async revokeAllForUser(userId) {
|
|
228
|
-
for (const [token, record] of this.records) {
|
|
229
|
-
if (record.userId === userId) this.records.delete(token);
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
};
|
|
233
|
-
|
|
234
|
-
// src/auth.ts
|
|
235
|
-
import { createHash as createHash3, randomBytes as randomBytes5, randomUUID as randomUUID2 } from "crypto";
|
|
236
|
-
import { BasaltError as BasaltError3, parseDuration as parseDuration2 } from "@basaltkit/core";
|
|
237
|
-
|
|
238
|
-
// src/throttle.ts
|
|
239
|
-
import { BasaltError as BasaltError2 } from "@basaltkit/core";
|
|
240
|
-
var AccountLockedError = class extends BasaltError2 {
|
|
241
|
-
constructor(retryAfterMs) {
|
|
242
|
-
super(
|
|
243
|
-
"AUTH_LOCKED",
|
|
244
|
-
`Too many failed login attempts. Try again in ${Math.ceil(retryAfterMs / 1e3)}s.`
|
|
245
|
-
);
|
|
246
|
-
this.retryAfterMs = retryAfterMs;
|
|
247
|
-
}
|
|
248
|
-
retryAfterMs;
|
|
249
|
-
status = 429;
|
|
250
|
-
};
|
|
251
|
-
var LoginThrottle = class {
|
|
252
|
-
failures = /* @__PURE__ */ new Map();
|
|
253
|
-
maxAttempts;
|
|
254
|
-
windowMs;
|
|
255
|
-
clock;
|
|
256
|
-
constructor(options = {}) {
|
|
257
|
-
this.maxAttempts = options.maxAttempts ?? 5;
|
|
258
|
-
this.windowMs = options.windowMs ?? 15 * 6e4;
|
|
259
|
-
this.clock = options.clock ?? (() => Date.now());
|
|
260
|
-
}
|
|
261
|
-
/** Throws {@link AccountLockedError} when the key is currently locked. */
|
|
262
|
-
assertAllowed(key) {
|
|
263
|
-
const entry = this.failures.get(key);
|
|
264
|
-
if (entry && this.clock() < entry.resetAt && entry.count >= this.maxAttempts) {
|
|
265
|
-
throw new AccountLockedError(entry.resetAt - this.clock());
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
recordFailure(key) {
|
|
269
|
-
const now = this.clock();
|
|
270
|
-
let entry = this.failures.get(key);
|
|
271
|
-
if (!entry || now >= entry.resetAt) entry = { count: 0, resetAt: now + this.windowMs };
|
|
272
|
-
entry.count += 1;
|
|
273
|
-
this.failures.set(key, entry);
|
|
274
|
-
}
|
|
275
|
-
reset(key) {
|
|
276
|
-
this.failures.delete(key);
|
|
277
|
-
}
|
|
278
|
-
};
|
|
279
|
-
|
|
280
|
-
// src/totp.ts
|
|
281
|
-
import { createHmac as createHmac2, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
282
|
-
var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
283
|
-
function base32Encode(bytes) {
|
|
284
|
-
let bits = 0;
|
|
285
|
-
let value = 0;
|
|
286
|
-
let out = "";
|
|
287
|
-
for (const byte of bytes) {
|
|
288
|
-
value = value << 8 | byte;
|
|
289
|
-
bits += 8;
|
|
290
|
-
while (bits >= 5) {
|
|
291
|
-
out += BASE32_ALPHABET[value >>> bits - 5 & 31];
|
|
292
|
-
bits -= 5;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
|
|
296
|
-
return out;
|
|
297
|
-
}
|
|
298
|
-
function base32Decode(input) {
|
|
299
|
-
const clean = input.toUpperCase().replace(/[\s=]/g, "");
|
|
300
|
-
let bits = 0;
|
|
301
|
-
let value = 0;
|
|
302
|
-
const out = [];
|
|
303
|
-
for (const char of clean) {
|
|
304
|
-
const idx = BASE32_ALPHABET.indexOf(char);
|
|
305
|
-
if (idx === -1) throw new Error("Invalid base32 character");
|
|
306
|
-
value = value << 5 | idx;
|
|
307
|
-
bits += 5;
|
|
308
|
-
if (bits >= 8) {
|
|
309
|
-
out.push(value >>> bits - 8 & 255);
|
|
310
|
-
bits -= 8;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
return Buffer.from(out);
|
|
314
|
-
}
|
|
315
|
-
function generateTotpSecret(bytes = 20) {
|
|
316
|
-
return base32Encode(randomBytes3(bytes));
|
|
317
|
-
}
|
|
318
|
-
function hotp(secret, counter, digits) {
|
|
319
|
-
const buf = Buffer.alloc(8);
|
|
320
|
-
buf.writeUInt32BE(Math.floor(counter / 4294967296), 0);
|
|
321
|
-
buf.writeUInt32BE(counter >>> 0, 4);
|
|
322
|
-
const digest = createHmac2("sha1", secret).update(buf).digest();
|
|
323
|
-
const offset = digest[digest.length - 1] & 15;
|
|
324
|
-
const binary = (digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255;
|
|
325
|
-
return (binary % 10 ** digits).toString().padStart(digits, "0");
|
|
326
|
-
}
|
|
327
|
-
function totp(secret, options = {}) {
|
|
328
|
-
const period = options.period ?? 30;
|
|
329
|
-
const digits = options.digits ?? 6;
|
|
330
|
-
const now = options.now ?? Date.now();
|
|
331
|
-
const counter = Math.floor(now / 1e3 / period);
|
|
332
|
-
return hotp(base32Decode(secret), counter, digits);
|
|
333
|
-
}
|
|
334
|
-
function matchTotpStep(secret, token, options = {}) {
|
|
335
|
-
const period = options.period ?? 30;
|
|
336
|
-
const digits = options.digits ?? 6;
|
|
337
|
-
const now = options.now ?? Date.now();
|
|
338
|
-
const window = options.window ?? 1;
|
|
339
|
-
const cleaned = token.replace(/\s/g, "");
|
|
340
|
-
if (cleaned.length !== digits) return null;
|
|
341
|
-
const key = base32Decode(secret);
|
|
342
|
-
const base = Math.floor(now / 1e3 / period);
|
|
343
|
-
let matched = -1;
|
|
344
|
-
for (let error = -window; error <= window; error++) {
|
|
345
|
-
const step = base + error;
|
|
346
|
-
const candidate = hotp(key, step, digits);
|
|
347
|
-
if (candidate.length === cleaned.length && timingSafeEqual3(Buffer.from(candidate), Buffer.from(cleaned))) {
|
|
348
|
-
matched = step;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
return matched === -1 ? null : matched;
|
|
352
|
-
}
|
|
353
|
-
function verifyTotp(secret, token, options = {}) {
|
|
354
|
-
return matchTotpStep(secret, token, options) !== null;
|
|
355
|
-
}
|
|
356
|
-
function otpauthUri(input) {
|
|
357
|
-
const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;
|
|
358
|
-
const params = new URLSearchParams({
|
|
359
|
-
secret: input.secret,
|
|
360
|
-
issuer: input.issuer,
|
|
361
|
-
algorithm: "SHA1",
|
|
362
|
-
digits: String(input.digits ?? 6),
|
|
363
|
-
period: String(input.period ?? 30)
|
|
364
|
-
});
|
|
365
|
-
return `otpauth://totp/${label}?${params.toString()}`;
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// src/secret-box.ts
|
|
369
|
-
import { createCipheriv, createDecipheriv, createHash as createHash2, randomBytes as randomBytes4 } from "crypto";
|
|
370
|
-
var PREFIX = "v1:";
|
|
371
|
-
function deriveKey(key) {
|
|
372
|
-
return createHash2("sha256").update(key).digest();
|
|
373
|
-
}
|
|
374
|
-
function encryptSecret(plaintext, key) {
|
|
375
|
-
const iv = randomBytes4(12);
|
|
376
|
-
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
377
|
-
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
378
|
-
const tag = cipher.getAuthTag();
|
|
379
|
-
return `${PREFIX}${iv.toString("base64")}:${tag.toString("base64")}:${ct.toString("base64")}`;
|
|
380
|
-
}
|
|
381
|
-
function decryptSecret(value, key) {
|
|
382
|
-
if (!value.startsWith(PREFIX)) return value;
|
|
383
|
-
const [, ivB64, tagB64, ctB64] = value.split(":");
|
|
384
|
-
if (!ivB64 || !tagB64 || !ctB64) throw new Error("Malformed encrypted secret.");
|
|
385
|
-
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"));
|
|
386
|
-
decipher.setAuthTag(Buffer.from(tagB64, "base64"));
|
|
387
|
-
return Buffer.concat([decipher.update(Buffer.from(ctB64, "base64")), decipher.final()]).toString("utf8");
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
// src/auth.ts
|
|
391
|
-
var InvalidCredentialsError = class extends BasaltError3 {
|
|
392
|
-
status = 401;
|
|
393
|
-
constructor() {
|
|
394
|
-
super("AUTH_INVALID_CREDENTIALS", "Invalid email or password.");
|
|
395
|
-
}
|
|
396
|
-
};
|
|
397
|
-
var EmailTakenError = class extends BasaltError3 {
|
|
398
|
-
status = 409;
|
|
399
|
-
constructor() {
|
|
400
|
-
super("AUTH_EMAIL_TAKEN", "An account with this email already exists.");
|
|
401
|
-
}
|
|
402
|
-
};
|
|
403
|
-
var WeakJwtSecretError = class extends BasaltError3 {
|
|
404
|
-
constructor(reason) {
|
|
405
|
-
super("AUTH_WEAK_SECRET", `The auth signing secret is ${reason}. Set a strong APP_SECRET (>= 32 chars).`);
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
var RefreshInvalidError = class extends BasaltError3 {
|
|
409
|
-
status = 401;
|
|
410
|
-
constructor() {
|
|
411
|
-
super("AUTH_REFRESH_INVALID", "The refresh token is invalid or expired.");
|
|
412
|
-
}
|
|
413
|
-
};
|
|
414
|
-
var RefreshReusedError = class extends BasaltError3 {
|
|
415
|
-
status = 401;
|
|
416
|
-
constructor() {
|
|
417
|
-
super("AUTH_REFRESH_REUSED", "Refresh token reuse detected. All sessions of this family were revoked.");
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
var AuthRequiredError = class extends BasaltError3 {
|
|
421
|
-
status = 401;
|
|
422
|
-
constructor() {
|
|
423
|
-
super("AUTH_REQUIRED", "Authentication required.");
|
|
424
|
-
}
|
|
425
|
-
};
|
|
426
|
-
var AuthTokenInvalidError = class extends BasaltError3 {
|
|
427
|
-
status = 400;
|
|
428
|
-
constructor() {
|
|
429
|
-
super("AUTH_TOKEN_INVALID", "The link is invalid or has expired. Request a new one.");
|
|
430
|
-
}
|
|
431
|
-
};
|
|
432
|
-
var UserUpdateUnsupportedError = class extends BasaltError3 {
|
|
433
|
-
status = 500;
|
|
434
|
-
constructor() {
|
|
435
|
-
super("AUTH_UPDATE_UNSUPPORTED", "The UserSource does not implement update() \u2014 required for this flow.");
|
|
436
|
-
}
|
|
437
|
-
};
|
|
438
|
-
var MfaRequiredError = class extends BasaltError3 {
|
|
439
|
-
status = 401;
|
|
440
|
-
constructor() {
|
|
441
|
-
super("AUTH_MFA_REQUIRED", "A multi-factor authentication code is required.");
|
|
442
|
-
}
|
|
443
|
-
};
|
|
444
|
-
var MfaInvalidCodeError = class extends BasaltError3 {
|
|
445
|
-
status = 401;
|
|
446
|
-
constructor() {
|
|
447
|
-
super("AUTH_MFA_INVALID", "The authentication code is incorrect.");
|
|
448
|
-
}
|
|
449
|
-
};
|
|
450
|
-
var MfaNotEnrolledError = class extends BasaltError3 {
|
|
451
|
-
status = 400;
|
|
452
|
-
constructor() {
|
|
453
|
-
super("AUTH_MFA_NOT_ENROLLED", "No MFA enrollment is in progress for this account.");
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
var publicUser = (user) => ({
|
|
457
|
-
id: user.id,
|
|
458
|
-
email: user.email,
|
|
459
|
-
emailVerified: user.emailVerified ?? false
|
|
460
|
-
});
|
|
461
|
-
var Auth = class {
|
|
462
|
-
users;
|
|
463
|
-
hasher;
|
|
464
|
-
sessions;
|
|
465
|
-
refreshTokens;
|
|
466
|
-
secret;
|
|
467
|
-
accessTtl;
|
|
468
|
-
refreshTtl;
|
|
469
|
-
sessionTtl;
|
|
470
|
-
hooks;
|
|
471
|
-
throttle;
|
|
472
|
-
ipThrottle;
|
|
473
|
-
tokens;
|
|
474
|
-
verificationTtl;
|
|
475
|
-
resetTtl;
|
|
476
|
-
mfa;
|
|
477
|
-
mfaIssuer;
|
|
478
|
-
mfaKey;
|
|
479
|
-
tokenVersions;
|
|
480
|
-
enumerationSafeRegister;
|
|
481
|
-
constructor(options) {
|
|
482
|
-
this.users = options.users;
|
|
483
|
-
this.secret = options.secret;
|
|
484
|
-
if (!this.secret) throw new WeakJwtSecretError("missing");
|
|
485
|
-
if (process.env["NODE_ENV"] === "production" && this.secret.length < 32) {
|
|
486
|
-
throw new WeakJwtSecretError("too short");
|
|
487
|
-
}
|
|
488
|
-
this.hasher = options.hasher ?? new ScryptPasswordHasher();
|
|
489
|
-
this.sessions = options.sessions ?? new MemorySessionStore();
|
|
490
|
-
this.refreshTokens = options.refreshTokens ?? new MemoryRefreshTokenStore();
|
|
491
|
-
this.accessTtl = options.accessTtl ?? "15m";
|
|
492
|
-
this.refreshTtl = options.refreshTtl ?? "30d";
|
|
493
|
-
this.sessionTtl = options.sessionTtl ?? "30d";
|
|
494
|
-
this.hooks = options.hooks;
|
|
495
|
-
this.throttle = options.loginThrottle === false ? void 0 : options.loginThrottle ?? new LoginThrottle();
|
|
496
|
-
this.ipThrottle = options.ipLoginThrottle === false ? void 0 : options.ipLoginThrottle ?? new LoginThrottle({ maxAttempts: 50, windowMs: 15 * 6e4 });
|
|
497
|
-
this.tokens = options.tokens ?? new MemoryAuthTokenStore();
|
|
498
|
-
this.verificationTtl = options.verificationTtl ?? "24h";
|
|
499
|
-
this.resetTtl = options.resetTtl ?? "1h";
|
|
500
|
-
this.mfa = options.mfa ?? new MemoryMfaStore();
|
|
501
|
-
this.mfaIssuer = options.mfaIssuer ?? "Basalt";
|
|
502
|
-
this.mfaKey = options.mfaEncryptionKey ? deriveKey(options.mfaEncryptionKey) : void 0;
|
|
503
|
-
this.tokenVersions = options.tokenVersions;
|
|
504
|
-
this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
|
|
505
|
-
}
|
|
506
|
-
async register(email, password) {
|
|
507
|
-
if (await this.users.findByEmail(email)) throw new EmailTakenError();
|
|
508
|
-
const user = await this.users.create({
|
|
509
|
-
email,
|
|
510
|
-
passwordHash: await this.hasher.hash(password)
|
|
511
|
-
});
|
|
512
|
-
await this.hooks?.emit("auth:registered", { user: publicUser(user) });
|
|
513
|
-
return publicUser(user);
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
517
|
-
* matched by email — find-or-create. A new account is created **passwordless**
|
|
518
|
-
* (a random, unusable password hash), so password login won't work for it
|
|
519
|
-
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
520
|
-
* Returns the tokens and whether the account was just created.
|
|
521
|
-
*/
|
|
522
|
-
async socialLogin(email, options = {}) {
|
|
523
|
-
let user = await this.users.findByEmail(email);
|
|
524
|
-
let created = false;
|
|
525
|
-
if (!user) {
|
|
526
|
-
user = await this.users.create({
|
|
527
|
-
email,
|
|
528
|
-
passwordHash: await this.hasher.hash(randomBytes5(32).toString("hex"))
|
|
529
|
-
});
|
|
530
|
-
created = true;
|
|
531
|
-
await this.hooks?.emit("auth:registered", { user: publicUser(user) });
|
|
532
|
-
}
|
|
533
|
-
if (options.emailVerified && !user.emailVerified && this.users.update) {
|
|
534
|
-
user = await this.users.update(user.id, { emailVerified: true }) ?? user;
|
|
535
|
-
}
|
|
536
|
-
const tokens = await this.issueTokens(user.id);
|
|
537
|
-
await this.hooks?.emit("auth:login", { user: publicUser(user) });
|
|
538
|
-
return { user: publicUser(user), tokens, created };
|
|
539
|
-
}
|
|
540
|
-
/**
|
|
541
|
-
* Enumeration-safe registration for the public endpoint: creates the account
|
|
542
|
-
* for a new email, or — when the email is already taken — does equivalent work
|
|
543
|
-
* (so timing doesn't leak) and emits `auth:register_existing_email` so the app
|
|
544
|
-
* can send an out-of-band "you already have an account" email. Returns nothing
|
|
545
|
-
* either way, so the response can't reveal whether the account existed.
|
|
546
|
-
*
|
|
547
|
-
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
548
|
-
* duplicate instead (the classic, enumerable behavior).
|
|
549
|
-
*/
|
|
550
|
-
async registerSafely(email, password) {
|
|
551
|
-
const existing = await this.users.findByEmail(email);
|
|
552
|
-
if (existing) {
|
|
553
|
-
if (!this.enumerationSafeRegister) throw new EmailTakenError();
|
|
554
|
-
await this.hasher.hash(password);
|
|
555
|
-
await this.hooks?.emit("auth:register_existing_email", { email });
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
const user = await this.users.create({
|
|
559
|
-
email,
|
|
560
|
-
passwordHash: await this.hasher.hash(password)
|
|
561
|
-
});
|
|
562
|
-
await this.hooks?.emit("auth:registered", { user: publicUser(user) });
|
|
563
|
-
}
|
|
564
|
-
/** Verifies credentials without side effects. Null on failure. */
|
|
565
|
-
async attempt(email, password) {
|
|
566
|
-
const user = await this.users.findByEmail(email);
|
|
567
|
-
if (!user) {
|
|
568
|
-
await this.hasher.verify(password, await this.dummyHash());
|
|
569
|
-
return null;
|
|
570
|
-
}
|
|
571
|
-
return await this.hasher.verify(password, user.passwordHash) ? user : null;
|
|
572
|
-
}
|
|
573
|
-
dummyHashPromise;
|
|
574
|
-
/** A valid hash of a throwaway secret, produced once by the configured hasher. */
|
|
575
|
-
dummyHash() {
|
|
576
|
-
return this.dummyHashPromise ??= this.hasher.hash("basalt-timing-equalizer");
|
|
577
|
-
}
|
|
578
|
-
/**
|
|
579
|
-
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
580
|
-
* account after too many failures (see {@link LoginThrottle}); a success
|
|
581
|
-
* clears the counter.
|
|
582
|
-
*
|
|
583
|
-
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
584
|
-
* required: a correct password with a missing code throws
|
|
585
|
-
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
586
|
-
* wrong code throws {@link MfaInvalidCodeError}.
|
|
587
|
-
*/
|
|
588
|
-
async login(email, password, mfaCode, context = {}) {
|
|
589
|
-
const key = email.toLowerCase();
|
|
590
|
-
const ipKey = context.ip ? `ip:${context.ip}` : void 0;
|
|
591
|
-
this.throttle?.assertAllowed(key);
|
|
592
|
-
if (ipKey) this.ipThrottle?.assertAllowed(ipKey);
|
|
593
|
-
const recordFailure = () => {
|
|
594
|
-
this.throttle?.recordFailure(key);
|
|
595
|
-
if (ipKey) this.ipThrottle?.recordFailure(ipKey);
|
|
596
|
-
};
|
|
597
|
-
const user = await this.attempt(email, password);
|
|
598
|
-
if (!user) {
|
|
599
|
-
recordFailure();
|
|
600
|
-
await this.hooks?.emit("auth:login_failed", { email });
|
|
601
|
-
throw new InvalidCredentialsError();
|
|
602
|
-
}
|
|
603
|
-
if (await this.isMfaEnabled(user.id)) {
|
|
604
|
-
if (!mfaCode) throw new MfaRequiredError();
|
|
605
|
-
if (!await this.verifyMfaCode(user.id, mfaCode)) {
|
|
606
|
-
recordFailure();
|
|
607
|
-
throw new MfaInvalidCodeError();
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
this.throttle?.reset(key);
|
|
611
|
-
const tokens = await this.issueTokens(user.id);
|
|
612
|
-
await this.hooks?.emit("auth:login", { user: publicUser(user) });
|
|
613
|
-
return { user: publicUser(user), tokens };
|
|
614
|
-
}
|
|
615
|
-
/**
|
|
616
|
-
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
617
|
-
* and issues a new one in the same family. If a consumed token comes back
|
|
618
|
-
* (theft indicator), the whole family is revoked.
|
|
619
|
-
*/
|
|
620
|
-
async refresh(refreshToken) {
|
|
621
|
-
const hashed = this.hashToken(refreshToken);
|
|
622
|
-
const record = await this.refreshTokens.find(hashed);
|
|
623
|
-
if (!record) throw new RefreshInvalidError();
|
|
624
|
-
if (record.usedAt !== void 0) {
|
|
625
|
-
await this.refreshTokens.revokeFamily(record.familyId);
|
|
626
|
-
throw new RefreshReusedError();
|
|
627
|
-
}
|
|
628
|
-
if (Date.now() >= record.expiresAt) throw new RefreshInvalidError();
|
|
629
|
-
await this.refreshTokens.markUsed(hashed);
|
|
630
|
-
return this.issueTokens(record.userId, record.familyId);
|
|
631
|
-
}
|
|
632
|
-
/** Revokes a refresh family — logout for token-based clients. */
|
|
633
|
-
async revoke(refreshToken) {
|
|
634
|
-
const record = await this.refreshTokens.find(this.hashToken(refreshToken));
|
|
635
|
-
if (record) await this.refreshTokens.revokeFamily(record.familyId);
|
|
636
|
-
}
|
|
637
|
-
/** Structural JWT verification only (signature + expiry). */
|
|
638
|
-
verifyAccess(accessToken) {
|
|
639
|
-
return verifyJwt(accessToken, this.secret);
|
|
640
|
-
}
|
|
641
|
-
/**
|
|
642
|
-
* Verifies the access token AND, when token-version revocation is enabled,
|
|
643
|
-
* rejects a token minted before the user's version was last bumped (i.e.
|
|
644
|
-
* revoked by a password reset / `revokeAllTokens`). Prefer this over
|
|
645
|
-
* {@link verifyAccess} on the request path.
|
|
646
|
-
*/
|
|
647
|
-
async verifyAccessToken(accessToken) {
|
|
648
|
-
const claims = this.verifyAccess(accessToken);
|
|
649
|
-
if (this.tokenVersions) {
|
|
650
|
-
const current = await this.tokenVersions.get(claims.sub);
|
|
651
|
-
if ((claims.tv ?? 0) < current) throw new AuthTokenInvalidError();
|
|
652
|
-
}
|
|
653
|
-
return claims;
|
|
654
|
-
}
|
|
655
|
-
/**
|
|
656
|
-
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
657
|
-
* by bumping the token version. No-op unless a {@link TokenVersionStore} is
|
|
658
|
-
* configured. Pair with refresh/session revocation for a full logout.
|
|
659
|
-
*/
|
|
660
|
-
async revokeAllTokens(userId) {
|
|
661
|
-
await this.tokenVersions?.increment(userId);
|
|
662
|
-
}
|
|
663
|
-
async createSession(userId) {
|
|
664
|
-
return this.sessions.create(userId, parseDuration2(this.sessionTtl));
|
|
665
|
-
}
|
|
666
|
-
async sessionUser(sessionId) {
|
|
667
|
-
const session = await this.sessions.find(sessionId);
|
|
668
|
-
return session ? this.users.findById(session.userId) : null;
|
|
669
|
-
}
|
|
670
|
-
async logout(sessionId) {
|
|
671
|
-
const session = await this.sessions.find(sessionId);
|
|
672
|
-
await this.sessions.delete(sessionId);
|
|
673
|
-
if (session) {
|
|
674
|
-
const user = await this.users.findById(session.userId);
|
|
675
|
-
if (user) await this.hooks?.emit("auth:logout", { user: publicUser(user) });
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
// --- email verification --------------------------------------------------
|
|
679
|
-
/**
|
|
680
|
-
* Starts email verification: mints a single-use token and emits
|
|
681
|
-
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
682
|
-
* caller can build the link) or null if no account matches — never reveals
|
|
683
|
-
* whether the email exists.
|
|
684
|
-
*/
|
|
685
|
-
async requestEmailVerification(email) {
|
|
686
|
-
const user = await this.users.findByEmail(email);
|
|
687
|
-
if (!user) return null;
|
|
688
|
-
const token = await this.issueOneTimeToken(user.id, "verify_email", this.verificationTtl);
|
|
689
|
-
await this.hooks?.emit("auth:verify_requested", { user: publicUser(user), token });
|
|
690
|
-
return { user: publicUser(user), token };
|
|
691
|
-
}
|
|
692
|
-
/** Consumes a verification token and marks the user's email verified. */
|
|
693
|
-
async verifyEmail(token) {
|
|
694
|
-
const record = await this.consumeToken(token, "verify_email");
|
|
695
|
-
const user = await this.updateUser(record.userId, { emailVerified: true });
|
|
696
|
-
await this.hooks?.emit("auth:email_verified", { user: publicUser(user) });
|
|
697
|
-
return publicUser(user);
|
|
698
|
-
}
|
|
699
|
-
// --- password reset ------------------------------------------------------
|
|
700
|
-
/**
|
|
701
|
-
* Starts a password reset: mints a single-use token and emits
|
|
702
|
-
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
703
|
-
* the caller always responds 200 (no account enumeration).
|
|
704
|
-
*/
|
|
705
|
-
async requestPasswordReset(email) {
|
|
706
|
-
const user = await this.users.findByEmail(email);
|
|
707
|
-
if (!user) return null;
|
|
708
|
-
const token = await this.issueOneTimeToken(user.id, "reset_password", this.resetTtl);
|
|
709
|
-
await this.hooks?.emit("auth:password_reset_requested", { user: publicUser(user), token });
|
|
710
|
-
return { user: publicUser(user), token };
|
|
711
|
-
}
|
|
712
|
-
/**
|
|
713
|
-
* Consumes a reset token, sets the new password, and revokes every existing
|
|
714
|
-
* session/refresh token for the user (a reset logs everyone else out).
|
|
715
|
-
*/
|
|
716
|
-
async resetPassword(token, newPassword) {
|
|
717
|
-
const record = await this.consumeToken(token, "reset_password");
|
|
718
|
-
const user = await this.updateUser(record.userId, {
|
|
719
|
-
passwordHash: await this.hasher.hash(newPassword)
|
|
720
|
-
});
|
|
721
|
-
await this.refreshTokens.revokeAllForUser?.(user.id);
|
|
722
|
-
await this.sessions.deleteAllForUser?.(user.id);
|
|
723
|
-
await this.tokenVersions?.increment(user.id);
|
|
724
|
-
await this.hooks?.emit("auth:password_reset", { user: publicUser(user) });
|
|
725
|
-
return publicUser(user);
|
|
726
|
-
}
|
|
727
|
-
// --- MFA (TOTP) ----------------------------------------------------------
|
|
728
|
-
async isMfaEnabled(userId) {
|
|
729
|
-
return (await this.mfa.get(userId))?.enabled ?? false;
|
|
730
|
-
}
|
|
731
|
-
async mfaStatus(userId) {
|
|
732
|
-
const record = await this.mfa.get(userId);
|
|
733
|
-
return { enabled: record?.enabled ?? false, pending: record !== null && !record.enabled };
|
|
734
|
-
}
|
|
735
|
-
/**
|
|
736
|
-
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
737
|
-
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
738
|
-
* {@link activateMfa} with a code from the app to switch it on.
|
|
739
|
-
*/
|
|
740
|
-
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
741
|
-
encryptMfaSecret(secret) {
|
|
742
|
-
return this.mfaKey ? encryptSecret(secret, this.mfaKey) : secret;
|
|
743
|
-
}
|
|
744
|
-
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
745
|
-
decryptMfaSecret(stored) {
|
|
746
|
-
return this.mfaKey ? decryptSecret(stored, this.mfaKey) : stored;
|
|
747
|
-
}
|
|
748
|
-
async enrollMfa(userId) {
|
|
749
|
-
const user = await this.users.findById(userId);
|
|
750
|
-
if (!user) throw new AuthRequiredError();
|
|
751
|
-
const secret = generateTotpSecret();
|
|
752
|
-
await this.mfa.set(userId, { secret: this.encryptMfaSecret(secret), enabled: false, recoveryCodes: [] });
|
|
753
|
-
return {
|
|
754
|
-
secret,
|
|
755
|
-
otpauthUri: otpauthUri({ secret, account: user.email, issuer: this.mfaIssuer })
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
/**
|
|
759
|
-
* Confirms enrollment by checking a code against the pending secret, enables
|
|
760
|
-
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
761
|
-
*/
|
|
762
|
-
async activateMfa(userId, code) {
|
|
763
|
-
const record = await this.mfa.get(userId);
|
|
764
|
-
if (!record || record.enabled) throw new MfaNotEnrolledError();
|
|
765
|
-
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
766
|
-
if (step === null) throw new MfaInvalidCodeError();
|
|
767
|
-
const recoveryCodes = Array.from({ length: 10 }, () => this.generateRecoveryCode());
|
|
768
|
-
await this.mfa.set(userId, {
|
|
769
|
-
secret: record.secret,
|
|
770
|
-
enabled: true,
|
|
771
|
-
recoveryCodes: recoveryCodes.map((c) => this.hashRecoveryCode(c))
|
|
772
|
-
});
|
|
773
|
-
const user = await this.users.findById(userId);
|
|
774
|
-
if (user) await this.hooks?.emit("auth:mfa_enabled", { user: publicUser(user) });
|
|
775
|
-
return { recoveryCodes };
|
|
776
|
-
}
|
|
777
|
-
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
778
|
-
async disableMfa(userId, code) {
|
|
779
|
-
if (!await this.isMfaEnabled(userId)) throw new MfaNotEnrolledError();
|
|
780
|
-
if (!await this.verifyMfaCode(userId, code)) throw new MfaInvalidCodeError();
|
|
781
|
-
await this.mfa.delete(userId);
|
|
782
|
-
const user = await this.users.findById(userId);
|
|
783
|
-
if (user) await this.hooks?.emit("auth:mfa_disabled", { user: publicUser(user) });
|
|
784
|
-
}
|
|
785
|
-
/**
|
|
786
|
-
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
787
|
-
* is consumed on success). Returns false unless MFA is enabled.
|
|
788
|
-
*/
|
|
789
|
-
async verifyMfaCode(userId, code) {
|
|
790
|
-
const record = await this.mfa.get(userId);
|
|
791
|
-
if (!record || !record.enabled) return false;
|
|
792
|
-
const step = matchTotpStep(this.decryptMfaSecret(record.secret), code);
|
|
793
|
-
if (step !== null) {
|
|
794
|
-
if (record.lastUsedStep !== void 0 && step <= record.lastUsedStep) return false;
|
|
795
|
-
record.lastUsedStep = step;
|
|
796
|
-
await this.mfa.set(userId, record);
|
|
797
|
-
return true;
|
|
798
|
-
}
|
|
799
|
-
const hash = this.hashRecoveryCode(code);
|
|
800
|
-
const index = record.recoveryCodes.indexOf(hash);
|
|
801
|
-
if (index === -1) return false;
|
|
802
|
-
record.recoveryCodes.splice(index, 1);
|
|
803
|
-
await this.mfa.set(userId, record);
|
|
804
|
-
return true;
|
|
805
|
-
}
|
|
806
|
-
generateRecoveryCode() {
|
|
807
|
-
const raw = randomBytes5(10).toString("hex");
|
|
808
|
-
return `${raw.slice(0, 5)}-${raw.slice(5, 10)}-${raw.slice(10, 15)}-${raw.slice(15)}`;
|
|
809
|
-
}
|
|
810
|
-
hashRecoveryCode(code) {
|
|
811
|
-
return createHash3("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
|
|
812
|
-
}
|
|
813
|
-
// --- token helpers -------------------------------------------------------
|
|
814
|
-
/** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
|
|
815
|
-
* persisted, so a leak of the token/session table can't be replayed. */
|
|
816
|
-
hashToken(token) {
|
|
817
|
-
return createHash3("sha256").update(token).digest("hex");
|
|
818
|
-
}
|
|
819
|
-
async issueOneTimeToken(userId, purpose, ttl) {
|
|
820
|
-
await this.tokens.deleteForUser(userId, purpose);
|
|
821
|
-
const token = randomBytes5(32).toString("base64url");
|
|
822
|
-
await this.tokens.create({
|
|
823
|
-
token: this.hashToken(token),
|
|
824
|
-
userId,
|
|
825
|
-
purpose,
|
|
826
|
-
expiresAt: Date.now() + parseDuration2(ttl)
|
|
827
|
-
});
|
|
828
|
-
return token;
|
|
829
|
-
}
|
|
830
|
-
async consumeToken(token, purpose) {
|
|
831
|
-
const hashed = this.hashToken(token);
|
|
832
|
-
const record = await this.tokens.find(hashed);
|
|
833
|
-
if (!record || record.purpose !== purpose || record.usedAt !== void 0 || Date.now() >= record.expiresAt) {
|
|
834
|
-
throw new AuthTokenInvalidError();
|
|
835
|
-
}
|
|
836
|
-
await this.tokens.markUsed(hashed);
|
|
837
|
-
return record;
|
|
838
|
-
}
|
|
839
|
-
async updateUser(id, patch) {
|
|
840
|
-
if (!this.users.update) throw new UserUpdateUnsupportedError();
|
|
841
|
-
const user = await this.users.update(id, patch);
|
|
842
|
-
if (!user) throw new AuthTokenInvalidError();
|
|
843
|
-
return user;
|
|
844
|
-
}
|
|
845
|
-
async issueTokens(userId, familyId = randomUUID2()) {
|
|
846
|
-
const refreshToken = randomBytes5(32).toString("base64url");
|
|
847
|
-
await this.refreshTokens.create({
|
|
848
|
-
// Persist only the hash; the raw token is returned to the client below.
|
|
849
|
-
token: this.hashToken(refreshToken),
|
|
850
|
-
familyId,
|
|
851
|
-
userId,
|
|
852
|
-
expiresAt: Date.now() + parseDuration2(this.refreshTtl)
|
|
853
|
-
});
|
|
854
|
-
const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : void 0;
|
|
855
|
-
return {
|
|
856
|
-
accessToken: signJwt(
|
|
857
|
-
{ sub: userId, ...tv !== void 0 ? { tv } : {} },
|
|
858
|
-
{ secret: this.secret, expiresIn: this.accessTtl }
|
|
859
|
-
),
|
|
860
|
-
refreshToken
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
};
|
|
864
|
-
|
|
865
|
-
// src/plugin.ts
|
|
866
|
-
import { createToken, definePlugin, ensureMetadata } from "@basaltkit/core";
|
|
867
|
-
var AUTH = createToken("auth");
|
|
868
|
-
function authPlugin(options) {
|
|
869
|
-
return definePlugin({
|
|
870
|
-
name: "basalt:auth",
|
|
871
|
-
register({ container, hooks }) {
|
|
872
|
-
container.singleton(AUTH, () => new Auth({ ...options, hooks }));
|
|
873
|
-
const metadata = ensureMetadata(container);
|
|
874
|
-
const enricher = async ({ request, context, container: c }) => {
|
|
875
|
-
const auth2 = c.get(AUTH);
|
|
876
|
-
const header = request.headers.authorization;
|
|
877
|
-
const bearer = typeof header === "string" && header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
|
|
878
|
-
if (bearer && !bearer.startsWith("mk_")) {
|
|
879
|
-
const claims = await auth2.verifyAccessToken(bearer);
|
|
880
|
-
const user = await auth2.users.findById(claims.sub);
|
|
881
|
-
if (user) context.user = publicUser(user);
|
|
882
|
-
return;
|
|
883
|
-
}
|
|
884
|
-
const sessionId = request.headers["x-session-id"];
|
|
885
|
-
if (typeof sessionId === "string") {
|
|
886
|
-
const user = await auth2.sessionUser(sessionId);
|
|
887
|
-
if (user) context.user = publicUser(user);
|
|
888
|
-
}
|
|
889
|
-
};
|
|
890
|
-
metadata.add("http:enrichers", enricher);
|
|
891
|
-
const guard = ({ route: route3, context }) => {
|
|
892
|
-
if (route3.meta?.["auth"] === true && !context.user) throw new AuthRequiredError();
|
|
893
|
-
};
|
|
894
|
-
metadata.add("http:guards", guard);
|
|
895
|
-
}
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
// src/apikeys.ts
|
|
900
|
-
import { createHash as createHash4, randomBytes as randomBytes6, randomUUID as randomUUID3 } from "crypto";
|
|
901
|
-
import { BasaltError as BasaltError4 } from "@basaltkit/core";
|
|
902
|
-
var ScopeRequiredError = class extends BasaltError4 {
|
|
903
|
-
status = 403;
|
|
904
|
-
constructor(scope) {
|
|
905
|
-
super("AUTH_SCOPE_REQUIRED", `This action requires the "${scope}" scope.`);
|
|
906
|
-
}
|
|
907
|
-
};
|
|
908
|
-
var KEY_PREFIX = "mk_live_";
|
|
909
|
-
var hashKey = (key) => createHash4("sha256").update(key).digest("hex");
|
|
910
|
-
var strip = (record) => {
|
|
911
|
-
const { hash: _hash, ...info } = record;
|
|
912
|
-
return info;
|
|
913
|
-
};
|
|
914
|
-
var scopesSatisfy = (granted, required) => granted.includes("*") || required.every((scope) => granted.includes(scope));
|
|
915
|
-
var ApiKeys = class {
|
|
916
|
-
store;
|
|
917
|
-
hooks;
|
|
918
|
-
now;
|
|
919
|
-
constructor(options = {}) {
|
|
920
|
-
this.store = options.store ?? new MemoryApiKeyStore();
|
|
921
|
-
this.hooks = options.hooks;
|
|
922
|
-
this.now = options.now ?? Date.now;
|
|
923
|
-
}
|
|
924
|
-
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
925
|
-
async issue(input) {
|
|
926
|
-
const secret = randomBytes6(24).toString("base64url");
|
|
927
|
-
const key = `${KEY_PREFIX}${secret}`;
|
|
928
|
-
const record = {
|
|
929
|
-
id: randomUUID3(),
|
|
930
|
-
name: input.name,
|
|
931
|
-
prefix: `${KEY_PREFIX}${secret.slice(0, 6)}`,
|
|
932
|
-
hash: hashKey(key),
|
|
933
|
-
scopes: input.scopes ?? ["*"],
|
|
934
|
-
createdAt: this.now(),
|
|
935
|
-
...input.tenantId !== void 0 ? { tenantId: input.tenantId } : {},
|
|
936
|
-
...input.userId !== void 0 ? { userId: input.userId } : {}
|
|
937
|
-
};
|
|
938
|
-
await this.store.create(record);
|
|
939
|
-
await this.hooks?.emit("auth:apikey_issued", {
|
|
940
|
-
id: record.id,
|
|
941
|
-
...record.tenantId !== void 0 ? { tenantId: record.tenantId } : {},
|
|
942
|
-
...record.userId !== void 0 ? { userId: record.userId } : {}
|
|
943
|
-
});
|
|
944
|
-
return { record: strip(record), key };
|
|
945
|
-
}
|
|
946
|
-
/**
|
|
947
|
-
* Resolves a presented key to its record, or null if it's malformed,
|
|
948
|
-
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
949
|
-
*/
|
|
950
|
-
async verify(presented) {
|
|
951
|
-
if (!presented.startsWith(KEY_PREFIX)) return null;
|
|
952
|
-
const record = await this.store.findByHash(hashKey(presented));
|
|
953
|
-
if (!record || record.revokedAt !== void 0) return null;
|
|
954
|
-
await this.store.touch(record.id, this.now());
|
|
955
|
-
return record;
|
|
956
|
-
}
|
|
957
|
-
async list(filter) {
|
|
958
|
-
return (await this.store.list(filter)).map(strip);
|
|
959
|
-
}
|
|
960
|
-
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
961
|
-
async revoke(id) {
|
|
962
|
-
const record = await this.store.findById(id);
|
|
963
|
-
if (record && record.revokedAt === void 0) {
|
|
964
|
-
await this.store.revoke(id, this.now());
|
|
965
|
-
await this.hooks?.emit("auth:apikey_revoked", { id });
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
/** Reads a single key's public info (used to authorize a revoke). */
|
|
969
|
-
async get(id) {
|
|
970
|
-
const record = await this.store.findById(id);
|
|
971
|
-
return record ? strip(record) : null;
|
|
972
|
-
}
|
|
973
|
-
};
|
|
974
|
-
|
|
975
|
-
// src/apikeys-plugin.ts
|
|
976
|
-
import { createToken as createToken2, definePlugin as definePlugin2, ensureMetadata as ensureMetadata2 } from "@basaltkit/core";
|
|
977
|
-
var API_KEYS = createToken2("auth:apikeys");
|
|
978
|
-
function apiKeysPlugin(options = {}) {
|
|
979
|
-
const header = options.header ?? "x-api-key";
|
|
980
|
-
return definePlugin2({
|
|
981
|
-
name: "basalt:apikeys",
|
|
982
|
-
register({ container, hooks }) {
|
|
983
|
-
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
984
|
-
const metadata = ensureMetadata2(container);
|
|
985
|
-
const enricher = async ({ request, context, container: c }) => {
|
|
986
|
-
const authHeader = request.headers.authorization;
|
|
987
|
-
const bearer = typeof authHeader === "string" && authHeader.startsWith("Bearer mk_") ? authHeader.slice("Bearer ".length) : void 0;
|
|
988
|
-
const custom = request.headers[header];
|
|
989
|
-
const presented = bearer ?? (typeof custom === "string" ? custom : void 0);
|
|
990
|
-
if (!presented) return;
|
|
991
|
-
const record = await c.get(API_KEYS).verify(presented);
|
|
992
|
-
if (!record) return;
|
|
993
|
-
context.apiKey = {
|
|
994
|
-
id: record.id,
|
|
995
|
-
scopes: record.scopes,
|
|
996
|
-
...record.tenantId !== void 0 ? { tenantId: record.tenantId } : {},
|
|
997
|
-
...record.userId !== void 0 ? { userId: record.userId } : {}
|
|
998
|
-
};
|
|
999
|
-
if (record.userId && options.users) {
|
|
1000
|
-
const user = await options.users.findById(record.userId);
|
|
1001
|
-
if (user) context.user = publicUser(user);
|
|
1002
|
-
}
|
|
1003
|
-
};
|
|
1004
|
-
metadata.add("http:enrichers", enricher);
|
|
1005
|
-
const guard = ({ route: route3, context }) => {
|
|
1006
|
-
const required = route3.meta?.["scopes"];
|
|
1007
|
-
if (!Array.isArray(required) || required.length === 0) return;
|
|
1008
|
-
const granted = context.apiKey?.scopes ?? [];
|
|
1009
|
-
for (const scope of required) {
|
|
1010
|
-
if (!scopesSatisfy(granted, [scope])) throw new ScopeRequiredError(scope);
|
|
1011
|
-
}
|
|
1012
|
-
};
|
|
1013
|
-
metadata.add("http:guards", guard);
|
|
1014
|
-
}
|
|
1015
|
-
});
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
// src/routes.ts
|
|
1019
|
-
import { ctx, BasaltError as BasaltError5 } from "@basaltkit/core";
|
|
1020
|
-
import { route } from "@basaltkit/fastify";
|
|
1021
|
-
import { z } from "zod";
|
|
1022
|
-
var credentials = z.object({ email: z.string().email(), password: z.string().min(8) });
|
|
1023
|
-
var auth = () => ctx().container.get(AUTH);
|
|
1024
|
-
var apiKeys = () => ctx().container.get(API_KEYS);
|
|
1025
|
-
function authRoutes() {
|
|
1026
|
-
return [
|
|
1027
|
-
route({
|
|
1028
|
-
method: "POST",
|
|
1029
|
-
url: "/auth/register",
|
|
1030
|
-
body: credentials,
|
|
1031
|
-
// Enumeration-safe: the same 202 whether the email is new or already taken
|
|
1032
|
-
// (a collision is signalled out-of-band via auth:register_existing_email).
|
|
1033
|
-
async handler({ body, reply }) {
|
|
1034
|
-
await auth().registerSafely(body.email, body.password);
|
|
1035
|
-
return reply.code(202).send({ ok: true });
|
|
1036
|
-
}
|
|
1037
|
-
}),
|
|
1038
|
-
route({
|
|
1039
|
-
method: "POST",
|
|
1040
|
-
url: "/auth/login",
|
|
1041
|
-
body: credentials.extend({ mfaCode: z.string().optional() }),
|
|
1042
|
-
async handler({ body, request }) {
|
|
1043
|
-
const { user, tokens } = await auth().login(
|
|
1044
|
-
body.email,
|
|
1045
|
-
body.password,
|
|
1046
|
-
body.mfaCode,
|
|
1047
|
-
request.ip ? { ip: request.ip } : {}
|
|
1048
|
-
);
|
|
1049
|
-
return { user, ...tokens };
|
|
1050
|
-
}
|
|
1051
|
-
}),
|
|
1052
|
-
route({
|
|
1053
|
-
method: "POST",
|
|
1054
|
-
url: "/auth/refresh",
|
|
1055
|
-
body: z.object({ refreshToken: z.string() }),
|
|
1056
|
-
async handler({ body }) {
|
|
1057
|
-
return auth().refresh(body.refreshToken);
|
|
1058
|
-
}
|
|
1059
|
-
}),
|
|
1060
|
-
route({
|
|
1061
|
-
method: "POST",
|
|
1062
|
-
url: "/auth/logout",
|
|
1063
|
-
body: z.object({ refreshToken: z.string() }),
|
|
1064
|
-
async handler({ body, reply }) {
|
|
1065
|
-
await auth().revoke(body.refreshToken);
|
|
1066
|
-
return reply.code(204).send();
|
|
1067
|
-
}
|
|
1068
|
-
}),
|
|
1069
|
-
route({
|
|
1070
|
-
method: "GET",
|
|
1071
|
-
url: "/auth/me",
|
|
1072
|
-
meta: { auth: true },
|
|
1073
|
-
async handler() {
|
|
1074
|
-
return ctx().user;
|
|
1075
|
-
}
|
|
1076
|
-
}),
|
|
1077
|
-
// --- email verification ------------------------------------------------
|
|
1078
|
-
route({
|
|
1079
|
-
method: "POST",
|
|
1080
|
-
url: "/auth/verify/request",
|
|
1081
|
-
body: z.object({ email: z.string().email() }),
|
|
1082
|
-
async handler({ body }) {
|
|
1083
|
-
await auth().requestEmailVerification(body.email);
|
|
1084
|
-
return { ok: true };
|
|
1085
|
-
}
|
|
1086
|
-
}),
|
|
1087
|
-
route({
|
|
1088
|
-
method: "POST",
|
|
1089
|
-
url: "/auth/verify",
|
|
1090
|
-
body: z.object({ token: z.string() }),
|
|
1091
|
-
async handler({ body }) {
|
|
1092
|
-
return { user: await auth().verifyEmail(body.token) };
|
|
1093
|
-
}
|
|
1094
|
-
}),
|
|
1095
|
-
// --- password reset ----------------------------------------------------
|
|
1096
|
-
route({
|
|
1097
|
-
method: "POST",
|
|
1098
|
-
url: "/auth/password/forgot",
|
|
1099
|
-
body: z.object({ email: z.string().email() }),
|
|
1100
|
-
async handler({ body }) {
|
|
1101
|
-
await auth().requestPasswordReset(body.email);
|
|
1102
|
-
return { ok: true };
|
|
1103
|
-
}
|
|
1104
|
-
}),
|
|
1105
|
-
route({
|
|
1106
|
-
method: "POST",
|
|
1107
|
-
url: "/auth/password/reset",
|
|
1108
|
-
body: z.object({ token: z.string(), password: z.string().min(8) }),
|
|
1109
|
-
async handler({ body }) {
|
|
1110
|
-
await auth().resetPassword(body.token, body.password);
|
|
1111
|
-
return { ok: true };
|
|
1112
|
-
}
|
|
1113
|
-
})
|
|
1114
|
-
];
|
|
1115
|
-
}
|
|
1116
|
-
var ApiKeyForbiddenError = class extends BasaltError5 {
|
|
1117
|
-
status = 404;
|
|
1118
|
-
constructor() {
|
|
1119
|
-
super("AUTH_APIKEY_NOT_FOUND", "API key not found.");
|
|
1120
|
-
}
|
|
1121
|
-
};
|
|
1122
|
-
function apiKeyRoutes() {
|
|
1123
|
-
const scope = () => {
|
|
1124
|
-
const c = ctx();
|
|
1125
|
-
return {
|
|
1126
|
-
...c.tenant ? { tenantId: c.tenant.id } : {},
|
|
1127
|
-
...c.user ? { userId: c.user.id } : {}
|
|
1128
|
-
};
|
|
1129
|
-
};
|
|
1130
|
-
return [
|
|
1131
|
-
route({
|
|
1132
|
-
method: "POST",
|
|
1133
|
-
url: "/apikeys",
|
|
1134
|
-
meta: { auth: true },
|
|
1135
|
-
body: z.object({
|
|
1136
|
-
name: z.string().min(1).max(100),
|
|
1137
|
-
scopes: z.array(z.string().min(1)).optional()
|
|
1138
|
-
}),
|
|
1139
|
-
async handler({ body, reply }) {
|
|
1140
|
-
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
|
1141
|
-
return reply.code(201).send({ ...record, key });
|
|
1142
|
-
}
|
|
1143
|
-
}),
|
|
1144
|
-
route({
|
|
1145
|
-
method: "GET",
|
|
1146
|
-
url: "/apikeys",
|
|
1147
|
-
meta: { auth: true },
|
|
1148
|
-
async handler() {
|
|
1149
|
-
return apiKeys().list(scope());
|
|
1150
|
-
}
|
|
1151
|
-
}),
|
|
1152
|
-
route({
|
|
1153
|
-
method: "DELETE",
|
|
1154
|
-
url: "/apikeys/:id",
|
|
1155
|
-
meta: { auth: true },
|
|
1156
|
-
params: z.object({ id: z.string() }),
|
|
1157
|
-
async handler({ params, reply }) {
|
|
1158
|
-
const record = await apiKeys().get(params.id);
|
|
1159
|
-
const { tenantId, userId } = scope();
|
|
1160
|
-
if (!record || record.tenantId !== tenantId || record.userId !== userId) {
|
|
1161
|
-
throw new ApiKeyForbiddenError();
|
|
1162
|
-
}
|
|
1163
|
-
await apiKeys().revoke(params.id);
|
|
1164
|
-
return reply.code(204).send();
|
|
1165
|
-
}
|
|
1166
|
-
})
|
|
1167
|
-
];
|
|
1168
|
-
}
|
|
1169
|
-
var MfaAuthRequiredError = class extends BasaltError5 {
|
|
1170
|
-
status = 401;
|
|
1171
|
-
constructor() {
|
|
1172
|
-
super("AUTH_REQUIRED", "Authentication required.");
|
|
1173
|
-
}
|
|
1174
|
-
};
|
|
1175
|
-
var currentUserId = () => {
|
|
1176
|
-
const id = ctx().user?.id;
|
|
1177
|
-
if (!id) throw new MfaAuthRequiredError();
|
|
1178
|
-
return id;
|
|
1179
|
-
};
|
|
1180
|
-
function mfaRoutes() {
|
|
1181
|
-
return [
|
|
1182
|
-
route({
|
|
1183
|
-
method: "POST",
|
|
1184
|
-
url: "/auth/mfa/enroll",
|
|
1185
|
-
meta: { auth: true },
|
|
1186
|
-
async handler() {
|
|
1187
|
-
return auth().enrollMfa(currentUserId());
|
|
1188
|
-
}
|
|
1189
|
-
}),
|
|
1190
|
-
route({
|
|
1191
|
-
method: "POST",
|
|
1192
|
-
url: "/auth/mfa/activate",
|
|
1193
|
-
meta: { auth: true },
|
|
1194
|
-
body: z.object({ code: z.string().min(6) }),
|
|
1195
|
-
async handler({ body }) {
|
|
1196
|
-
return auth().activateMfa(currentUserId(), body.code);
|
|
1197
|
-
}
|
|
1198
|
-
}),
|
|
1199
|
-
route({
|
|
1200
|
-
method: "GET",
|
|
1201
|
-
url: "/auth/mfa/status",
|
|
1202
|
-
meta: { auth: true },
|
|
1203
|
-
async handler() {
|
|
1204
|
-
return auth().mfaStatus(currentUserId());
|
|
1205
|
-
}
|
|
1206
|
-
}),
|
|
1207
|
-
route({
|
|
1208
|
-
method: "POST",
|
|
1209
|
-
url: "/auth/mfa/disable",
|
|
1210
|
-
meta: { auth: true },
|
|
1211
|
-
body: z.object({ code: z.string().min(6) }),
|
|
1212
|
-
async handler({ body, reply }) {
|
|
1213
|
-
await auth().disableMfa(currentUserId(), body.code);
|
|
1214
|
-
return reply.code(204).send();
|
|
1215
|
-
}
|
|
1216
|
-
})
|
|
1217
|
-
];
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
// src/oauth.ts
|
|
1221
|
-
import { createHmac as createHmac3, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
1222
|
-
import { BasaltError as BasaltError6 } from "@basaltkit/core";
|
|
1223
|
-
var OAuthProviderUnknownError = class extends BasaltError6 {
|
|
1224
|
-
status = 404;
|
|
1225
|
-
constructor(name) {
|
|
1226
|
-
super("AUTH_OAUTH_UNKNOWN_PROVIDER", `Unknown OAuth provider "${name}".`);
|
|
1227
|
-
}
|
|
1228
|
-
};
|
|
1229
|
-
var OAuthStateInvalidError = class extends BasaltError6 {
|
|
1230
|
-
status = 400;
|
|
1231
|
-
constructor() {
|
|
1232
|
-
super("AUTH_OAUTH_STATE_INVALID", "The OAuth state is missing, invalid, tampered with, or expired.");
|
|
1233
|
-
}
|
|
1234
|
-
};
|
|
1235
|
-
var OAuthExchangeError = class extends BasaltError6 {
|
|
1236
|
-
status = 502;
|
|
1237
|
-
constructor(detail) {
|
|
1238
|
-
super("AUTH_OAUTH_EXCHANGE_FAILED", `OAuth token/profile exchange failed: ${detail}`);
|
|
1239
|
-
}
|
|
1240
|
-
};
|
|
1241
|
-
function googleProvider(keys) {
|
|
1242
|
-
return {
|
|
1243
|
-
name: "google",
|
|
1244
|
-
authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
1245
|
-
tokenUrl: "https://oauth2.googleapis.com/token",
|
|
1246
|
-
clientId: keys.clientId,
|
|
1247
|
-
clientSecret: keys.clientSecret,
|
|
1248
|
-
scopes: keys.scopes ?? ["openid", "email", "profile"],
|
|
1249
|
-
async fetchProfile(accessToken, doFetch) {
|
|
1250
|
-
const res = await doFetch("https://openidconnect.googleapis.com/v1/userinfo", {
|
|
1251
|
-
headers: { authorization: `Bearer ${accessToken}` }
|
|
1252
|
-
});
|
|
1253
|
-
if (!res.ok) throw new OAuthExchangeError(`google userinfo HTTP ${res.status}`);
|
|
1254
|
-
const p = await res.json();
|
|
1255
|
-
return {
|
|
1256
|
-
subject: String(p.sub),
|
|
1257
|
-
email: String(p.email),
|
|
1258
|
-
emailVerified: p.email_verified === true,
|
|
1259
|
-
...p.name ? { name: p.name } : {}
|
|
1260
|
-
};
|
|
1261
|
-
}
|
|
1262
|
-
};
|
|
1263
|
-
}
|
|
1264
|
-
function githubProvider(keys) {
|
|
1265
|
-
return {
|
|
1266
|
-
name: "github",
|
|
1267
|
-
authorizeUrl: "https://github.com/login/oauth/authorize",
|
|
1268
|
-
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
1269
|
-
clientId: keys.clientId,
|
|
1270
|
-
clientSecret: keys.clientSecret,
|
|
1271
|
-
scopes: keys.scopes ?? ["read:user", "user:email"],
|
|
1272
|
-
async fetchProfile(accessToken, doFetch) {
|
|
1273
|
-
const headers = { authorization: `Bearer ${accessToken}`, accept: "application/vnd.github+json" };
|
|
1274
|
-
const userRes = await doFetch("https://api.github.com/user", { headers });
|
|
1275
|
-
if (!userRes.ok) throw new OAuthExchangeError(`github user HTTP ${userRes.status}`);
|
|
1276
|
-
const user = await userRes.json();
|
|
1277
|
-
let email = user.email ?? void 0;
|
|
1278
|
-
let emailVerified = false;
|
|
1279
|
-
const emailsRes = await doFetch("https://api.github.com/user/emails", { headers });
|
|
1280
|
-
if (emailsRes.ok) {
|
|
1281
|
-
const emails = await emailsRes.json();
|
|
1282
|
-
const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
|
|
1283
|
-
if (primary) {
|
|
1284
|
-
email = primary.email;
|
|
1285
|
-
emailVerified = true;
|
|
1286
|
-
}
|
|
1287
|
-
}
|
|
1288
|
-
if (!email) throw new OAuthExchangeError("github returned no usable email");
|
|
1289
|
-
return { subject: String(user.id), email, emailVerified, ...user.name ? { name: user.name } : {} };
|
|
1290
|
-
}
|
|
1291
|
-
};
|
|
1292
|
-
}
|
|
1293
|
-
function oidcProvider(config) {
|
|
1294
|
-
return {
|
|
1295
|
-
name: config.name ?? "oidc",
|
|
1296
|
-
authorizeUrl: config.authorizeUrl,
|
|
1297
|
-
tokenUrl: config.tokenUrl,
|
|
1298
|
-
clientId: config.clientId,
|
|
1299
|
-
clientSecret: config.clientSecret,
|
|
1300
|
-
scopes: config.scopes ?? ["openid", "email", "profile"],
|
|
1301
|
-
async fetchProfile(accessToken, doFetch) {
|
|
1302
|
-
const res = await doFetch(config.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } });
|
|
1303
|
-
if (!res.ok) throw new OAuthExchangeError(`oidc userinfo HTTP ${res.status}`);
|
|
1304
|
-
const p = await res.json();
|
|
1305
|
-
return {
|
|
1306
|
-
subject: String(p.sub),
|
|
1307
|
-
email: String(p.email),
|
|
1308
|
-
emailVerified: p.email_verified === true,
|
|
1309
|
-
...p.name ? { name: p.name } : {}
|
|
1310
|
-
};
|
|
1311
|
-
}
|
|
1312
|
-
};
|
|
1313
|
-
}
|
|
1314
|
-
async function discoverOidcProvider(config) {
|
|
1315
|
-
const doFetch = config.fetch ?? globalThis.fetch;
|
|
1316
|
-
const url = `${config.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
|
|
1317
|
-
const res = await doFetch(url);
|
|
1318
|
-
if (!res.ok) throw new OAuthExchangeError(`OIDC discovery HTTP ${res.status} for ${url}`);
|
|
1319
|
-
const meta = await res.json();
|
|
1320
|
-
if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.userinfo_endpoint) {
|
|
1321
|
-
throw new OAuthExchangeError("OIDC discovery document is missing required endpoints");
|
|
1322
|
-
}
|
|
1323
|
-
return oidcProvider({
|
|
1324
|
-
...config.name ? { name: config.name } : {},
|
|
1325
|
-
authorizeUrl: meta.authorization_endpoint,
|
|
1326
|
-
tokenUrl: meta.token_endpoint,
|
|
1327
|
-
userInfoUrl: meta.userinfo_endpoint,
|
|
1328
|
-
clientId: config.clientId,
|
|
1329
|
-
clientSecret: config.clientSecret,
|
|
1330
|
-
...config.scopes ? { scopes: config.scopes } : {}
|
|
1331
|
-
});
|
|
1332
|
-
}
|
|
1333
|
-
var OAuth = class {
|
|
1334
|
-
constructor(auth2, providers, options) {
|
|
1335
|
-
this.auth = auth2;
|
|
1336
|
-
this.options = options;
|
|
1337
|
-
this.providers = new Map(providers.map((p) => [p.name, p]));
|
|
1338
|
-
this.doFetch = options.fetch ?? globalThis.fetch;
|
|
1339
|
-
this.now = options.now ?? Date.now;
|
|
1340
|
-
this.stateTtl = options.stateTtlMs ?? 10 * 6e4;
|
|
1341
|
-
}
|
|
1342
|
-
auth;
|
|
1343
|
-
options;
|
|
1344
|
-
providers;
|
|
1345
|
-
doFetch;
|
|
1346
|
-
now;
|
|
1347
|
-
stateTtl;
|
|
1348
|
-
names() {
|
|
1349
|
-
return [...this.providers.keys()];
|
|
1350
|
-
}
|
|
1351
|
-
provider(name) {
|
|
1352
|
-
const p = this.providers.get(name);
|
|
1353
|
-
if (!p) throw new OAuthProviderUnknownError(name);
|
|
1354
|
-
return p;
|
|
1355
|
-
}
|
|
1356
|
-
/** The provider's authorization URL to redirect the browser to. */
|
|
1357
|
-
authorizeUrl(name, redirectUri) {
|
|
1358
|
-
const p = this.provider(name);
|
|
1359
|
-
const state = this.signState({ n: randomBytes7(16).toString("hex"), e: this.now() + this.stateTtl, p: name });
|
|
1360
|
-
const params = new URLSearchParams({
|
|
1361
|
-
client_id: p.clientId,
|
|
1362
|
-
redirect_uri: redirectUri,
|
|
1363
|
-
response_type: "code",
|
|
1364
|
-
scope: p.scopes.join(" "),
|
|
1365
|
-
state
|
|
1366
|
-
});
|
|
1367
|
-
return `${p.authorizeUrl}?${params.toString()}`;
|
|
1368
|
-
}
|
|
1369
|
-
/** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
|
|
1370
|
-
async callback(name, input) {
|
|
1371
|
-
const payload = this.verifyState(input.state);
|
|
1372
|
-
if (payload.p !== name) throw new OAuthStateInvalidError();
|
|
1373
|
-
const p = this.provider(name);
|
|
1374
|
-
const accessToken = await this.exchangeCode(p, input.code, input.redirectUri);
|
|
1375
|
-
const profile = await p.fetchProfile(accessToken, this.doFetch);
|
|
1376
|
-
if (!profile.email) throw new OAuthExchangeError("provider returned no email");
|
|
1377
|
-
return this.auth.socialLogin(profile.email, { emailVerified: profile.emailVerified === true });
|
|
1378
|
-
}
|
|
1379
|
-
async exchangeCode(p, code, redirectUri) {
|
|
1380
|
-
const res = await this.doFetch(p.tokenUrl, {
|
|
1381
|
-
method: "POST",
|
|
1382
|
-
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
1383
|
-
body: new URLSearchParams({
|
|
1384
|
-
grant_type: "authorization_code",
|
|
1385
|
-
code,
|
|
1386
|
-
redirect_uri: redirectUri,
|
|
1387
|
-
client_id: p.clientId,
|
|
1388
|
-
client_secret: p.clientSecret
|
|
1389
|
-
}).toString()
|
|
1390
|
-
});
|
|
1391
|
-
const text = await res.text();
|
|
1392
|
-
const json = text ? JSON.parse(text) : {};
|
|
1393
|
-
if (!res.ok || !json.access_token) {
|
|
1394
|
-
throw new OAuthExchangeError(json.error_description ?? json.error ?? `token endpoint HTTP ${res.status}`);
|
|
1395
|
-
}
|
|
1396
|
-
return json.access_token;
|
|
1397
|
-
}
|
|
1398
|
-
signState(payload) {
|
|
1399
|
-
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
1400
|
-
const sig = createHmac3("sha256", this.options.secret).update(body).digest("base64url");
|
|
1401
|
-
return `${body}.${sig}`;
|
|
1402
|
-
}
|
|
1403
|
-
verifyState(state) {
|
|
1404
|
-
if (!state) throw new OAuthStateInvalidError();
|
|
1405
|
-
const dot = state.indexOf(".");
|
|
1406
|
-
if (dot < 0) throw new OAuthStateInvalidError();
|
|
1407
|
-
const body = state.slice(0, dot);
|
|
1408
|
-
const sig = state.slice(dot + 1);
|
|
1409
|
-
const expected = createHmac3("sha256", this.options.secret).update(body).digest("base64url");
|
|
1410
|
-
const a = Buffer.from(sig);
|
|
1411
|
-
const b = Buffer.from(expected);
|
|
1412
|
-
if (a.length !== b.length || !timingSafeEqual4(a, b)) throw new OAuthStateInvalidError();
|
|
1413
|
-
let payload;
|
|
1414
|
-
try {
|
|
1415
|
-
payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
1416
|
-
} catch {
|
|
1417
|
-
throw new OAuthStateInvalidError();
|
|
1418
|
-
}
|
|
1419
|
-
if (typeof payload.e !== "number" || this.now() > payload.e) throw new OAuthStateInvalidError();
|
|
1420
|
-
return payload;
|
|
1421
|
-
}
|
|
1422
|
-
};
|
|
1423
|
-
|
|
1424
|
-
// src/oauth-plugin.ts
|
|
1425
|
-
import { createToken as createToken3, ctx as ctx2, definePlugin as definePlugin3 } from "@basaltkit/core";
|
|
1426
|
-
import { route as route2 } from "@basaltkit/fastify";
|
|
1427
|
-
import { z as z2 } from "zod";
|
|
1428
|
-
var OAUTH = createToken3("auth.oauth");
|
|
1429
|
-
function oauthPlugin(options) {
|
|
1430
|
-
const { providers, ...oauthOptions } = options;
|
|
1431
|
-
return definePlugin3({
|
|
1432
|
-
name: "basalt:auth:oauth",
|
|
1433
|
-
register({ container }) {
|
|
1434
|
-
container.singleton(OAUTH, (c) => new OAuth(c.get(AUTH), providers, oauthOptions));
|
|
1435
|
-
}
|
|
1436
|
-
});
|
|
1437
|
-
}
|
|
1438
|
-
function oauthRoutes(options) {
|
|
1439
|
-
const oauth = () => ctx2().container.get(OAUTH);
|
|
1440
|
-
const base = options.callbackBaseUrl.replace(/\/+$/, "");
|
|
1441
|
-
const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
|
|
1442
|
-
return [
|
|
1443
|
-
route2({
|
|
1444
|
-
method: "GET",
|
|
1445
|
-
url: "/auth/oauth/:provider",
|
|
1446
|
-
params: z2.object({ provider: z2.string() }),
|
|
1447
|
-
async handler({ params, reply }) {
|
|
1448
|
-
const url = oauth().authorizeUrl(params.provider, redirectUri(params.provider));
|
|
1449
|
-
return reply.code(302).header("location", url).send();
|
|
1450
|
-
}
|
|
1451
|
-
}),
|
|
1452
|
-
route2({
|
|
1453
|
-
method: "GET",
|
|
1454
|
-
url: "/auth/oauth/:provider/callback",
|
|
1455
|
-
params: z2.object({ provider: z2.string() }),
|
|
1456
|
-
query: z2.object({ code: z2.string(), state: z2.string() }),
|
|
1457
|
-
async handler({ params, query, reply }) {
|
|
1458
|
-
const { user, tokens } = await oauth().callback(params.provider, {
|
|
1459
|
-
code: query.code,
|
|
1460
|
-
state: query.state,
|
|
1461
|
-
redirectUri: redirectUri(params.provider)
|
|
1462
|
-
});
|
|
1463
|
-
if (options.successRedirect) {
|
|
1464
|
-
const url = new URL(options.successRedirect);
|
|
1465
|
-
url.hash = new URLSearchParams({
|
|
1466
|
-
access_token: tokens.accessToken,
|
|
1467
|
-
refresh_token: tokens.refreshToken
|
|
1468
|
-
}).toString();
|
|
1469
|
-
return reply.code(302).header("location", url.toString()).send();
|
|
1470
|
-
}
|
|
1471
|
-
return { user, ...tokens };
|
|
1472
|
-
}
|
|
1473
|
-
})
|
|
1474
|
-
];
|
|
1475
|
-
}
|
|
1476
|
-
|
|
1477
|
-
// src/webauthn.ts
|
|
1478
|
-
import { randomBytes as randomBytes8 } from "crypto";
|
|
1479
|
-
import { BasaltError as BasaltError7 } from "@basaltkit/core";
|
|
1480
|
-
var MemoryPasskeyStore = class {
|
|
1481
|
-
byId = /* @__PURE__ */ new Map();
|
|
1482
|
-
async add(credential) {
|
|
1483
|
-
this.byId.set(credential.id, { ...credential });
|
|
1484
|
-
}
|
|
1485
|
-
async get(credentialId) {
|
|
1486
|
-
const found = this.byId.get(credentialId);
|
|
1487
|
-
return found ? { ...found } : null;
|
|
1488
|
-
}
|
|
1489
|
-
async forUser(userId) {
|
|
1490
|
-
return [...this.byId.values()].filter((c) => c.userId === userId).map((c) => ({ ...c }));
|
|
1491
|
-
}
|
|
1492
|
-
async updateCounter(credentialId, counter, lastUsedAt) {
|
|
1493
|
-
const found = this.byId.get(credentialId);
|
|
1494
|
-
if (found) {
|
|
1495
|
-
found.counter = counter;
|
|
1496
|
-
found.lastUsedAt = lastUsedAt;
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
async remove(credentialId) {
|
|
1500
|
-
this.byId.delete(credentialId);
|
|
1501
|
-
}
|
|
1502
|
-
};
|
|
1503
|
-
var MemoryWebAuthnChallengeStore = class {
|
|
1504
|
-
entries = /* @__PURE__ */ new Map();
|
|
1505
|
-
now;
|
|
1506
|
-
constructor(options = {}) {
|
|
1507
|
-
this.now = options.now ?? (() => Date.now());
|
|
1508
|
-
}
|
|
1509
|
-
async save(key, challenge, expiresAt) {
|
|
1510
|
-
this.entries.set(key, { challenge, expiresAt });
|
|
1511
|
-
}
|
|
1512
|
-
async take(key) {
|
|
1513
|
-
const entry = this.entries.get(key);
|
|
1514
|
-
if (!entry) return null;
|
|
1515
|
-
this.entries.delete(key);
|
|
1516
|
-
return entry.expiresAt > this.now() ? entry.challenge : null;
|
|
1517
|
-
}
|
|
1518
|
-
};
|
|
1519
|
-
var DEFAULT_PUB_KEY_PARAMS = [
|
|
1520
|
-
{ type: "public-key", alg: -7 },
|
|
1521
|
-
{ type: "public-key", alg: -257 }
|
|
1522
|
-
];
|
|
1523
|
-
var WebAuthnChallengeError = class extends BasaltError7 {
|
|
1524
|
-
status = 400;
|
|
1525
|
-
constructor() {
|
|
1526
|
-
super("WEBAUTHN_CHALLENGE_INVALID", "No matching WebAuthn challenge \u2014 it expired or was already used.");
|
|
1527
|
-
}
|
|
1528
|
-
};
|
|
1529
|
-
var WebAuthnVerificationError = class extends BasaltError7 {
|
|
1530
|
-
status = 400;
|
|
1531
|
-
constructor() {
|
|
1532
|
-
super("WEBAUTHN_VERIFICATION_FAILED", "The WebAuthn response could not be verified.");
|
|
1533
|
-
}
|
|
1534
|
-
};
|
|
1535
|
-
var PasskeyNotFoundError = class extends BasaltError7 {
|
|
1536
|
-
status = 404;
|
|
1537
|
-
constructor() {
|
|
1538
|
-
super("PASSKEY_NOT_FOUND", "No passkey matches the presented credential.");
|
|
1539
|
-
}
|
|
1540
|
-
};
|
|
1541
|
-
var PasskeyClonedError = class extends BasaltError7 {
|
|
1542
|
-
status = 401;
|
|
1543
|
-
constructor() {
|
|
1544
|
-
super("PASSKEY_CLONED", "Signature counter did not increase \u2014 the authenticator may be cloned.");
|
|
1545
|
-
}
|
|
1546
|
-
};
|
|
1547
|
-
var WebAuthnService = class {
|
|
1548
|
-
config;
|
|
1549
|
-
credentials;
|
|
1550
|
-
challenges;
|
|
1551
|
-
verifier;
|
|
1552
|
-
now;
|
|
1553
|
-
randomChallenge;
|
|
1554
|
-
constructor(options) {
|
|
1555
|
-
this.config = options.config;
|
|
1556
|
-
this.credentials = options.credentials;
|
|
1557
|
-
this.challenges = options.challenges;
|
|
1558
|
-
this.verifier = options.verifier;
|
|
1559
|
-
this.now = options.now ?? (() => Date.now());
|
|
1560
|
-
this.randomChallenge = options.randomChallenge ?? (() => randomBytes8(32).toString("base64url"));
|
|
1561
|
-
}
|
|
1562
|
-
get uv() {
|
|
1563
|
-
return this.config.userVerification ?? "preferred";
|
|
1564
|
-
}
|
|
1565
|
-
get timeout() {
|
|
1566
|
-
return this.config.timeoutMs ?? 6e4;
|
|
1567
|
-
}
|
|
1568
|
-
async issueChallenge(sessionKey) {
|
|
1569
|
-
const challenge = this.randomChallenge();
|
|
1570
|
-
await this.challenges.save(sessionKey, challenge, this.now() + (this.config.challengeTtlMs ?? 3e5));
|
|
1571
|
-
return challenge;
|
|
1572
|
-
}
|
|
1573
|
-
/** Registration options for a known user; stores the challenge under `sessionKey`. */
|
|
1574
|
-
async startRegistration(sessionKey, user) {
|
|
1575
|
-
const challenge = await this.issueChallenge(sessionKey);
|
|
1576
|
-
const existing = await this.credentials.forUser(user.id);
|
|
1577
|
-
return {
|
|
1578
|
-
challenge,
|
|
1579
|
-
rp: { id: this.config.rpId, name: this.config.rpName },
|
|
1580
|
-
user: { id: user.id, name: user.name, displayName: user.displayName ?? user.name },
|
|
1581
|
-
pubKeyCredParams: this.config.pubKeyCredParams ?? DEFAULT_PUB_KEY_PARAMS,
|
|
1582
|
-
timeout: this.timeout,
|
|
1583
|
-
attestation: "none",
|
|
1584
|
-
excludeCredentials: existing.map((c) => ({
|
|
1585
|
-
type: "public-key",
|
|
1586
|
-
id: c.id,
|
|
1587
|
-
...c.transports ? { transports: c.transports } : {}
|
|
1588
|
-
})),
|
|
1589
|
-
authenticatorSelection: { userVerification: this.uv, residentKey: "preferred" }
|
|
1590
|
-
};
|
|
1591
|
-
}
|
|
1592
|
-
/** Verify a registration response and store the new passkey. Throws on failure. */
|
|
1593
|
-
async finishRegistration(sessionKey, userId, response, deviceName) {
|
|
1594
|
-
const expectedChallenge = await this.challenges.take(sessionKey);
|
|
1595
|
-
if (!expectedChallenge) throw new WebAuthnChallengeError();
|
|
1596
|
-
const result = await this.verifier.verifyRegistration({
|
|
1597
|
-
response,
|
|
1598
|
-
expectedChallenge,
|
|
1599
|
-
expectedOrigin: this.config.origin,
|
|
1600
|
-
expectedRpId: this.config.rpId,
|
|
1601
|
-
requireUserVerification: this.uv === "required"
|
|
1602
|
-
});
|
|
1603
|
-
if (!result.verified || !result.credential) throw new WebAuthnVerificationError();
|
|
1604
|
-
const credential = {
|
|
1605
|
-
id: result.credential.id,
|
|
1606
|
-
userId,
|
|
1607
|
-
publicKey: result.credential.publicKey,
|
|
1608
|
-
counter: result.credential.counter,
|
|
1609
|
-
...result.credential.transports ? { transports: result.credential.transports } : {},
|
|
1610
|
-
...deviceName ? { deviceName } : {},
|
|
1611
|
-
createdAt: this.now()
|
|
1612
|
-
};
|
|
1613
|
-
await this.credentials.add(credential);
|
|
1614
|
-
return credential;
|
|
1615
|
-
}
|
|
1616
|
-
/** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
|
|
1617
|
-
async startAuthentication(sessionKey, userId) {
|
|
1618
|
-
const challenge = await this.issueChallenge(sessionKey);
|
|
1619
|
-
const creds = userId ? await this.credentials.forUser(userId) : [];
|
|
1620
|
-
return {
|
|
1621
|
-
challenge,
|
|
1622
|
-
timeout: this.timeout,
|
|
1623
|
-
rpId: this.config.rpId,
|
|
1624
|
-
userVerification: this.uv,
|
|
1625
|
-
allowCredentials: creds.map((c) => ({
|
|
1626
|
-
type: "public-key",
|
|
1627
|
-
id: c.id,
|
|
1628
|
-
...c.transports ? { transports: c.transports } : {}
|
|
1629
|
-
}))
|
|
1630
|
-
};
|
|
1631
|
-
}
|
|
1632
|
-
/**
|
|
1633
|
-
* Verify an authentication response. Looks the credential up by its id, checks
|
|
1634
|
-
* the signature counter increased (clone detection), persists the new counter,
|
|
1635
|
-
* and returns whose passkey authenticated. Throws on any failure.
|
|
1636
|
-
*/
|
|
1637
|
-
async finishAuthentication(sessionKey, response) {
|
|
1638
|
-
const credentialId = response?.id;
|
|
1639
|
-
if (!credentialId) throw new PasskeyNotFoundError();
|
|
1640
|
-
const credential = await this.credentials.get(credentialId);
|
|
1641
|
-
if (!credential) throw new PasskeyNotFoundError();
|
|
1642
|
-
const expectedChallenge = await this.challenges.take(sessionKey);
|
|
1643
|
-
if (!expectedChallenge) throw new WebAuthnChallengeError();
|
|
1644
|
-
const result = await this.verifier.verifyAuthentication({
|
|
1645
|
-
response,
|
|
1646
|
-
expectedChallenge,
|
|
1647
|
-
expectedOrigin: this.config.origin,
|
|
1648
|
-
expectedRpId: this.config.rpId,
|
|
1649
|
-
requireUserVerification: this.uv === "required",
|
|
1650
|
-
credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter }
|
|
1651
|
-
});
|
|
1652
|
-
if (!result.verified) throw new WebAuthnVerificationError();
|
|
1653
|
-
if (credential.counter > 0 && result.newCounter <= credential.counter) {
|
|
1654
|
-
throw new PasskeyClonedError();
|
|
1655
|
-
}
|
|
1656
|
-
await this.credentials.updateCounter(credential.id, result.newCounter, this.now());
|
|
1657
|
-
return { userId: credential.userId, credentialId: credential.id };
|
|
1658
|
-
}
|
|
1659
|
-
/** A user's registered passkeys (for a "manage devices" screen). */
|
|
1660
|
-
async list(userId) {
|
|
1661
|
-
return this.credentials.forUser(userId);
|
|
1662
|
-
}
|
|
1663
|
-
/** Remove a passkey (revoke a device). */
|
|
1664
|
-
async remove(credentialId) {
|
|
1665
|
-
await this.credentials.remove(credentialId);
|
|
1666
|
-
}
|
|
1667
|
-
};
|
|
1668
|
-
|
|
1669
|
-
// src/webauthn-plugin.ts
|
|
1670
|
-
import { createToken as createToken4, definePlugin as definePlugin4 } from "@basaltkit/core";
|
|
1671
|
-
var WEBAUTHN = createToken4("auth:webauthn");
|
|
1672
|
-
function webauthnPlugin(options) {
|
|
1673
|
-
return definePlugin4({
|
|
1674
|
-
name: "basalt:auth-webauthn",
|
|
1675
|
-
register({ container }) {
|
|
1676
|
-
container.singleton(
|
|
1677
|
-
WEBAUTHN,
|
|
1678
|
-
() => new WebAuthnService({
|
|
1679
|
-
config: options.config,
|
|
1680
|
-
verifier: options.verifier,
|
|
1681
|
-
credentials: options.credentials ?? new MemoryPasskeyStore(),
|
|
1682
|
-
challenges: options.challenges ?? new MemoryWebAuthnChallengeStore()
|
|
1683
|
-
})
|
|
1684
|
-
);
|
|
1685
|
-
}
|
|
1686
|
-
});
|
|
1687
|
-
}
|
|
1688
|
-
export {
|
|
1689
|
-
API_KEYS,
|
|
1690
|
-
AUTH,
|
|
1691
|
-
AccountLockedError,
|
|
1692
|
-
ApiKeys,
|
|
1693
|
-
Auth,
|
|
1694
|
-
AuthRequiredError,
|
|
1695
|
-
AuthTokenInvalidError,
|
|
1696
|
-
EmailTakenError,
|
|
1697
|
-
InvalidCredentialsError,
|
|
1698
|
-
LoginThrottle,
|
|
1699
|
-
MemoryApiKeyStore,
|
|
1700
|
-
MemoryAuthTokenStore,
|
|
1701
|
-
MemoryMfaStore,
|
|
1702
|
-
MemoryPasskeyStore,
|
|
1703
|
-
MemoryRefreshTokenStore,
|
|
1704
|
-
MemorySessionStore,
|
|
1705
|
-
MemoryTokenVersionStore,
|
|
1706
|
-
MemoryUserSource,
|
|
1707
|
-
MemoryWebAuthnChallengeStore,
|
|
1708
|
-
MfaInvalidCodeError,
|
|
1709
|
-
MfaNotEnrolledError,
|
|
1710
|
-
MfaRequiredError,
|
|
1711
|
-
OAUTH,
|
|
1712
|
-
OAuth,
|
|
1713
|
-
OAuthExchangeError,
|
|
1714
|
-
OAuthProviderUnknownError,
|
|
1715
|
-
OAuthStateInvalidError,
|
|
1716
|
-
PasskeyClonedError,
|
|
1717
|
-
PasskeyNotFoundError,
|
|
1718
|
-
RefreshInvalidError,
|
|
1719
|
-
RefreshReusedError,
|
|
1720
|
-
ScopeRequiredError,
|
|
1721
|
-
ScryptPasswordHasher,
|
|
1722
|
-
TokenExpiredError,
|
|
1723
|
-
TokenInvalidError,
|
|
1724
|
-
UserUpdateUnsupportedError,
|
|
1725
|
-
WEBAUTHN,
|
|
1726
|
-
WeakJwtSecretError,
|
|
1727
|
-
WebAuthnChallengeError,
|
|
1728
|
-
WebAuthnService,
|
|
1729
|
-
WebAuthnVerificationError,
|
|
1730
|
-
apiKeyRoutes,
|
|
1731
|
-
apiKeysPlugin,
|
|
1732
|
-
authPlugin,
|
|
1733
|
-
authRoutes,
|
|
1734
|
-
base32Decode,
|
|
1735
|
-
base32Encode,
|
|
1736
|
-
discoverOidcProvider,
|
|
1737
|
-
generateTotpSecret,
|
|
1738
|
-
githubProvider,
|
|
1739
|
-
googleProvider,
|
|
1740
|
-
matchTotpStep,
|
|
1741
|
-
mfaRoutes,
|
|
1742
|
-
oauthPlugin,
|
|
1743
|
-
oauthRoutes,
|
|
1744
|
-
oidcProvider,
|
|
1745
|
-
otpauthUri,
|
|
1746
|
-
publicUser,
|
|
1747
|
-
scopesSatisfy,
|
|
1748
|
-
signJwt,
|
|
1749
|
-
totp,
|
|
1750
|
-
verifyJwt,
|
|
1751
|
-
verifyTotp,
|
|
1752
|
-
webauthnPlugin
|
|
1753
|
-
};
|
|
1
|
+
export { ScryptPasswordHasher } from './hashing.js';
|
|
2
|
+
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, } from './jwt.js';
|
|
3
|
+
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, } from './stores.js';
|
|
4
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, } from './auth.js';
|
|
5
|
+
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
|
|
6
|
+
export { authPlugin, AUTH } from './plugin.js';
|
|
7
|
+
export { ApiKeys, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
|
+
export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
|
|
9
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
10
|
+
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
|
11
|
+
export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
|
|
12
|
+
export { LoginThrottle, AccountLockedError } from './throttle.js';
|
|
13
|
+
export { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, WebAuthnChallengeError, WebAuthnVerificationError, PasskeyNotFoundError, PasskeyClonedError, PasskeyExistsError, WebAuthnSubjectMismatchError, } from './webauthn.js';
|
|
14
|
+
export { webauthnPlugin, WEBAUTHN } from './webauthn-plugin.js';
|