@c9up/warden 0.1.26 → 0.2.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.
Files changed (41) hide show
  1. package/dist/WardenProvider.d.ts +1 -0
  2. package/dist/WardenProvider.d.ts.map +1 -1
  3. package/dist/WardenProvider.js +16 -2
  4. package/dist/WardenProvider.js.map +1 -1
  5. package/dist/mfa/OtpProvider.d.ts +39 -1
  6. package/dist/mfa/OtpProvider.d.ts.map +1 -1
  7. package/dist/mfa/OtpProvider.js +97 -5
  8. package/dist/mfa/OtpProvider.js.map +1 -1
  9. package/dist/mfa/WebauthnProvider.d.ts +60 -10
  10. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  11. package/dist/mfa/WebauthnProvider.js +207 -47
  12. package/dist/mfa/WebauthnProvider.js.map +1 -1
  13. package/dist/native.d.ts.map +1 -1
  14. package/dist/native.js +7 -23
  15. package/dist/native.js.map +1 -1
  16. package/dist/quasar.d.ts +6 -9
  17. package/dist/quasar.d.ts.map +1 -1
  18. package/dist/quasar.js +17 -47
  19. package/dist/quasar.js.map +1 -1
  20. package/dist/services/main.d.ts +10 -0
  21. package/dist/services/main.d.ts.map +1 -1
  22. package/dist/services/main.js +12 -0
  23. package/dist/services/main.js.map +1 -1
  24. package/dist/vendor/nativeBinary.d.ts +43 -0
  25. package/dist/vendor/nativeBinary.d.ts.map +1 -0
  26. package/dist/vendor/nativeBinary.js +99 -0
  27. package/dist/vendor/nativeBinary.js.map +1 -0
  28. package/dist/vendor/quasarConnection.d.ts +35 -0
  29. package/dist/vendor/quasarConnection.d.ts.map +1 -0
  30. package/dist/vendor/quasarConnection.js +62 -0
  31. package/dist/vendor/quasarConnection.js.map +1 -0
  32. package/index.win32-x64-msvc.node +0 -0
  33. package/package.json +1 -1
  34. package/src/WardenProvider.ts +18 -2
  35. package/src/mfa/OtpProvider.ts +133 -6
  36. package/src/mfa/WebauthnProvider.ts +289 -71
  37. package/src/native.ts +7 -25
  38. package/src/quasar.ts +18 -64
  39. package/src/services/main.ts +13 -0
  40. package/src/vendor/nativeBinary.ts +110 -0
  41. package/src/vendor/quasarConnection.ts +129 -0
@@ -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
 
package/src/native.ts CHANGED
@@ -5,21 +5,7 @@
5
5
  * other consumer) throws `E_WARDEN_NAPI_REQUIRED` at use time. Password
6
6
  * hashing is the sole responsibility of `@c9up/sigil` (story 40.1).
7
7
  */
8
- import { createRequire } from "node:module";
9
- import { dirname, join } from "node:path";
10
- import { arch, platform } from "node:process";
11
- import { fileURLToPath } from "node:url";
12
-
13
- const nodeRequire = createRequire(import.meta.url);
14
- const currentDir = dirname(fileURLToPath(import.meta.url));
15
-
16
- const platformMap: Record<string, string> = {
17
- "linux-x64": "linux-x64-gnu",
18
- "linux-arm64": "linux-arm64-gnu",
19
- "darwin-x64": "darwin-x64",
20
- "darwin-arm64": "darwin-arm64",
21
- "win32-x64": "win32-x64-msvc",
22
- };
8
+ import { loadNativeBinary } from "./vendor/nativeBinary.js";
23
9
 
24
10
  /**
25
11
  * The engine's surface, as the Rust declares it.
@@ -30,16 +16,12 @@ const platformMap: Record<string, string> = {
30
16
  */
31
17
  export type NativeWarden = typeof import("./native/generated.js");
32
18
 
33
- let native: NativeWarden | undefined;
34
-
35
- try {
36
- const suffix = platformMap[`${platform}-${arch}`];
37
- if (suffix) {
38
- native = nodeRequire(join(currentDir, `../index.${suffix}.node`));
39
- }
40
- } catch {
41
- // Binary not available — JwtStrategy will throw E_WARDEN_NAPI_REQUIRED at use time.
42
- }
19
+ // Absent is not an error here: `JwtStrategy` throws E_WARDEN_NAPI_REQUIRED at
20
+ // use time, which names what the caller was trying to do. The loader reports
21
+ // what happened and this decides — the platform table itself is shared, since
22
+ // a package that misses a new target fails only on that platform.
23
+ const attempt = loadNativeBinary<NativeWarden>();
24
+ const native = attempt.loaded ? attempt.binary : undefined;
43
25
 
44
26
  /** Whether the Rust NAPI engine loaded. */
45
27
  export function isNativeAvailable(): boolean {
package/src/quasar.ts CHANGED
@@ -1,78 +1,32 @@
1
1
  /**
2
2
  * Resolving a Redis connection by name, from `@c9up/quasar`.
3
3
  *
4
- * Warden does not depend on quasar: it is an optional peer, and this module
5
- * never imports it statically. The specifier is built at runtime so the
6
- * TypeScript build stays free of it too — a hard type import would make echo
7
- * unbuildable for anyone whose blacklist is in memory.
8
- *
9
- * The shape is checked before use rather than asserted, the same way warden
10
- * duck-types its host framework.
4
+ * The loading, the shape check and the messages are the same in every package
5
+ * that offers a Redis-backed option, so they are vendored rather than written
6
+ * again: `src/vendor/quasarConnection.ts`, generated from one source. What is
7
+ * specific to this package — the commands it issues, and what it does with
8
+ * them — stays here, because that is the part a reader needs.
11
9
  */
12
10
 
13
11
  import type { RedisLikeClient } from "./RedisBlacklistDriver.js";
12
+ import { quasarConnection as loadQuasarConnection } from "./vendor/quasarConnection.js";
14
13
 
15
- /** The slice of quasar's manager this needs: a connection, by name. */
16
- interface ConnectionSource {
17
- connection(name?: string): unknown;
18
- }
19
-
20
- function isConnectionSource(value: unknown): value is ConnectionSource {
21
- return (
22
- typeof value === "object" &&
23
- value !== null &&
24
- typeof Reflect.get(value, "connection") === "function"
25
- );
26
- }
27
-
28
- function isRedisLikeClient(value: unknown): value is RedisLikeClient {
29
- if (typeof value !== "object" || value === null) return false;
30
- // The commands this driver actually issues — the whole of `RedisLikeClient`.
31
- // A connection missing one would fail on the first revocation, far from the
32
- // cause. Nothing more: the driver documents itself as needing only `set`
33
- // with an "EX" ttl and `exists`, so demanding sets or key scans here would
34
- // reject a client that works perfectly well.
35
- const required = ["set", "exists"];
36
- return required.every(
37
- (name) => typeof Reflect.get(value, name) === "function",
38
- );
39
- }
14
+ // Only what the driver documents itself as needing: `set` with an "EX" ttl,
15
+ // and `exists`. Demanding key scans here would reject a client that works.
16
+ const REQUIRED = ["set", "exists"] as const;
40
17
 
41
18
  /**
42
- * A resolver for `new RedisBlacklistDriver(quasarConnection())` — quasar is
43
- * loaded on the first revocation check, not at config time.
19
+ * A resolver — quasar is loaded on first use, not at config time.
44
20
  */
45
21
  export function quasarConnection(
46
22
  name?: string,
47
23
  ): () => Promise<RedisLikeClient> {
48
- return async () => {
49
- const specifier = "@c9up/quasar/services/main";
50
- let loaded: unknown;
51
- try {
52
- loaded = await import(/* @vite-ignore */ specifier);
53
- } catch (cause) {
54
- throw new Error(
55
- `Warden: the "${name ?? "default"}" blacklist asks for a quasar connection, but @c9up/quasar is not installed.\n` +
56
- " pnpm add @c9up/quasar",
57
- { cause },
58
- );
59
- }
60
-
61
- const manager = isConnectionSource(loaded)
62
- ? loaded
63
- : Reflect.get(Object(loaded), "default");
64
- if (!isConnectionSource(manager)) {
65
- throw new Error(
66
- "Warden: @c9up/quasar/services/main did not expose a connection() manager",
67
- );
68
- }
69
-
70
- const connection = manager.connection(name);
71
- if (!isRedisLikeClient(connection)) {
72
- throw new Error(
73
- `Warden: quasar connection "${name ?? "default"}" does not carry the commands this blacklist needs`,
74
- );
75
- }
76
- return connection;
77
- };
24
+ return async () =>
25
+ loadQuasarConnection<RedisLikeClient>({
26
+ pkg: "warden",
27
+ name,
28
+ required: REQUIRED,
29
+ what: "the token blacklist",
30
+ raise: (_reason, message, cause) => new Error(message, { cause }),
31
+ });
78
32
  }
@@ -24,6 +24,19 @@ export function getAuth(): AuthManager | undefined {
24
24
  return instance;
25
25
  }
26
26
 
27
+ /**
28
+ * @internal Release the singleton, so a shut-down application does not leave a
29
+ * dead AuthManager reachable through `services/main`.
30
+ *
31
+ * The caller checks ownership first (`getAuth() === mine`). Two applications in
32
+ * one process share this module, and the one shutting down must not clear a
33
+ * manager the other has since installed — for auth, that would leave the
34
+ * survivor authenticating against nothing, or throwing on every guarded route.
35
+ */
36
+ export function clearAuth(): void {
37
+ instance = undefined;
38
+ }
39
+
27
40
  const auth: AuthManager = new Proxy({} as AuthManager, {
28
41
  get(_target, prop) {
29
42
  if (!instance) {