@c9up/warden 0.1.25 → 0.1.27

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 (78) hide show
  1. package/dist/RedisBlacklistDriver.d.ts.map +1 -1
  2. package/dist/RedisBlacklistDriver.js +12 -2
  3. package/dist/RedisBlacklistDriver.js.map +1 -1
  4. package/dist/WardenProvider.d.ts +2 -0
  5. package/dist/WardenProvider.d.ts.map +1 -1
  6. package/dist/WardenProvider.js +29 -3
  7. package/dist/WardenProvider.js.map +1 -1
  8. package/dist/augmentations.d.ts +27 -1
  9. package/dist/augmentations.d.ts.map +1 -1
  10. package/dist/augmentations.js +9 -1
  11. package/dist/augmentations.js.map +1 -1
  12. package/dist/bouncer/Bouncer.d.ts.map +1 -1
  13. package/dist/bouncer/Bouncer.js +2 -1
  14. package/dist/bouncer/Bouncer.js.map +1 -1
  15. package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
  16. package/dist/bouncer/PolicyAuthorizer.js +2 -1
  17. package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
  18. package/dist/bouncer/emitSafely.d.ts +18 -0
  19. package/dist/bouncer/emitSafely.d.ts.map +1 -0
  20. package/dist/bouncer/emitSafely.js +22 -0
  21. package/dist/bouncer/emitSafely.js.map +1 -0
  22. package/dist/bouncer/types.d.ts +10 -1
  23. package/dist/bouncer/types.d.ts.map +1 -1
  24. package/dist/mfa/BackupCodesProvider.js +2 -2
  25. package/dist/mfa/BackupCodesProvider.js.map +1 -1
  26. package/dist/mfa/MfaManager.js +1 -1
  27. package/dist/mfa/MfaManager.js.map +1 -1
  28. package/dist/mfa/TotpProvider.js +6 -5
  29. package/dist/mfa/TotpProvider.js.map +1 -1
  30. package/dist/mfa/base32.js +2 -2
  31. package/dist/mfa/base32.js.map +1 -1
  32. package/dist/mfa/webauthn-codec.d.ts.map +1 -1
  33. package/dist/mfa/webauthn-codec.js +11 -4
  34. package/dist/mfa/webauthn-codec.js.map +1 -1
  35. package/dist/native.d.ts.map +1 -1
  36. package/dist/native.js +7 -23
  37. package/dist/native.js.map +1 -1
  38. package/dist/quasar.d.ts +6 -9
  39. package/dist/quasar.d.ts.map +1 -1
  40. package/dist/quasar.js +17 -47
  41. package/dist/quasar.js.map +1 -1
  42. package/dist/services/main.d.ts +10 -0
  43. package/dist/services/main.d.ts.map +1 -1
  44. package/dist/services/main.js +12 -0
  45. package/dist/services/main.js.map +1 -1
  46. package/dist/vendor/nativeBinary.d.ts +43 -0
  47. package/dist/vendor/nativeBinary.d.ts.map +1 -0
  48. package/dist/vendor/nativeBinary.js +99 -0
  49. package/dist/vendor/nativeBinary.js.map +1 -0
  50. package/dist/vendor/quasarConnection.d.ts +35 -0
  51. package/dist/vendor/quasarConnection.d.ts.map +1 -0
  52. package/dist/vendor/quasarConnection.js +62 -0
  53. package/dist/vendor/quasarConnection.js.map +1 -0
  54. package/index.darwin-arm64.node +0 -0
  55. package/index.darwin-x64.node +0 -0
  56. package/index.linux-arm64-gnu.node +0 -0
  57. package/index.linux-x64-gnu.node +0 -0
  58. package/index.win32-x64-msvc.node +0 -0
  59. package/package.json +3 -2
  60. package/scripts/build-napi-types.mjs +4 -3
  61. package/scripts/generate-napi-types.mjs +9 -6
  62. package/src/RedisBlacklistDriver.ts +15 -5
  63. package/src/WardenProvider.ts +31 -5
  64. package/src/augmentations.ts +28 -1
  65. package/src/bouncer/Bouncer.ts +2 -1
  66. package/src/bouncer/PolicyAuthorizer.ts +2 -1
  67. package/src/bouncer/emitSafely.ts +28 -0
  68. package/src/bouncer/types.ts +10 -1
  69. package/src/mfa/BackupCodesProvider.ts +2 -2
  70. package/src/mfa/MfaManager.ts +1 -1
  71. package/src/mfa/TotpProvider.ts +6 -6
  72. package/src/mfa/base32.ts +2 -2
  73. package/src/mfa/webauthn-codec.ts +11 -4
  74. package/src/native.ts +7 -25
  75. package/src/quasar.ts +18 -64
  76. package/src/services/main.ts +13 -0
  77. package/src/vendor/nativeBinary.ts +110 -0
  78. package/src/vendor/quasarConnection.ts +129 -0
@@ -130,12 +130,15 @@ for (const fn of fns) {
130
130
  // napi-derive emits the whole declaration for a function, unlike a struct
131
131
  // where `def` holds only the members.
132
132
  const declaration = fn.def.trim()
133
- out.push(
134
- declaration.startsWith('export declare function')
135
- ? `${declaration};`
136
- : `export declare function ${fn.name}${declaration};`,
137
- '',
138
- )
133
+ // napi-derive 3 emits a bare `function name(...)` where 2 emitted the
134
+ // signature after the name; concatenating onto the former produced
135
+ // `function xfunction x(...)`.
136
+ const rendered = declaration.startsWith('export declare function')
137
+ ? declaration
138
+ : declaration.startsWith('function ')
139
+ ? `export declare ${declaration}`
140
+ : `export declare function ${fn.name}${declaration}`
141
+ out.push(`${rendered};`, '')
139
142
  }
140
143
 
141
144
  const stale = Object.keys(CALLBACK_REFINEMENTS).filter((k) => !used.has(k))
@@ -58,11 +58,21 @@ export class RedisBlacklistDriver implements BlacklistDriver {
58
58
  }
59
59
  if (!this.#pending) {
60
60
  const resolver = this.#source;
61
- this.#pending = Promise.resolve(resolver()).then((client) => {
62
- this.#resolved = client;
63
- this.#pending = undefined;
64
- return client;
65
- });
61
+ // `finally`, not the success path: clearing it only on success left a
62
+ // REJECTED promise in the slot, and every later call returned that
63
+ // same rejection. One refused connection at boot — Redis still
64
+ // starting, a network blip — and the blacklist never reconnected for
65
+ // the life of the process, which for a revocation store means every
66
+ // later check failing open or hard. Bay and echo already clear it
67
+ // this way.
68
+ this.#pending = Promise.resolve(resolver())
69
+ .then((client) => {
70
+ this.#resolved = client;
71
+ return client;
72
+ })
73
+ .finally(() => {
74
+ this.#pending = undefined;
75
+ });
66
76
  }
67
77
  return this.#pending;
68
78
  }
@@ -1,3 +1,4 @@
1
+ import "./augmentations.js";
1
2
  import { AuthManager, type AuthStrategy } from "./AuthManager.js";
2
3
  import type { WardenConfig } from "./config.js";
3
4
  import { WardenError } from "./errors.js";
@@ -5,7 +6,7 @@ import { MfaManager } from "./mfa/MfaManager.js";
5
6
  import type { BouncerRegistry } from "./middleware.js";
6
7
  import { MemoryRightsStore } from "./rights/MemoryRightsStore.js";
7
8
  import { RightsResolver } from "./rights/RightsResolver.js";
8
- import { setAuth } from "./services/main.js";
9
+ import { clearAuth, getAuth, setAuth } from "./services/main.js";
9
10
  import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
10
11
  import { JwtStrategy } from "./strategies/JwtStrategy.js";
11
12
  import { SessionStrategy } from "./strategies/SessionStrategy.js";
@@ -25,6 +26,9 @@ export interface WardenAppContext {
25
26
  }
26
27
 
27
28
  export default class WardenProvider {
29
+ /** The manager this provider installed, so shutdown only clears its own. */
30
+ #auth: AuthManager | undefined;
31
+
28
32
  constructor(protected app: WardenAppContext) {}
29
33
 
30
34
  register() {
@@ -135,9 +139,17 @@ export default class WardenProvider {
135
139
  // (events → "bus", rosetta → "i18n"). Without this, Station's
136
140
  // `container.resolve("auth")` threw and its admin auth gate
137
141
  // silently fell back to open-mode.
138
- this.app.container.singleton("auth", () =>
139
- this.app.container.resolve(AuthManager),
140
- );
142
+ // Namespaced by the package that owns it, the way upstream namespaces
143
+ // `lucid.db`, `auth.manager` and `drive.manager` by theirs. The bare
144
+ // token stays bound beside it: it is what every existing
145
+ // `container.make(...)` asks for, and a token is not worth breaking an
146
+ // application over.
147
+ // The host container is duck-typed here, so the factory answers
148
+ // `unknown`; what `container.make('warden.auth')` hands back is typed by
149
+ // the augmentation, not by this call.
150
+ const auth = (): unknown => this.app.container.resolve(AuthManager);
151
+ this.app.container.singleton("warden.auth", auth);
152
+ this.app.container.singleton("auth", auth);
141
153
 
142
154
  // MFA (optional): the app builds an MfaManager with its persistent stores
143
155
  // + providers and passes it via config.mfa. Registered by class and under
@@ -146,16 +158,30 @@ export default class WardenProvider {
146
158
  const mfa = config.mfa?.manager;
147
159
  if (mfa) {
148
160
  this.app.container.singleton(MfaManager, () => mfa);
161
+ this.app.container.singleton("warden.mfa", () => mfa);
149
162
  this.app.container.singleton("mfa", () => mfa);
150
163
  }
151
164
  }
152
165
 
153
166
  async boot() {
154
167
  const manager = await this.app.container.resolve(AuthManager);
155
- if (manager instanceof AuthManager) setAuth(manager);
168
+ if (manager instanceof AuthManager) {
169
+ this.#auth = manager;
170
+ setAuth(manager);
171
+ }
156
172
  await this.#registerTemplateTags();
157
173
  }
158
174
 
175
+ async shutdown() {
176
+ // Release the module-level singleton, but only while it is still ours.
177
+ // A stopped application left a dead AuthManager reachable through
178
+ // `import auth from '@c9up/warden/services/main'`; and with two
179
+ // applications in one process, clearing unconditionally would take the
180
+ // survivor's auth down with it.
181
+ if (this.#auth !== undefined && getAuth() === this.#auth) clearAuth();
182
+ this.#auth = undefined;
183
+ }
184
+
159
185
  /**
160
186
  * Publish `@can` / `@cannot` to the template engine, as AdonisJS's bouncer
161
187
  * does. A migrated template keeps `@can('PostPolicy.edit', post) … @endcan`
@@ -1,5 +1,13 @@
1
1
  /**
2
- * Teach ream's `Authenticators` interface what `ctx.auth.use(name)` returns.
2
+ * Teach ream's `Authenticators` and `ContainerBindings` interfaces what warden
3
+ * puts in them.
4
+ *
5
+ * `Authenticators` says what `ctx.auth.use(name)` returns; `ContainerBindings`
6
+ * says what `container.make('auth')` returns. Only the first was filled in —
7
+ * ream's own comment on `ContainerBindings` names `auth` (warden) as reaching
8
+ * it by augmentation from here, and nothing did, so resolving by the string
9
+ * token answered `unknown` and every call site had to assert a type it could
10
+ * not prove.
3
11
  *
4
12
  * ream declares that interface empty on purpose — it owns no auth package, so
5
13
  * it cannot know an application's guards, and `use()` falls back to `unknown`
@@ -17,9 +25,28 @@
17
25
  // Referenced so the augmentation below resolves the module it augments.
18
26
  import type {} from "@c9up/ream/types";
19
27
  import type { GuardAccessor } from "./Authenticator.js";
28
+ import type { AuthManager } from "./AuthManager.js";
29
+ import type { MfaManager } from "./mfa/MfaManager.js";
20
30
 
21
31
  declare module "@c9up/ream/types" {
22
32
  interface Authenticators {
23
33
  [guardName: string]: GuardAccessor;
24
34
  }
35
+
36
+ interface ContainerBindings {
37
+ /** The auth manager, bound by `WardenProvider`. */
38
+ "warden.auth": AuthManager;
39
+ /**
40
+ * The same binding under the name it had before the token carried its
41
+ * package. Kept bound so an existing `container.make(...)` resolves.
42
+ */
43
+ auth: AuthManager;
44
+ /** The MFA manager — bound only when `config.mfa.manager` is set. */
45
+ "warden.mfa": MfaManager;
46
+ /**
47
+ * The same binding under the name it had before the token carried its
48
+ * package. Kept bound so an existing `container.make(...)` resolves.
49
+ */
50
+ mfa: MfaManager;
51
+ }
25
52
  }
@@ -18,6 +18,7 @@ import type { EffectivePermissions, Scope } from "../rights/types.js";
18
18
  import { AbilitiesBuilder } from "./AbilitiesBuilder.js";
19
19
  import { AuthorizationResponse } from "./AuthorizationResponse.js";
20
20
  import type { BasePolicy } from "./BasePolicy.js";
21
+ import { emitSafely } from "./emitSafely.js";
21
22
  import {
22
23
  defaultResponseBuilder,
23
24
  evaluate,
@@ -271,7 +272,7 @@ export class Bouncer {
271
272
  response: AuthorizationResponse,
272
273
  parameters: unknown[],
273
274
  ): void {
274
- this.#emitter?.emit("authorization:finished", {
275
+ emitSafely(this.#emitter, "authorization:finished", {
275
276
  user: this.#getUser(),
276
277
  action,
277
278
  // What the check was ABOUT. AdonisJS carries it, and without it an
@@ -12,6 +12,7 @@ import type { EffectivePermissions, Scope } from "../rights/types.js";
12
12
  import type { AuthorizationResponse } from "./AuthorizationResponse.js";
13
13
  import { BasePolicy } from "./BasePolicy.js";
14
14
  import { getActionMetadata } from "./decorators.js";
15
+ import { emitSafely } from "./emitSafely.js";
15
16
  import {
16
17
  type Action,
17
18
  evaluate,
@@ -112,7 +113,7 @@ export class PolicyAuthorizer {
112
113
  after: policy.after?.bind(policy),
113
114
  responseBuilder: this.#responseBuilder,
114
115
  });
115
- this.#emitter?.emit("authorization:finished", {
116
+ emitSafely(this.#emitter, "authorization:finished", {
116
117
  user: this.#user,
117
118
  action,
118
119
  // Same payload as an ability check: which resource the decision was
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Emit an authorization event without letting the listener come back.
3
+ *
4
+ * `@adonisjs/events` declares `emit(): Promise<void>` and rethrows when a
5
+ * listener fails and the application registered no error handler. Nobody
6
+ * awaits an authorization event — it is an audit trail, not a participant in
7
+ * the decision — so that rejection had nowhere to go and ended the process
8
+ * over a logger.
9
+ *
10
+ * The emitter is invoked INSIDE the async function rather than before it:
11
+ * `Promise.resolve(emit(...))` runs `emit` first, so a synchronous throw would
12
+ * still escape. The call itself stays synchronous, because an async body runs
13
+ * to its first `await` — the deferral is only the failure handling.
14
+ */
15
+ export function emitSafely(
16
+ emitter: { emit: (event: string, payload: unknown) => unknown } | undefined,
17
+ event: string,
18
+ payload: unknown,
19
+ ): void {
20
+ if (emitter === undefined) return;
21
+ void (async () => emitter.emit(event, payload))().catch((error: unknown) => {
22
+ process.stderr.write(
23
+ `[warden] '${event}' listener failed: ${
24
+ error instanceof Error ? error.message : String(error)
25
+ }\n`,
26
+ );
27
+ });
28
+ }
@@ -29,7 +29,16 @@ export interface PolicyContainerResolver {
29
29
  * them to say WHICH resource was refused. No-op when absent.
30
30
  */
31
31
  export interface BouncerEmitter {
32
- emit(event: string, payload: unknown): void;
32
+ /**
33
+ * `unknown`, not `void`. `@adonisjs/events` declares
34
+ * `emit(): Promise<void>` and rethrows when a listener fails and no error
35
+ * handler is registered — and a `void` return type ACCEPTS a
36
+ * promise-returning function, so a call site reads as if there were
37
+ * nothing to handle. That is how an authorization listener's rejection
38
+ * went unnoticed. Duck-typed, so it stays wider than Adonis's own class:
39
+ * a Node EventEmitter returns boolean.
40
+ */
41
+ emit(event: string, payload: unknown): unknown;
33
42
  }
34
43
 
35
44
  /**
@@ -79,8 +79,8 @@ export class BackupCodesProvider {
79
79
  const candidate = normalize(code);
80
80
  let matchedIndex = -1;
81
81
  // Scan every entry (no early exit) so timing doesn't leak position.
82
- for (let i = 0; i < hashes.length; i++) {
83
- if (matchesStored(hashes[i], candidate)) {
82
+ for (const [i, stored] of hashes.entries()) {
83
+ if (matchesStored(stored, candidate)) {
84
84
  matchedIndex = i;
85
85
  }
86
86
  }
@@ -133,7 +133,7 @@ export class MfaManager {
133
133
  async confirmTotp(factorId: string, code: string): Promise<boolean> {
134
134
  const totp = this.#requireTotp();
135
135
  const factor = await this.#store.findById(factorId);
136
- if (!factor || factor.kind !== "totp" || !factor.secret) {
136
+ if (factor?.kind !== "totp" || !factor.secret) {
137
137
  return false;
138
138
  }
139
139
  if (!(await totp.verify(factor.secret, code))) {
@@ -201,12 +201,12 @@ export class TotpProvider {
201
201
  const hmac = createHmac(this.#cfg.algorithm.toLowerCase(), Buffer.from(key))
202
202
  .update(buf)
203
203
  .digest();
204
- const off = hmac[hmac.length - 1] & 0xf;
205
- const bin =
206
- ((hmac[off] & 0x7f) << 24) |
207
- ((hmac[off + 1] & 0xff) << 16) |
208
- ((hmac[off + 2] & 0xff) << 8) |
209
- (hmac[off + 3] & 0xff);
204
+ // RFC 4226 dynamic truncation. `readUInt32BE` reads the four bytes as
205
+ // one value and bounds-checks itself, where four indexed reads each
206
+ // came back "a byte, or nothing" — the digest is 20 bytes and the
207
+ // offset is masked to 0-15, so the window always fits.
208
+ const off = (hmac.at(-1) ?? 0) & 0xf;
209
+ const bin = hmac.readUInt32BE(off) & 0x7fffffff;
210
210
  return (bin % 10 ** this.#cfg.digits)
211
211
  .toString()
212
212
  .padStart(this.#cfg.digits, "0");
package/src/mfa/base32.ts CHANGED
@@ -5,8 +5,8 @@
5
5
 
6
6
  const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
7
7
  const CHAR_TO_VAL: Record<string, number> = {};
8
- for (let i = 0; i < ALPHABET.length; i++) {
9
- CHAR_TO_VAL[ALPHABET[i]] = i;
8
+ for (const [i, char] of [...ALPHABET].entries()) {
9
+ CHAR_TO_VAL[char] = i;
10
10
  }
11
11
 
12
12
  /** Encode bytes to an unpadded, uppercase base32 string. */
@@ -73,15 +73,20 @@ export function decodeCbor(buf: Buffer, start = 0, depth = 0): Decoded {
73
73
  if (start < 0 || start >= buf.length) {
74
74
  throw new Error("CBOR: item starts past the end of the buffer");
75
75
  }
76
- const major = buf[start] >> 5;
77
- const info = buf[start] & 0x1f;
76
+ // `start` was bounds-checked against the buffer just above; naming the
77
+ // byte is what carries that check into the reads below.
78
+ const head = buf[start];
79
+ if (head === undefined)
80
+ throw new Error("CBOR: item starts past the end of the buffer");
81
+ const major = head >> 5;
82
+ const info = head & 0x1f;
78
83
  let len: number;
79
84
  let p = start + 1;
80
85
  if (info < 24) {
81
86
  len = info;
82
87
  } else if (info === 24) {
83
88
  if (p >= buf.length) throw new Error("CBOR: truncated length");
84
- len = buf[p];
89
+ len = buf.readUInt8(p);
85
90
  p += 1;
86
91
  } else if (info === 25) {
87
92
  if (p + 2 > buf.length) throw new Error("CBOR: truncated length");
@@ -183,7 +188,9 @@ export function parseAuthenticatorData(authData: Buffer): AuthenticatorData {
183
188
  if (authData.length < 37) {
184
189
  throw new Error("authenticatorData is too short");
185
190
  }
186
- const flagsByte = authData[32];
191
+ // The length check above guarantees byte 32; `readUInt8` bounds-checks it
192
+ // again rather than reading it as a byte that might not be there.
193
+ const flagsByte = authData.readUInt8(32);
187
194
  const flags = {
188
195
  up: (flagsByte & 0x01) !== 0,
189
196
  uv: (flagsByte & 0x04) !== 0,
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) {
@@ -0,0 +1,110 @@
1
+ // Generated from scripts/vendor/nativeBinary.ts — do not edit.
2
+ //
3
+ // This package is published and built from its own repository, so the file
4
+ // has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
5
+ // and `pnpm vendor:check` fails if this copy has drifted from the original.
6
+
7
+ /**
8
+ * Finding the NAPI binary a package ships beside itself.
9
+ *
10
+ * Every package with a Rust engine repeats the same table: napi-rs names its
11
+ * artefacts `index.<platform>-<arch>-<abi>.node`, and the mapping from Node's
12
+ * `platform`/`arch` to that suffix is the part that must never differ between
13
+ * packages. Adding a target means adding it everywhere, and a package that
14
+ * missed the edit fails only on that platform — which is exactly the failure
15
+ * nobody reproduces.
16
+ *
17
+ * What is NOT here is the policy. Some packages degrade when the binary is
18
+ * absent and answer `undefined`; others refuse loudly with build instructions.
19
+ * Both are right for their package, so the loader reports what happened and
20
+ * the caller decides.
21
+ */
22
+
23
+ import { createRequire } from "node:module";
24
+ import { dirname, join } from "node:path";
25
+ import { arch, platform } from "node:process";
26
+ import { fileURLToPath } from "node:url";
27
+
28
+ /** Node's `platform-arch` → the suffix napi-rs builds under. */
29
+ const TARGETS: Record<string, string> = {
30
+ "linux-x64": "linux-x64-gnu",
31
+ "linux-arm64": "linux-arm64-gnu",
32
+ "darwin-x64": "darwin-x64",
33
+ "darwin-arm64": "darwin-arm64",
34
+ "win32-x64": "win32-x64-msvc",
35
+ };
36
+
37
+ /**
38
+ * Every `platform-arch` a binary is built for.
39
+ *
40
+ * For the message a package raises when it refuses: "no binary for
41
+ * linux-riscv64" is only actionable next to the list of what there IS.
42
+ */
43
+ export function supportedTargets(): readonly string[] {
44
+ return Object.keys(TARGETS);
45
+ }
46
+
47
+ /** The suffix a given `platform-arch` builds under, or `undefined`. */
48
+ export function nativeTargetSuffix(target: string): string | undefined {
49
+ return TARGETS[target];
50
+ }
51
+
52
+ /** The suffix for THIS platform, or `undefined` where no binary is built. */
53
+ export function nativeBinarySuffix(): string | undefined {
54
+ return nativeTargetSuffix(`${platform}-${arch}`);
55
+ }
56
+
57
+ /**
58
+ * Why the binary is not there, phrased for whoever has to fix it.
59
+ *
60
+ * "not found" and "not built for your platform" call for different actions,
61
+ * and a single "unavailable" leaves the reader to guess which one they are
62
+ * looking at.
63
+ */
64
+ export function unavailableReason(cause?: unknown): string {
65
+ if (cause !== undefined) {
66
+ return `failed to load (${cause instanceof Error ? cause.message : String(cause)})`;
67
+ }
68
+ const target = `${platform}-${arch}`;
69
+ return nativeTargetSuffix(target) !== undefined
70
+ ? "binary not found"
71
+ : `no prebuilt binary for ${target}`;
72
+ }
73
+
74
+ /**
75
+ * `musl` builds under a different suffix, and the failure is otherwise
76
+ * baffling: the file is there, and `require` still refuses it. Worth saying so
77
+ * in a message rather than leaving a reader to discover glibc.
78
+ */
79
+ export function muslHint(): string {
80
+ return platform === "linux"
81
+ ? " On Alpine/musl, the gnu binary will not load — build the musl target."
82
+ : "";
83
+ }
84
+
85
+ /** What a load attempt did, so the caller can apply its own policy. */
86
+ export type NativeBinaryResult<T> =
87
+ | { loaded: true; binary: T }
88
+ | { loaded: false; suffix: string | undefined; cause?: unknown };
89
+
90
+ /**
91
+ * Load `<package root>/index.<suffix>.node`.
92
+ *
93
+ * The path is fixed rather than passed: this file is generated into
94
+ * `<package>/src/vendor/`, so the package root is always two levels up, from
95
+ * `src` and from `dist` alike.
96
+ */
97
+ export function loadNativeBinary<T>(): NativeBinaryResult<T> {
98
+ const suffix = nativeBinarySuffix();
99
+ if (suffix === undefined) return { loaded: false, suffix };
100
+ const here = dirname(fileURLToPath(import.meta.url));
101
+ try {
102
+ const nodeRequire = createRequire(import.meta.url);
103
+ return {
104
+ loaded: true,
105
+ binary: nodeRequire(join(here, `../../index.${suffix}.node`)) as T,
106
+ };
107
+ } catch (cause) {
108
+ return { loaded: false, suffix, cause };
109
+ }
110
+ }