@c9up/warden 0.1.27 → 0.2.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.
@@ -90,13 +90,31 @@ export interface AuthenticationOptionsJSON {
90
90
  * store should use a TTL column / `EXPIRE`; the in-memory default stamps an
91
91
  * `expiresAt` and refuses an expired challenge in `take`.
92
92
  */
93
+ /**
94
+ * What a pending ceremony holds.
95
+ *
96
+ * The identity is stored WITH the challenge, and that is the point. A store
97
+ * that kept only `state -> challenge` let `finishRegistration` be handed any
98
+ * `userId` the caller produced: an integration that read it back from the
99
+ * request, or whose session changed between the two steps, attached a valid
100
+ * passkey to the wrong account — a working credential on someone else's login.
101
+ */
102
+ export interface WebauthnCeremony {
103
+ challenge: string;
104
+ /**
105
+ * The user this ceremony was started for. Absent only for a usernameless
106
+ * authentication, where the credential itself names the owner.
107
+ */
108
+ userId?: string;
109
+ }
110
+
93
111
  export interface WebauthnChallengeStore {
94
- save(state: string, challenge: string): Promise<void>;
112
+ save(state: string, ceremony: WebauthnCeremony): Promise<void>;
95
113
  /**
96
- * Return the challenge for `state` and remove it (single-use). MUST return
97
- * `null` if the stored challenge has passed its TTL.
114
+ * Return the ceremony for `state` and remove it (single-use). MUST return
115
+ * `null` if the stored ceremony has passed its TTL.
98
116
  */
99
- take(state: string): Promise<string | null>;
117
+ take(state: string): Promise<WebauthnCeremony | null>;
100
118
  }
101
119
 
102
120
  /** A registered passkey, persisted between ceremonies. */
@@ -116,28 +134,143 @@ export interface WebauthnCredentialStore {
116
134
  save(passkey: StoredPasskey): Promise<void>;
117
135
  findById(id: string): Promise<StoredPasskey | null>;
118
136
  findByUser(userId: string): Promise<StoredPasskey[]>;
119
- updateCounter(id: string, counter: number): Promise<void>;
137
+ /**
138
+ * Advance the signature counter, and ONLY from the value that was read.
139
+ *
140
+ * The counter is the whole of the cloned-authenticator defence: a clone
141
+ * replays a lower count than the real device has reached, and the mismatch
142
+ * is what betrays it. Read-compare-write across `findById` and a plain
143
+ * `updateCounter` let two concurrent assertions read the same old value,
144
+ * both pass, and then write in either order — so the stored counter could
145
+ * go BACKWARDS and the guard lost the only evidence it has.
146
+ *
147
+ * Returns `false` when the stored value is no longer `expected`, which
148
+ * means another assertion won the race and this one must be refused. A
149
+ * persistent store implements it as a conditional write:
150
+ *
151
+ * SQL UPDATE … SET counter = $next WHERE id = $id AND counter = $expected
152
+ * Redis a WATCH/MULTI, or a Lua compare-and-set
153
+ *
154
+ * It ADVANCES: an implementation must also refuse `next < expected`, so a
155
+ * caller that decided wrongly cannot write the counter backwards and
156
+ * disarm the defence for every assertion after it. In SQL that is a second
157
+ * clause — `AND $next >= counter`.
158
+ */
159
+ advanceCounter(id: string, expected: number, next: number): Promise<boolean>;
160
+ }
161
+
162
+ /**
163
+ * Run a parse of attacker-supplied bytes, turning a throw into "invalid".
164
+ *
165
+ * A truncated attestation, a malformed COSE key or authenticator data that
166
+ * stops mid-structure are INPUT errors — `CBOR: item starts past the end of the
167
+ * buffer` reaching the caller is a 500 for a bad request, and a 500 tells
168
+ * whoever sent it that they reached something which did not expect them.
169
+ *
170
+ * Deliberately narrow: only the decoding and the signature check go through
171
+ * here. A store that cannot be read is infrastructure, and reporting an outage
172
+ * as "not verified" would let a database failure read as a failed login.
173
+ */
174
+ function parsePayload<T>(parse: () => T | null): T | null {
175
+ try {
176
+ return parse();
177
+ } catch {
178
+ return null;
179
+ }
120
180
  }
121
181
 
122
182
  export class MemoryWebauthnChallengeStore implements WebauthnChallengeStore {
123
- #store = new Map<string, { challenge: string; expiresAt: number }>();
183
+ #store = new Map<string, WebauthnCeremony & { expiresAt: number }>();
124
184
  readonly #ttlMs: number;
125
185
 
126
- /** @param ttlMs Server-side challenge lifetime. Default 5 min. */
127
- constructor(ttlMs = 300_000) {
186
+ /**
187
+ * @param ttlMs Server-side challenge lifetime. Default 5 min.
188
+ * @param maxEntries How many pending ceremonies this process will hold.
189
+ * Sweeping removes only EXPIRED entries, so a flood of still-valid ones
190
+ * grew the map without a ceiling. Default 10 000.
191
+ */
192
+ constructor(ttlMs = 300_000, maxEntries = 10_000) {
193
+ // A TTL of Infinity or NaN is not a TTL: the challenge never expires,
194
+ // against a contract that says it MUST be time-bound — and an unconsumed
195
+ // challenge left live indefinitely is exactly the replay window the
196
+ // expiry exists to close.
197
+ if (!Number.isInteger(ttlMs) || ttlMs < 1) {
198
+ throw new WardenError(
199
+ "E_WARDEN_STORE_TTL_INVALID",
200
+ `ttlMs must be a positive integer, got ${String(ttlMs)}.`,
201
+ {
202
+ hint: "Give the ceremony a lifetime in milliseconds — the default is 300000 (5 min).",
203
+ },
204
+ );
205
+ }
128
206
  this.#ttlMs = ttlMs;
207
+ // A ceiling of 0, a negative, NaN or Infinity is not a ceiling: the
208
+ // first two refuse every write and the last two disable the bound this
209
+ // exists to provide, silently. A caller asking for one of those means
210
+ // something, and none of the meanings is what would have happened.
211
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
212
+ throw new WardenError(
213
+ "E_WARDEN_STORE_LIMIT_INVALID",
214
+ `maxEntries must be a positive integer, got ${String(maxEntries)}.`,
215
+ {
216
+ hint: "Pass the number of pending entries this process may hold — the default is 10_000.",
217
+ },
218
+ );
219
+ }
220
+ this.#maxEntries = maxEntries;
129
221
  }
130
222
 
131
- async save(state: string, challenge: string): Promise<void> {
132
- this.#store.set(state, { challenge, expiresAt: Date.now() + this.#ttlMs });
223
+ /**
224
+ * Size at which the next sweep runs, doubling each time.
225
+ *
226
+ * Entries only ever left when their state was reused or taken, so a
227
+ * ceremony nobody finished — a passkey prompt dismissed, which happens all
228
+ * day — stayed for the life of the process. Sweeping on write bounds it
229
+ * without a timer, which would hold the event loop open and need a disposal
230
+ * contract this store does not have.
231
+ */
232
+ #sweepAt = 64;
233
+ readonly #maxEntries: number;
234
+
235
+ async save(state: string, ceremony: WebauthnCeremony): Promise<void> {
236
+ if (this.#store.size >= this.#maxEntries && !this.#store.has(state)) {
237
+ this.#sweep();
238
+ }
239
+ if (this.#store.size >= this.#maxEntries && !this.#store.has(state)) {
240
+ // Refused rather than evicted: making room by dropping someone
241
+ // else's pending ceremony is how a flood locks a real user out.
242
+ throw new WardenError(
243
+ "E_WARDEN_WEBAUTHN_STORE_FULL",
244
+ `The in-memory WebAuthn challenge store is full (${this.#maxEntries} pending ceremonies).`,
245
+ {
246
+ hint: "Rate-limit the endpoint that starts a ceremony, or move to a persistent store with its own TTL.",
247
+ },
248
+ );
249
+ }
250
+ this.#store.set(state, {
251
+ ...ceremony,
252
+ expiresAt: Date.now() + this.#ttlMs,
253
+ });
254
+ if (this.#store.size > this.#sweepAt) this.#sweep();
133
255
  }
134
- async take(state: string): Promise<string | null> {
256
+
257
+ /** Drop everything already expired. */
258
+ #sweep(): void {
259
+ const now = Date.now();
260
+ for (const [state, entry] of this.#store) {
261
+ if (entry.expiresAt < now) this.#store.delete(state);
262
+ }
263
+ this.#sweepAt = Math.max(64, this.#store.size * 2);
264
+ }
265
+ async take(state: string): Promise<WebauthnCeremony | null> {
135
266
  const entry = this.#store.get(state);
136
267
  this.#store.delete(state); // single-use regardless of freshness
137
- if (!entry || entry.expiresAt < Date.now()) {
268
+ // `<=`, not `<`: an entry whose deadline is exactly now has expired.
269
+ // Strictly-less left it valid for the remainder of that millisecond.
270
+ if (!entry || entry.expiresAt <= Date.now()) {
138
271
  return null;
139
272
  }
140
- return entry.challenge;
273
+ return { challenge: entry.challenge, userId: entry.userId };
141
274
  }
142
275
  }
143
276
 
@@ -152,11 +285,26 @@ export class MemoryWebauthnCredentialStore implements WebauthnCredentialStore {
152
285
  async findByUser(userId: string): Promise<StoredPasskey[]> {
153
286
  return [...this.#store.values()].filter((p) => p.userId === userId);
154
287
  }
155
- async updateCounter(id: string, counter: number): Promise<void> {
288
+ /**
289
+ * Atomic here for free: a synchronous read, compare and write with no
290
+ * `await` between them cannot be interleaved on a single-threaded runtime.
291
+ * Written as one block on purpose — an `await` inside would silently
292
+ * reintroduce the race this exists to close.
293
+ */
294
+ async advanceCounter(
295
+ id: string,
296
+ expected: number,
297
+ next: number,
298
+ ): Promise<boolean> {
156
299
  const p = this.#store.get(id);
157
- if (p) {
158
- this.#store.set(id, { ...p, counter });
159
- }
300
+ if (!p || p.counter !== expected) return false;
301
+ // Defence in depth: this method ADVANCES. A caller that has already
302
+ // decided the assertion is good can still have decided it wrongly, and
303
+ // a store that writes whatever it is handed turns one bad decision into
304
+ // a permanently disarmed counter.
305
+ if (next < expected) return false;
306
+ this.#store.set(id, { ...p, counter: next });
307
+ return true;
160
308
  }
161
309
  }
162
310
 
@@ -266,7 +414,9 @@ export class WebauthnProvider {
266
414
  },
267
415
  };
268
416
  const state = randomBytes(16).toString("hex");
269
- await this.#challenges.save(state, challenge);
417
+ // The identity travels WITH the challenge. Stored apart, `finish` had to
418
+ // trust whatever `userId` the caller handed back.
419
+ await this.#challenges.save(state, { challenge, userId: user.id });
270
420
  return { options, state };
271
421
  }
272
422
 
@@ -279,47 +429,74 @@ export class WebauthnProvider {
279
429
  userId: string,
280
430
  response: RegistrationResponseJSON,
281
431
  ): Promise<{ verified: boolean }> {
282
- const expectedChallenge = await this.#challenges.take(state);
283
- if (!expectedChallenge) {
432
+ const ceremony = await this.#challenges.take(state);
433
+ if (!ceremony) {
434
+ return { verified: false };
435
+ }
436
+ // The passkey is registered for the user who STARTED the ceremony, not
437
+ // for whoever the caller names now. A mismatch is an integration reading
438
+ // the id back from the request, or a session that changed between the
439
+ // two steps; either way it would attach a working credential to the
440
+ // wrong account, so it is refused rather than resolved in someone's
441
+ // favour.
442
+ if (ceremony.userId !== undefined && ceremony.userId !== userId) {
284
443
  return { verified: false };
285
444
  }
286
445
  if (
287
446
  !this.#validClientData(
288
447
  response.response.clientDataJSON,
289
448
  "webauthn.create",
290
- expectedChallenge,
449
+ ceremony.challenge,
291
450
  )
292
451
  ) {
293
452
  return { verified: false };
294
453
  }
295
454
 
296
- const attestation = decodeCbor(
297
- base64urlToBuffer(response.response.attestationObject),
298
- ).value;
299
- if (!(attestation instanceof Map)) {
300
- return { verified: false };
301
- }
302
- const authDataRaw = attestation.get("authData");
303
- if (!Buffer.isBuffer(authDataRaw)) {
304
- return { verified: false };
305
- }
306
- const authData = parseAuthenticatorData(authDataRaw);
307
- if (
308
- !this.#validAuthenticator(authData) ||
309
- !authData.cosePublicKey ||
310
- !authData.cosePublicKeyBytes ||
311
- !authData.credentialId
312
- ) {
455
+ // The payload is attacker-supplied: a truncated attestation, a malformed
456
+ // COSE key or authenticator data that stops mid-structure are INPUT
457
+ // errors, and this method promises `{ verified: false }` for an invalid
458
+ // response. Letting the decoder's exception out turned a bad request
459
+ // into a 500 — and a 500 tells whoever sent it that they reached
460
+ // something that did not expect them.
461
+ //
462
+ // Only the parsing is wrapped: a store that cannot be read is
463
+ // infrastructure, and swallowing that would report "not verified" for an
464
+ // outage.
465
+ const parsed = parsePayload(() => {
466
+ const attestation = decodeCbor(
467
+ base64urlToBuffer(response.response.attestationObject),
468
+ ).value;
469
+ if (!(attestation instanceof Map)) return null;
470
+ const authDataRaw = attestation.get("authData");
471
+ if (!Buffer.isBuffer(authDataRaw)) return null;
472
+ const authData = parseAuthenticatorData(authDataRaw);
473
+ if (
474
+ !this.#validAuthenticator(authData) ||
475
+ !authData.cosePublicKey ||
476
+ !authData.cosePublicKeyBytes ||
477
+ !authData.credentialId
478
+ ) {
479
+ return null;
480
+ }
481
+ // The narrowing is carried OUT of the closure: the guard above proved
482
+ // these three are present, and the caller cannot see that through an
483
+ // object literal typed from `authData` alone.
484
+ return {
485
+ credentialId: authData.credentialId,
486
+ publicKeyBytes: authData.cosePublicKeyBytes,
487
+ signCount: authData.signCount,
488
+ alg: coseToKeyObject(authData.cosePublicKey).alg,
489
+ };
490
+ });
491
+ if (parsed === null) {
313
492
  return { verified: false };
314
493
  }
315
-
316
- const { alg } = coseToKeyObject(authData.cosePublicKey);
317
494
  await this.#credentials.save({
318
- id: bufferToBase64url(authData.credentialId),
495
+ id: bufferToBase64url(parsed.credentialId),
319
496
  userId,
320
- publicKey: bufferToBase64url(authData.cosePublicKeyBytes),
321
- alg,
322
- counter: authData.signCount,
497
+ publicKey: bufferToBase64url(parsed.publicKeyBytes),
498
+ alg: parsed.alg,
499
+ counter: parsed.signCount,
323
500
  transports: response.response.transports,
324
501
  });
325
502
  return { verified: true };
@@ -348,7 +525,10 @@ export class WebauthnProvider {
348
525
  : undefined,
349
526
  };
350
527
  const state = randomBytes(16).toString("hex");
351
- await this.#challenges.save(state, challenge);
528
+ // `userId` is optional here: a usernameless login is named by the
529
+ // credential itself. When it IS given, storing it lets `finish` refuse an
530
+ // assertion from someone else's passkey.
531
+ await this.#challenges.save(state, { challenge, userId });
352
532
  return { options, state };
353
533
  }
354
534
 
@@ -361,15 +541,15 @@ export class WebauthnProvider {
361
541
  state: string,
362
542
  response: AuthenticationResponseJSON,
363
543
  ): Promise<{ verified: boolean; userId?: string }> {
364
- const expectedChallenge = await this.#challenges.take(state);
365
- if (!expectedChallenge) {
544
+ const ceremony = await this.#challenges.take(state);
545
+ if (!ceremony) {
366
546
  return { verified: false };
367
547
  }
368
548
  if (
369
549
  !this.#validClientData(
370
550
  response.response.clientDataJSON,
371
551
  "webauthn.get",
372
- expectedChallenge,
552
+ ceremony.challenge,
373
553
  )
374
554
  ) {
375
555
  return { verified: false };
@@ -379,37 +559,75 @@ export class WebauthnProvider {
379
559
  if (!stored) {
380
560
  return { verified: false };
381
561
  }
382
-
383
- const authDataRaw = base64urlToBuffer(response.response.authenticatorData);
384
- const authData = parseAuthenticatorData(authDataRaw);
385
- if (!this.#validAuthenticator(authData)) {
562
+ // When the ceremony named a user, the asserted credential has to be
563
+ // theirs. `allowCredentials` is a HINT the browser may ignore and an
564
+ // attacker simply will: without this, a login started for one account
565
+ // could be completed with a passkey belonging to another.
566
+ if (ceremony.userId !== undefined && stored.userId !== ceremony.userId) {
386
567
  return { verified: false };
387
568
  }
388
569
 
389
- // Signed payload = authenticatorData ‖ SHA-256(clientDataJSON).
390
- const clientHash = sha256(
391
- base64urlToBuffer(response.response.clientDataJSON),
392
- );
393
- const signedData = Buffer.concat([authDataRaw, clientHash]);
394
- const { key } = coseToKeyObject(
395
- expectCoseMap(base64urlToBuffer(stored.publicKey)),
396
- );
397
- const ok = verifyWebauthnSignature(
398
- stored.alg,
399
- key,
400
- signedData,
401
- base64urlToBuffer(response.response.signature),
402
- );
403
- if (!ok) {
570
+ // Same reasoning as registration: the payload is attacker-supplied, and
571
+ // this method promises `{ verified: false }` for an invalid one. Only
572
+ // the parsing and the signature check are wrapped — a store failure is
573
+ // infrastructure and must not be reported as "not verified".
574
+ const checked = parsePayload(() => {
575
+ const authDataRaw = base64urlToBuffer(
576
+ response.response.authenticatorData,
577
+ );
578
+ const authData = parseAuthenticatorData(authDataRaw);
579
+ if (!this.#validAuthenticator(authData)) return null;
580
+
581
+ // Signed payload = authenticatorData ‖ SHA-256(clientDataJSON).
582
+ const clientHash = sha256(
583
+ base64urlToBuffer(response.response.clientDataJSON),
584
+ );
585
+ const signedData = Buffer.concat([authDataRaw, clientHash]);
586
+ const { key } = coseToKeyObject(
587
+ expectCoseMap(base64urlToBuffer(stored.publicKey)),
588
+ );
589
+ const ok = verifyWebauthnSignature(
590
+ stored.alg,
591
+ key,
592
+ signedData,
593
+ base64urlToBuffer(response.response.signature),
594
+ );
595
+ return ok ? { authData } : null;
596
+ });
597
+ if (checked === null) {
404
598
  return { verified: false };
405
599
  }
600
+ const { authData } = checked;
406
601
 
407
- // Replay guard: a non-zero counter must strictly advance. Authenticators
408
- // that always report 0 (e.g. many platform passkeys) are exempt.
409
- if (authData.signCount !== 0 && authData.signCount <= stored.counter) {
602
+ // Replay guard, as the spec words it: run the comparison when EITHER
603
+ // counter is nonzero, then refuse anything that does not strictly
604
+ // advance. Authenticators that always report 0 — many platform passkeys
605
+ // — stay exempt, because that is the case where both sides are zero.
606
+ //
607
+ // The guard used to test the incoming counter alone, so a credential
608
+ // sitting at 42 accepted an assertion reporting 0 and then WROTE 0
609
+ // back. That is worse than admitting one assertion: it erases the
610
+ // stored counter, and with it the clone detection for every assertion
611
+ // after it.
612
+ if (
613
+ (authData.signCount !== 0 || stored.counter !== 0) &&
614
+ authData.signCount <= stored.counter
615
+ ) {
616
+ return { verified: false };
617
+ }
618
+ // The write is what decides. Comparing here and writing unconditionally
619
+ // let a second assertion that read the same old counter also pass, and
620
+ // whichever wrote last set the stored value — possibly backwards.
621
+ // Refusing when the counter has moved under us costs a legitimate user
622
+ // one retry and costs a clone the whole attack.
623
+ const advanced = await this.#credentials.advanceCounter(
624
+ stored.id,
625
+ stored.counter,
626
+ authData.signCount,
627
+ );
628
+ if (!advanced) {
410
629
  return { verified: false };
411
630
  }
412
- await this.#credentials.updateCounter(stored.id, authData.signCount);
413
631
  return { verified: true, userId: stored.userId };
414
632
  }
415
633
 
@@ -10,6 +10,7 @@ import type {
10
10
  AuthStrategy,
11
11
  UserPayload,
12
12
  } from "../AuthManager.js";
13
+ import { resolveExpiresInSeconds, type TokenDuration } from "../duration.js";
13
14
  import { nativeWarden } from "../native.js";
14
15
  import type { TokenBlacklist } from "../TokenBlacklist.js";
15
16
 
@@ -71,6 +72,13 @@ export interface JwtStrategyConfig {
71
72
  * correctness but ordering by recency keeps the common path fast.
72
73
  */
73
74
  previousSecrets?: readonly string[];
75
+ /**
76
+ * Token lifetime — seconds as a number, or a duration string (`'1h'`,
77
+ * `'7 days'`), which is the spelling upstream uses and the one a config
78
+ * copied from an Adonis app carries.
79
+ */
80
+ expiresIn?: TokenDuration;
81
+ /** The seconds-only spelling this package shipped first. `expiresIn` wins. */
74
82
  expiresInSeconds?: number;
75
83
  /**
76
84
  * Resolve the user for a verified token. Receives the token `sub` AND the
@@ -121,7 +129,11 @@ export class JwtStrategy implements AuthStrategy {
121
129
  }
122
130
  this.#secret = config.secret;
123
131
  this.#verifySecrets = [config.secret, ...(config.previousSecrets ?? [])];
124
- this.#expiresIn = config.expiresInSeconds ?? 3600;
132
+ this.#expiresIn = resolveExpiresInSeconds(
133
+ config.expiresIn,
134
+ config.expiresInSeconds,
135
+ 3600,
136
+ );
125
137
  this.#findUser = config.findUser;
126
138
  this.#verifyCredentials = config.verifyCredentials;
127
139
  this.#blacklist = config.blacklist;