@basaltkit/auth 3.1.0 → 4.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/dist/webauthn.js CHANGED
@@ -1,5 +1,13 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { BasaltError } from '@basaltkit/core';
3
+ /** A passkey store without {@link PasskeyStore.compareAndSetCounter} (written against the pre-CAS contract). */
4
+ export class PasskeyStoreOutdatedError extends BasaltError {
5
+ status = 500;
6
+ expose = false;
7
+ constructor() {
8
+ super('PASSKEY_STORE_OUTDATED', 'The PasskeyStore has no compareAndSetCounter(): clone detection cannot be enforced atomically. Implement it (one conditional UPDATE).');
9
+ }
10
+ }
3
11
  export class MemoryPasskeyStore {
4
12
  byId = new Map();
5
13
  async add(credential) {
@@ -12,6 +20,16 @@ export class MemoryPasskeyStore {
12
20
  async forUser(userId) {
13
21
  return [...this.byId.values()].filter((c) => c.userId === userId).map((c) => ({ ...c }));
14
22
  }
23
+ // Synchronous compare-and-set: no await between the read and the write.
24
+ async compareAndSetCounter(credentialId, expected, next, lastUsedAt) {
25
+ const found = this.byId.get(credentialId);
26
+ if (!found || found.counter !== expected)
27
+ return false;
28
+ found.counter = next;
29
+ found.lastUsedAt = lastUsedAt;
30
+ return true;
31
+ }
32
+ /** @deprecated See {@link PasskeyStore.updateCounter}. */
15
33
  async updateCounter(credentialId, counter, lastUsedAt) {
16
34
  const found = this.byId.get(credentialId);
17
35
  if (found) {
@@ -32,13 +50,18 @@ export class MemoryWebAuthnChallengeStore {
32
50
  this.maxEntries = options.maxEntries ?? 10_000;
33
51
  }
34
52
  async save(key, value, expiresAt) {
35
- // Purge expired entries so unconsumed challenges cannot accumulate (DoS),
36
- // and cap total size with FIFO eviction as a hard backstop.
53
+ // Purge expired entries so unconsumed challenges cannot accumulate (DoS).
54
+ // The map is kept in insertion order and every entry is (re)appended on
55
+ // save, so with a constant TTL the oldest entries expire first: stop at the
56
+ // first live one instead of scanning the whole store on every save.
37
57
  const now = this.now();
38
58
  for (const [k, entry] of this.entries) {
39
- if (entry.expiresAt <= now)
40
- this.entries.delete(k);
59
+ if (entry.expiresAt > now)
60
+ break;
61
+ this.entries.delete(k);
41
62
  }
63
+ this.entries.delete(key);
64
+ // Cap total size with FIFO eviction as a hard backstop.
42
65
  while (this.entries.size >= this.maxEntries) {
43
66
  const oldest = this.entries.keys().next().value;
44
67
  if (oldest === undefined)
@@ -106,6 +129,10 @@ export class WebAuthnService {
106
129
  randomChallenge;
107
130
  constructor(options) {
108
131
  this.config = options.config;
132
+ // Fail at wiring time, not at the first login: without the compare-and-set
133
+ // a cloned authenticator could race the genuine one past clone detection.
134
+ if (typeof options.credentials?.compareAndSetCounter !== 'function')
135
+ throw new PasskeyStoreOutdatedError();
109
136
  this.credentials = options.credentials;
110
137
  this.challenges = options.challenges;
111
138
  this.verifier = options.verifier;
@@ -184,9 +211,14 @@ export class WebAuthnService {
184
211
  await this.credentials.add(credential);
185
212
  return credential;
186
213
  }
187
- /** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
214
+ /**
215
+ * Authentication options; omit `userId` for discoverable login. With a
216
+ * `userId` (step-up, re-authentication) the challenge is bound to that user:
217
+ * {@link finishAuthentication} then refuses a passkey that belongs to anyone
218
+ * else, and `allowCredentials` lists only that user's passkeys.
219
+ */
188
220
  async startAuthentication(sessionKey, userId) {
189
- const challenge = await this.issueChallenge('auth', sessionKey);
221
+ const challenge = await this.issueChallenge('auth', sessionKey, userId);
190
222
  const creds = userId ? await this.credentials.forUser(userId) : [];
191
223
  return {
192
224
  challenge,
@@ -202,8 +234,9 @@ export class WebAuthnService {
202
234
  }
203
235
  /**
204
236
  * Verify an authentication response. Looks the credential up by its id, checks
205
- * the signature counter increased (clone detection), persists the new counter,
206
- * and returns whose passkey authenticated. Throws on any failure.
237
+ * the signature counter increased (clone detection), persists the new counter
238
+ * with a compare-and-set (so two concurrent assertions cannot both pass), and
239
+ * returns whose passkey authenticated. Throws on any failure.
207
240
  */
208
241
  async finishAuthentication(sessionKey, response) {
209
242
  const rawId = response?.id;
@@ -219,6 +252,11 @@ export class WebAuthnService {
219
252
  const credential = await this.credentials.get(credentialId);
220
253
  if (!credential)
221
254
  throw new PasskeyNotFoundError();
255
+ // A challenge issued for a specific user (step-up) is only satisfied by
256
+ // that user's passkey — never by another account's valid assertion.
257
+ if (stored.userId !== undefined && stored.userId !== credential.userId) {
258
+ throw new WebAuthnSubjectMismatchError();
259
+ }
222
260
  const result = await this.verifier.verifyAuthentication({
223
261
  response,
224
262
  expectedChallenge: stored.challenge,
@@ -229,20 +267,41 @@ export class WebAuthnService {
229
267
  });
230
268
  if (!result.verified)
231
269
  throw new WebAuthnVerificationError();
270
+ // The counter is a 32-bit unsigned integer. Anything else (NaN, negative,
271
+ // fractional) would slip past the comparison below and, once stored,
272
+ // disable clone detection for the credential for good.
273
+ if (!Number.isSafeInteger(result.newCounter) || result.newCounter < 0)
274
+ throw new WebAuthnVerificationError();
232
275
  // Clone detection: a real authenticator's counter strictly increases. Some
233
276
  // report 0 forever — only enforce when the stored counter is non-zero.
234
277
  if (credential.counter > 0 && result.newCounter <= credential.counter) {
235
278
  throw new PasskeyClonedError();
236
279
  }
237
- await this.credentials.updateCounter(credential.id, result.newCounter, this.now());
280
+ // Atomic: the counter must still be the one this assertion was checked
281
+ // against. A concurrent assertion (a clone used at the same time) that
282
+ // already moved it makes this one fail as a clone.
283
+ if (!(await this.credentials.compareAndSetCounter(credential.id, credential.counter, result.newCounter, this.now()))) {
284
+ throw new PasskeyClonedError();
285
+ }
238
286
  return { userId: credential.userId, credentialId: credential.id };
239
287
  }
240
288
  /** A user's registered passkeys (for a "manage devices" screen). */
241
289
  async list(userId) {
242
290
  return this.credentials.forUser(userId);
243
291
  }
244
- /** Remove a passkey (revoke a device). */
245
- async remove(credentialId) {
292
+ /**
293
+ * Remove one of `userId`'s passkeys (revoke a device). The credential must
294
+ * belong to `userId`: a credential id is not an authorization, so an id that
295
+ * is unknown or owned by another user throws {@link PasskeyNotFoundError}
296
+ * (the same error for both, so the call cannot probe other users' devices).
297
+ */
298
+ async remove(userId, credentialId) {
299
+ if (typeof userId !== 'string' || userId.length === 0 || typeof credentialId !== 'string') {
300
+ throw new PasskeyNotFoundError();
301
+ }
302
+ const credential = await this.credentials.get(credentialId);
303
+ if (!credential || credential.userId !== userId)
304
+ throw new PasskeyNotFoundError();
246
305
  await this.credentials.remove(credentialId);
247
306
  }
248
307
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "3.1.0",
3
+ "version": "4.0.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -18,8 +18,8 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@basaltkit/core": "^1.3.2",
22
- "@basaltkit/http": "^2.2.0"
21
+ "@basaltkit/core": "^1.5.0",
22
+ "@basaltkit/http": "^2.6.0"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"
@@ -29,7 +29,7 @@
29
29
  "typescript": "^7.0.2",
30
30
  "vitest": "^5.0.1",
31
31
  "zod": "^4.6.5",
32
- "@basaltkit/fastify": "^2.2.0",
32
+ "@basaltkit/fastify": "^2.5.0",
33
33
  "@basaltkit/tsconfig": "^0.24.0"
34
34
  },
35
35
  "publishConfig": {