@c9up/warden 0.2.5 → 0.2.7

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 (183) hide show
  1. package/README.md +74 -5
  2. package/dist/AccessToken.d.ts +257 -0
  3. package/dist/AccessToken.d.ts.map +1 -0
  4. package/dist/AccessToken.js +370 -0
  5. package/dist/AccessToken.js.map +1 -0
  6. package/dist/AttemptStore.d.ts +16 -2
  7. package/dist/AttemptStore.d.ts.map +1 -1
  8. package/dist/AttemptStore.js +38 -12
  9. package/dist/AttemptStore.js.map +1 -1
  10. package/dist/AuthManager.d.ts +44 -8
  11. package/dist/AuthManager.d.ts.map +1 -1
  12. package/dist/AuthManager.js +42 -11
  13. package/dist/AuthManager.js.map +1 -1
  14. package/dist/AuthRateLimiter.d.ts +16 -3
  15. package/dist/AuthRateLimiter.d.ts.map +1 -1
  16. package/dist/AuthRateLimiter.js +25 -6
  17. package/dist/AuthRateLimiter.js.map +1 -1
  18. package/dist/Authenticator.d.ts +98 -10
  19. package/dist/Authenticator.d.ts.map +1 -1
  20. package/dist/Authenticator.js +223 -19
  21. package/dist/Authenticator.js.map +1 -1
  22. package/dist/Guard.d.ts.map +1 -1
  23. package/dist/Guard.js +17 -5
  24. package/dist/Guard.js.map +1 -1
  25. package/dist/RedisBlacklistDriver.d.ts.map +1 -1
  26. package/dist/RedisBlacklistDriver.js +11 -0
  27. package/dist/RedisBlacklistDriver.js.map +1 -1
  28. package/dist/RefreshTokenStore.d.ts +37 -6
  29. package/dist/RefreshTokenStore.d.ts.map +1 -1
  30. package/dist/RefreshTokenStore.js +51 -10
  31. package/dist/RefreshTokenStore.js.map +1 -1
  32. package/dist/ResilientBlacklistDriver.d.ts +23 -6
  33. package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
  34. package/dist/ResilientBlacklistDriver.js +26 -9
  35. package/dist/ResilientBlacklistDriver.js.map +1 -1
  36. package/dist/TokenBlacklist.d.ts +3 -1
  37. package/dist/TokenBlacklist.d.ts.map +1 -1
  38. package/dist/TokenBlacklist.js +27 -1
  39. package/dist/TokenBlacklist.js.map +1 -1
  40. package/dist/WardenProvider.d.ts +2 -0
  41. package/dist/WardenProvider.d.ts.map +1 -1
  42. package/dist/WardenProvider.js +4 -58
  43. package/dist/WardenProvider.js.map +1 -1
  44. package/dist/authFinder.d.ts +58 -0
  45. package/dist/authFinder.d.ts.map +1 -0
  46. package/dist/authFinder.js +77 -0
  47. package/dist/authFinder.js.map +1 -0
  48. package/dist/bearer.d.ts +12 -0
  49. package/dist/bearer.d.ts.map +1 -0
  50. package/dist/bearer.js +19 -0
  51. package/dist/bearer.js.map +1 -0
  52. package/dist/bouncer/Bouncer.d.ts +2 -2
  53. package/dist/bouncer/Bouncer.d.ts.map +1 -1
  54. package/dist/bouncer/Bouncer.js +17 -4
  55. package/dist/bouncer/Bouncer.js.map +1 -1
  56. package/dist/bouncer/PolicyAuthorizer.d.ts +1 -1
  57. package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
  58. package/dist/bouncer/PolicyAuthorizer.js +1 -1
  59. package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
  60. package/dist/bouncer/evaluate.d.ts +5 -1
  61. package/dist/bouncer/evaluate.d.ts.map +1 -1
  62. package/dist/bouncer/evaluate.js +7 -6
  63. package/dist/bouncer/evaluate.js.map +1 -1
  64. package/dist/config.d.ts +8 -4
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +4 -1
  67. package/dist/config.js.map +1 -1
  68. package/dist/errors.d.ts +28 -0
  69. package/dist/errors.d.ts.map +1 -1
  70. package/dist/errors.js +63 -2
  71. package/dist/errors.js.map +1 -1
  72. package/dist/index.d.ts +10 -6
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +6 -4
  75. package/dist/index.js.map +1 -1
  76. package/dist/mfa/MfaManager.d.ts +33 -8
  77. package/dist/mfa/MfaManager.d.ts.map +1 -1
  78. package/dist/mfa/MfaManager.js +69 -20
  79. package/dist/mfa/MfaManager.js.map +1 -1
  80. package/dist/mfa/TotpProvider.d.ts.map +1 -1
  81. package/dist/mfa/TotpProvider.js +8 -0
  82. package/dist/mfa/TotpProvider.js.map +1 -1
  83. package/dist/mfa/WebauthnProvider.d.ts +22 -0
  84. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  85. package/dist/mfa/WebauthnProvider.js +57 -12
  86. package/dist/mfa/WebauthnProvider.js.map +1 -1
  87. package/dist/middleware.d.ts +13 -3
  88. package/dist/middleware.d.ts.map +1 -1
  89. package/dist/middleware.js +28 -6
  90. package/dist/middleware.js.map +1 -1
  91. package/dist/native.d.ts +6 -2
  92. package/dist/native.d.ts.map +1 -1
  93. package/dist/native.js +19 -2
  94. package/dist/native.js.map +1 -1
  95. package/dist/quasar.d.ts.map +1 -1
  96. package/dist/quasar.js +8 -1
  97. package/dist/quasar.js.map +1 -1
  98. package/dist/rights/RightsResolver.d.ts +10 -0
  99. package/dist/rights/RightsResolver.d.ts.map +1 -1
  100. package/dist/rights/RightsResolver.js +23 -0
  101. package/dist/rights/RightsResolver.js.map +1 -1
  102. package/dist/sanitize.d.ts.map +1 -1
  103. package/dist/sanitize.js +3 -1
  104. package/dist/sanitize.js.map +1 -1
  105. package/dist/services/main.d.ts.map +1 -1
  106. package/dist/services/main.js +12 -2
  107. package/dist/services/main.js.map +1 -1
  108. package/dist/standalone.d.ts +24 -3
  109. package/dist/standalone.d.ts.map +1 -1
  110. package/dist/standalone.js +22 -32
  111. package/dist/standalone.js.map +1 -1
  112. package/dist/strategies/ApiKeyStrategy.d.ts +46 -12
  113. package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
  114. package/dist/strategies/ApiKeyStrategy.js +76 -37
  115. package/dist/strategies/ApiKeyStrategy.js.map +1 -1
  116. package/dist/strategies/BasicAuthStrategy.d.ts.map +1 -1
  117. package/dist/strategies/BasicAuthStrategy.js +5 -2
  118. package/dist/strategies/BasicAuthStrategy.js.map +1 -1
  119. package/dist/strategies/JwtStrategy.d.ts +6 -2
  120. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  121. package/dist/strategies/JwtStrategy.js +58 -11
  122. package/dist/strategies/JwtStrategy.js.map +1 -1
  123. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  124. package/dist/strategies/SessionStrategy.js +4 -1
  125. package/dist/strategies/SessionStrategy.js.map +1 -1
  126. package/dist/templateTags.d.ts +42 -0
  127. package/dist/templateTags.d.ts.map +1 -0
  128. package/dist/templateTags.js +82 -0
  129. package/dist/templateTags.js.map +1 -0
  130. package/dist/vendor/nativeBinary.d.ts +26 -2
  131. package/dist/vendor/nativeBinary.d.ts.map +1 -1
  132. package/dist/vendor/nativeBinary.js +63 -6
  133. package/dist/vendor/nativeBinary.js.map +1 -1
  134. package/dist/vendor/quasarConnection.d.ts +44 -3
  135. package/dist/vendor/quasarConnection.d.ts.map +1 -1
  136. package/dist/vendor/quasarConnection.js +64 -23
  137. package/dist/vendor/quasarConnection.js.map +1 -1
  138. package/index.darwin-arm64.node +0 -0
  139. package/index.darwin-x64.node +0 -0
  140. package/index.linux-arm64-gnu.node +0 -0
  141. package/index.linux-x64-gnu.node +0 -0
  142. package/index.win32-x64-msvc.node +0 -0
  143. package/package.json +9 -5
  144. package/src/AccessToken.ts +550 -0
  145. package/src/AttemptStore.ts +42 -13
  146. package/src/AuthManager.ts +75 -18
  147. package/src/AuthRateLimiter.ts +24 -8
  148. package/src/Authenticator.ts +282 -22
  149. package/src/Guard.ts +18 -5
  150. package/src/RedisBlacklistDriver.ts +11 -0
  151. package/src/RefreshTokenStore.ts +79 -13
  152. package/src/ResilientBlacklistDriver.ts +30 -9
  153. package/src/TokenBlacklist.ts +28 -1
  154. package/src/WardenProvider.ts +6 -83
  155. package/src/authFinder.ts +118 -0
  156. package/src/bearer.ts +16 -0
  157. package/src/bouncer/Bouncer.ts +21 -6
  158. package/src/bouncer/PolicyAuthorizer.ts +1 -1
  159. package/src/bouncer/evaluate.ts +7 -10
  160. package/src/config.ts +8 -4
  161. package/src/errors.ts +80 -2
  162. package/src/index.ts +29 -0
  163. package/src/mfa/MfaManager.ts +98 -22
  164. package/src/mfa/TotpProvider.ts +15 -2
  165. package/src/mfa/WebauthnProvider.ts +77 -13
  166. package/src/middleware.ts +52 -8
  167. package/src/native.ts +20 -4
  168. package/src/quasar.ts +13 -2
  169. package/src/rights/RightsResolver.ts +27 -0
  170. package/src/sanitize.ts +4 -2
  171. package/src/services/main.ts +14 -2
  172. package/src/standalone.ts +75 -37
  173. package/src/strategies/ApiKeyStrategy.ts +117 -42
  174. package/src/strategies/BasicAuthStrategy.ts +7 -2
  175. package/src/strategies/JwtStrategy.ts +61 -10
  176. package/src/strategies/SessionStrategy.ts +4 -1
  177. package/src/templateTags.ts +117 -0
  178. package/src/vendor/nativeBinary.ts +82 -6
  179. package/src/vendor/quasarConnection.ts +105 -22
  180. package/stubs/config/auth.stub +3 -0
  181. package/scripts/build-napi-types.mjs +0 -69
  182. package/scripts/copy-napi.mjs +0 -75
  183. package/scripts/generate-napi-types.mjs +0 -156
@@ -15,6 +15,7 @@ import type {
15
15
  AuthStrategy,
16
16
  UserPayload,
17
17
  } from "../AuthManager.js";
18
+ import { rejectedAsNull } from "../authFinder.js";
18
19
 
19
20
  export interface BasicAuthConfig {
20
21
  /**
@@ -86,11 +87,15 @@ export class BasicAuthStrategy implements AuthStrategy {
86
87
  if (typeof uid !== "string" || typeof password !== "string") {
87
88
  return { authenticated: false, error: "Invalid credentials" };
88
89
  }
89
- const user = await this.#config.verifyCredentials(uid, password);
90
+ const user = await rejectedAsNull(
91
+ this.#config.verifyCredentials(uid, password),
92
+ );
90
93
  // One message for an unknown user and for a wrong password: telling them
91
94
  // apart turns the endpoint into a username oracle.
92
95
  if (!user) return { authenticated: false, error: "Invalid credentials" };
93
- return { authenticated: true, user };
96
+ // A password is not a step-up: whatever the application's user carries
97
+ // under `mfa` (an "MFA enabled" column) must not satisfy `@RequireMfa()`.
98
+ return { authenticated: true, user: { ...user, mfa: false } };
94
99
  }
95
100
 
96
101
  /** Authenticate from the raw `Authorization` header value. */
@@ -10,8 +10,9 @@ import type {
10
10
  AuthStrategy,
11
11
  UserPayload,
12
12
  } from "../AuthManager.js";
13
+ import { rejectedAsNull } from "../authFinder.js";
13
14
  import { resolveExpiresInSeconds, type TokenDuration } from "../duration.js";
14
- import { nativeWarden } from "../native.js";
15
+ import { nativeWarden, nativeWardenLoadError } from "../native.js";
15
16
  import type { TokenBlacklist } from "../TokenBlacklist.js";
16
17
 
17
18
  /**
@@ -26,8 +27,12 @@ export interface JwtClaims {
26
27
  permissions?: string[];
27
28
  iat: number;
28
29
  exp: number;
29
- /** RFC 7519 JWT ID — populated at sign time so revocation can target a single token. */
30
- jti: string;
30
+ /**
31
+ * RFC 7519 JWT ID — populated at sign time so revocation can target a
32
+ * single token. Absent only on a token signed elsewhere, which a strategy
33
+ * with a blacklist refuses (it could never be revoked).
34
+ */
35
+ jti?: string;
31
36
  [key: string]: unknown;
32
37
  }
33
38
 
@@ -47,6 +52,7 @@ function sign(payload: JwtClaims, secret: string): string {
47
52
  if (!rust) {
48
53
  throw new Error(
49
54
  "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
55
+ { cause: nativeWardenLoadError() },
50
56
  );
51
57
  }
52
58
  return rust.jwtSign(JSON.stringify(payload), secret);
@@ -57,16 +63,59 @@ function verify(token: string, secret: string): JwtClaims | null {
57
63
  if (!rust) {
58
64
  throw new Error(
59
65
  "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
66
+ { cause: nativeWardenLoadError() },
60
67
  );
61
68
  }
69
+ let parsed: unknown;
62
70
  try {
63
- const payloadJson = rust.jwtVerify(token, secret);
64
- const payload = JSON.parse(payloadJson) as JwtClaims;
65
- if (typeof payload.sub !== "string" || !payload.sub) return null;
66
- return payload;
71
+ parsed = JSON.parse(rust.jwtVerify(token, secret));
67
72
  } catch {
68
73
  return null;
69
74
  }
75
+ return toJwtClaims(parsed);
76
+ }
77
+
78
+ function isStringArray(value: unknown): value is string[] {
79
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
80
+ }
81
+
82
+ /**
83
+ * The verified payload, if it has the shape {@link JwtClaims} promises.
84
+ *
85
+ * The signature proves who wrote the claims, not what they contain. Trusted
86
+ * as-is, a token without `iat` slipped past an app's "iat predates
87
+ * passwordChangedAt" check in `findUser` (`undefined < n` is false), and a
88
+ * non-string `jti` reached the blacklist. Anything off-shape is refused.
89
+ */
90
+ function toJwtClaims(value: unknown): JwtClaims | null {
91
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
92
+ return null;
93
+ }
94
+ const sub: unknown = Reflect.get(value, "sub");
95
+ const iat: unknown = Reflect.get(value, "iat");
96
+ const exp: unknown = Reflect.get(value, "exp");
97
+ const jti: unknown = Reflect.get(value, "jti");
98
+ const roles: unknown = Reflect.get(value, "roles");
99
+ const permissions: unknown = Reflect.get(value, "permissions");
100
+ if (typeof sub !== "string" || sub.length === 0) return null;
101
+ if (typeof iat !== "number" || !Number.isFinite(iat)) return null;
102
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
103
+ if (jti !== undefined && (typeof jti !== "string" || jti.length === 0)) {
104
+ return null;
105
+ }
106
+ if (roles !== undefined && !isStringArray(roles)) return null;
107
+ if (permissions !== undefined && !isStringArray(permissions)) return null;
108
+ // Optional claims are carried only when the token has them: an explicit
109
+ // `undefined` would show up as a key the token never asserted.
110
+ return {
111
+ ...value,
112
+ sub,
113
+ iat,
114
+ exp,
115
+ ...(jti === undefined ? {} : { jti }),
116
+ ...(roles === undefined ? {} : { roles }),
117
+ ...(permissions === undefined ? {} : { permissions }),
118
+ };
70
119
  }
71
120
 
72
121
  export interface JwtStrategyConfig {
@@ -174,7 +223,7 @@ export class JwtStrategy implements AuthStrategy {
174
223
  return { authenticated: false, error: "Email and password are required" };
175
224
  }
176
225
 
177
- const user = await this.#verifyCredentials(email, password);
226
+ const user = await rejectedAsNull(this.#verifyCredentials(email, password));
178
227
  if (!user) {
179
228
  return { authenticated: false, error: "Invalid credentials" };
180
229
  }
@@ -199,7 +248,7 @@ export class JwtStrategy implements AuthStrategy {
199
248
  // trust such a token — reject it rather than let an
200
249
  // unrevocable token through. (signToken always sets a jti;
201
250
  // this guards legacy / externally-signed tokens.)
202
- if (typeof payload.jti !== "string" || payload.jti.length === 0) {
251
+ if (payload.jti === undefined) {
203
252
  return { authenticated: false, error: "Token missing jti claim" };
204
253
  }
205
254
  if (await this.#blacklist.isRevoked(payload.jti)) {
@@ -268,7 +317,9 @@ export class JwtStrategy implements AuthStrategy {
268
317
  );
269
318
  }
270
319
  const payload = this.#verifyWithRotation(token);
271
- if (!payload) return false;
320
+ // No jti, nothing to list: verify() refuses such a token anyway once a
321
+ // blacklist is configured, which revoking requires.
322
+ if (!payload || payload.jti === undefined) return false;
272
323
  const expMs = payload.exp * 1000;
273
324
  if (expMs <= Date.now()) return false;
274
325
  await this.#blacklist.revoke(payload.jti, expMs);
@@ -256,7 +256,10 @@ export class SessionStrategy implements AuthStrategy {
256
256
  if (!user) return null;
257
257
 
258
258
  if (state) state.viaRemember = true;
259
- return { user, cookieValue: recycled.value };
259
+ // A revived session has not stepped up (seatSession forgets the marker
260
+ // too): `findUser`'s own `mfa` field must not satisfy `@RequireMfa()`
261
+ // on the request the cookie was replayed on.
262
+ return { user: { ...user, mfa: false }, cookieValue: recycled.value };
260
263
  }
261
264
 
262
265
  /**
@@ -0,0 +1,117 @@
1
+ import { WardenError } from "./errors.js";
2
+
3
+ /** The only surface warden needs of a template engine. */
4
+ export interface TemplateEngineLike {
5
+ registerTag(tag: {
6
+ tagName: string;
7
+ block: boolean;
8
+ seekable: boolean;
9
+ compile(
10
+ parser: unknown,
11
+ buffer: { writeRaw(text: string): void },
12
+ token: {
13
+ properties: { jsArg: string };
14
+ renderBody(): string | Promise<string>;
15
+ evaluate(expression: string): unknown;
16
+ },
17
+ ): void | Promise<void>;
18
+ }): void;
19
+ }
20
+
21
+ /**
22
+ * Register `@can` / `@cannot`, as AdonisJS's bouncer publishes them. A
23
+ * migrated template keeps `@can('PostPolicy.edit', post) … @endcan` unchanged.
24
+ *
25
+ * Both are BLOCK tags and both AWAIT — the check returns a promise — so they
26
+ * render on the async path and raise on a synchronous one, matching upstream
27
+ * (which emits `await bouncer.can(...)`). The checks themselves come from
28
+ * `ctx.bouncer.templateHelpers`, shared into the view per request.
29
+ */
30
+ export function registerBouncerTemplateTags(engine: TemplateEngineLike): void {
31
+ for (const tagName of ["can", "cannot"] as const) {
32
+ engine.registerTag({
33
+ tagName,
34
+ block: true,
35
+ seekable: true,
36
+ async compile(_parser, buffer, token) {
37
+ // The shared bag lives in the render scope under `bouncer`.
38
+ const bouncer = token.evaluate(
39
+ "typeof bouncer === 'undefined' ? undefined : bouncer",
40
+ );
41
+ const check = Reflect.get(Object(bouncer), tagName);
42
+ if (typeof check !== "function") {
43
+ // No bouncer on this request: deny rather than render an
44
+ // unguarded body.
45
+ return;
46
+ }
47
+ const args = token.evaluate(`[${token.properties.jsArg}]`);
48
+ const allowed = await check.apply(
49
+ bouncer,
50
+ Array.isArray(args) ? args : [],
51
+ );
52
+ if (allowed === true) buffer.writeRaw(await token.renderBody());
53
+ },
54
+ });
55
+ }
56
+ }
57
+
58
+ /** Loads the template engine package. Swappable so a test needs no engine. */
59
+ export type EnginePackageLoader = () => Promise<unknown>;
60
+
61
+ const loadInker: EnginePackageLoader = () => {
62
+ // Built rather than written inline: inker is an OPTIONAL peer, and a
63
+ // literal `import("@c9up/inker")` makes a bundler resolve it at build time
64
+ // for an application that never installed it. Computed, it only runs
65
+ // behind the `usingInker` flag.
66
+ const specifier = "@c9up/inker";
67
+ return import(/* @vite-ignore */ specifier);
68
+ };
69
+
70
+ function unusable(detail: string): WardenError {
71
+ return new WardenError(
72
+ "E_WARDEN_TEMPLATE_ENGINE_UNUSABLE",
73
+ `The template engine is installed but @can / @cannot cannot be registered: ${detail}`,
74
+ {
75
+ hint: "`@c9up/inker` must default-export its plugin registrar (`inker.use(plugin)`), whose plugins receive an engine with `registerTag()`.",
76
+ },
77
+ );
78
+ }
79
+
80
+ /**
81
+ * Publish the bouncer tags the way AdonisJS's bouncer does with Edge: through
82
+ * the engine package's MODULE SINGLETON (`inker.use(plugin)`), guarded by the
83
+ * host's `usingInker` flag — never by resolving a container binding. `use()`
84
+ * queues the plugin and the engine runs it before its next render, whenever
85
+ * the engine was built.
86
+ *
87
+ * Returns whether the tags were handed over. A registrar or an engine of the
88
+ * wrong shape is an error, not a skip: an unregistered `@can` would render as
89
+ * plain text and show the guarded body's markup to everyone.
90
+ */
91
+ export async function installBouncerTemplateTags(
92
+ usingInker: boolean,
93
+ load: EnginePackageLoader = loadInker,
94
+ ): Promise<boolean> {
95
+ if (!usingInker) return false;
96
+ const module: unknown = await load();
97
+ const registrar =
98
+ typeof module === "object" && module !== null
99
+ ? Reflect.get(module, "default")
100
+ : undefined;
101
+ const use = Reflect.get(Object(registrar), "use");
102
+ if (typeof use !== "function") {
103
+ throw unusable("its default export has no use()");
104
+ }
105
+ use.call(registrar, (engine: unknown) => {
106
+ const register = Reflect.get(Object(engine), "registerTag");
107
+ if (typeof register !== "function") {
108
+ throw unusable("the engine has no registerTag()");
109
+ }
110
+ registerBouncerTemplateTags({
111
+ registerTag: (tag) => {
112
+ register.call(engine, tag);
113
+ },
114
+ });
115
+ });
116
+ return true;
117
+ }
@@ -87,24 +87,100 @@ export type NativeBinaryResult<T> =
87
87
  | { loaded: true; binary: T }
88
88
  | { loaded: false; suffix: string | undefined; cause?: unknown };
89
89
 
90
+ /** Whether `value` carries a function under `name` (a napi class is one too). */
91
+ function hasFunction(value: object, name: string): boolean {
92
+ const member: unknown = Reflect.get(value, name);
93
+ return typeof member === "function";
94
+ }
95
+
90
96
  /**
91
- * Load `<package root>/index.<suffix>.node`.
97
+ * The names among `names` that `value` does not carry as functions.
98
+ *
99
+ * Classes count, being functions, and so does a class's static member: `value`
100
+ * may itself be a function. What a guard rejects is only useful named, so the
101
+ * loader reports this list rather than a bare "no".
102
+ */
103
+ export function missingFunctions(
104
+ value: unknown,
105
+ names: readonly string[],
106
+ ): string[] {
107
+ if (
108
+ value === null ||
109
+ (typeof value !== "object" && typeof value !== "function")
110
+ ) {
111
+ return [...names];
112
+ }
113
+ return names.filter((name) => !hasFunction(value, name));
114
+ }
115
+
116
+ /**
117
+ * Whether `value` carries every one of `names` as a function.
118
+ *
119
+ * The building block of the guard a package hands to `loadNativeBinary`, over
120
+ * the list of what it actually calls on its binary — the same list it passes
121
+ * as `expects`, so the message can name what is missing.
122
+ */
123
+ export function hasFunctions(
124
+ value: unknown,
125
+ names: readonly string[],
126
+ ): value is object {
127
+ if (
128
+ value === null ||
129
+ (typeof value !== "object" && typeof value !== "function")
130
+ ) {
131
+ return false;
132
+ }
133
+ return missingFunctions(value, names).length === 0;
134
+ }
135
+
136
+ /**
137
+ * Load `<package root>/index.<suffix>.node`, and check it is the binary the
138
+ * package calls.
92
139
  *
93
140
  * The path is fixed rather than passed: this file is generated into
94
141
  * `<package>/src/vendor/`, so the package root is always two levels up, from
95
142
  * `src` and from `dist` alike.
143
+ *
144
+ * `isBinary` is the package's own check of what it calls. A declaration only
145
+ * says what the Rust promises: a stale build, or one from another version,
146
+ * loads just as well and then fails on the first missing call, far from here.
147
+ * A rejected module is reported as a failed load, so the package's policy
148
+ * (degrade or refuse) applies to it unchanged. `expects`, the list the guard is
149
+ * built from, lets that report name the missing calls.
96
150
  */
97
- export function loadNativeBinary<T>(): NativeBinaryResult<T> {
151
+ export function loadNativeBinary<T>(
152
+ isBinary: (value: unknown) => value is T,
153
+ expects?: readonly string[],
154
+ ): NativeBinaryResult<T> {
98
155
  const suffix = nativeBinarySuffix();
99
156
  if (suffix === undefined) return { loaded: false, suffix };
100
157
  const here = dirname(fileURLToPath(import.meta.url));
158
+ let loaded: unknown;
101
159
  try {
102
160
  const nodeRequire = createRequire(import.meta.url);
103
- return {
104
- loaded: true,
105
- binary: nodeRequire(join(here, `../../index.${suffix}.node`)) as T,
106
- };
161
+ loaded = nodeRequire(join(here, `../../index.${suffix}.node`));
107
162
  } catch (cause) {
108
163
  return { loaded: false, suffix, cause };
109
164
  }
165
+ if (isBinary(loaded)) return { loaded: true, binary: loaded };
166
+ return {
167
+ loaded: false,
168
+ suffix,
169
+ cause: new Error(
170
+ `index.${suffix}.node loaded, but ${rejection(loaded, expects)}. ` +
171
+ "The binary is stale or from another version: rebuild it.",
172
+ ),
173
+ };
174
+ }
175
+
176
+ /** What a rejected binary lacks, or, without a list to check, what it has. */
177
+ function rejection(loaded: unknown, expects?: readonly string[]): string {
178
+ const missing =
179
+ expects === undefined ? [] : missingFunctions(loaded, expects);
180
+ if (missing.length > 0) return `it lacks ${missing.join(", ")}`;
181
+ const exported =
182
+ typeof loaded === "object" && loaded !== null
183
+ ? Object.keys(loaded).filter((name) => hasFunction(loaded, name))
184
+ : [];
185
+ return `it is not the binary this package calls (it exports: ${exported.length > 0 ? exported.join(", ") : "none"})`;
110
186
  }
@@ -31,23 +31,83 @@ interface ConnectionSource {
31
31
  * `"connection" in manager` is FALSE while reading it returns the function —
32
32
  * gating on `in` rejected the real manager. And a module namespace under a
33
33
  * test double RAISES for an export it does not have, rather than answering
34
- * undefined, so a bare read fails on the mock. Reading through a catch is what
35
- * satisfies both.
34
+ * undefined, so a bare read fails on the mock.
35
+ *
36
+ * So the read is caught, but what it raised is kept: on quasar's accessor a
37
+ * throw is not an absence, it is the accessor saying its provider has not
38
+ * booted, and dropping that turned it into a wrong diagnosis.
36
39
  */
37
- function readMember(value: unknown, name: string): unknown {
38
- if (typeof value !== "object" || value === null) return undefined;
40
+ type MemberRead = { value: unknown } | { threw: unknown };
41
+
42
+ function readMember(value: unknown, name: string): MemberRead {
43
+ if (typeof value !== "object" || value === null) return { value: undefined };
39
44
  try {
40
- return Reflect.get(value, name);
41
- } catch {
42
- return undefined;
45
+ return { value: Reflect.get(value, name) };
46
+ } catch (threw) {
47
+ return { threw };
43
48
  }
44
49
  }
45
50
 
51
+ function memberValue(read: MemberRead): unknown {
52
+ return "value" in read ? read.value : undefined;
53
+ }
54
+
46
55
  function isConnectionSource(value: unknown): value is ConnectionSource {
47
- return typeof readMember(value, "connection") === "function";
56
+ return typeof memberValue(readMember(value, "connection")) === "function";
48
57
  }
49
58
 
50
- export interface QuasarConnectionRequest {
59
+ /**
60
+ * The commands among `commands` that `value` does not carry as functions.
61
+ *
62
+ * Reads go through the same catch as above, so a command whose read throws
63
+ * counts as missing.
64
+ */
65
+ export function missingCommands(
66
+ value: unknown,
67
+ commands: readonly string[],
68
+ ): string[] {
69
+ return commands.filter(
70
+ (command) => typeof memberValue(readMember(value, command)) !== "function",
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Whether `value` carries every one of `commands` as a function.
76
+ *
77
+ * The building block of the guard a caller passes as `isConnection`, over the
78
+ * same list it passes as `required` — which is what names the gap when the
79
+ * guard says no.
80
+ */
81
+ export function hasCommands(
82
+ value: unknown,
83
+ commands: readonly string[],
84
+ ): value is object {
85
+ if (typeof value !== "object" || value === null) return false;
86
+ return missingCommands(value, commands).length === 0;
87
+ }
88
+
89
+ /**
90
+ * Whether a client resolved earlier has ended for good, and must be resolved
91
+ * again rather than used.
92
+ *
93
+ * ioredis reaches `end` once its retry strategy gives up (quasar's generated
94
+ * config gives up after ten attempts, about three seconds of outage), or after
95
+ * `quit()`/`disconnect()`. From there every command rejects with "Connection is
96
+ * closed." and the client never comes back. Quasar drops such a connection and
97
+ * hands out a fresh one on the next `connection(name)`, so a store that kept
98
+ * the first answer of its resolver stayed on the dead client until the process
99
+ * restarted, even once Redis was back.
100
+ *
101
+ * `close` is NOT terminal: ioredis reconnects from it by itself, and throwing
102
+ * that client away would leak its socket. A client with no `status` (a test
103
+ * double, another library) never counts as ended. Only meaningful for a
104
+ * resolver: a client handed in directly is the caller's to replace.
105
+ */
106
+ export function hasEnded(client: unknown): boolean {
107
+ return memberValue(readMember(client, "status")) === "end";
108
+ }
109
+
110
+ export interface QuasarConnectionRequest<T> {
51
111
  /** The package asking. It prefixes every message this can raise. */
52
112
  pkg: string;
53
113
  /**
@@ -65,8 +125,16 @@ export interface QuasarConnectionRequest {
65
125
  ) => Error;
66
126
  /** Connection name, or `undefined` for quasar's default. */
67
127
  name?: string;
68
- /** The commands the caller will actually issue. */
128
+ /** The commands the caller will actually issue, named in the message. */
69
129
  required: readonly string[];
130
+ /**
131
+ * The caller's check that the connection is the client it needs.
132
+ *
133
+ * Written by the caller over the commands it issues (`hasCommands` with
134
+ * `required` does it), because only the caller knows its client type. The
135
+ * connection is handed over only once this has said yes.
136
+ */
137
+ isConnection: (value: unknown) => value is T;
70
138
  /** What the caller does with them, for the message that names a gap. */
71
139
  what: string;
72
140
  /**
@@ -86,9 +154,10 @@ export interface QuasarConnectionRequest {
86
154
  * command, far from the line that asked for it.
87
155
  */
88
156
  export async function quasarConnection<T>(
89
- request: QuasarConnectionRequest,
157
+ request: QuasarConnectionRequest<T>,
90
158
  ): Promise<T> {
91
- const { pkg, name, required, what, raise, alternative } = request;
159
+ const { pkg, name, required, what, raise, alternative, isConnection } =
160
+ request;
92
161
  const specifier = "@c9up/quasar/services/main";
93
162
  let loaded: unknown;
94
163
  try {
@@ -102,9 +171,22 @@ export async function quasarConnection<T>(
102
171
  );
103
172
  }
104
173
 
105
- const manager = isConnectionSource(loaded)
106
- ? loaded
107
- : Reflect.get(Object(loaded), "default");
174
+ // The namespace itself may be the manager (a test double); a throw there is
175
+ // the mock refusing an export it lacks, not an answer.
176
+ const direct = memberValue(readMember(loaded, "connection"));
177
+ const manager =
178
+ typeof direct === "function"
179
+ ? loaded
180
+ : memberValue(readMember(Object(loaded), "default"));
181
+ const read = readMember(manager, "connection");
182
+ if ("threw" in read) {
183
+ throw raise(
184
+ "quasar-missing",
185
+ `[${pkg}] ${what} asks for the quasar connection "${name ?? "default"}", but @c9up/quasar's manager is not available yet: ` +
186
+ "its provider has not booted, or is not registered in this application's providers.",
187
+ read.threw,
188
+ );
189
+ }
108
190
  if (!isConnectionSource(manager)) {
109
191
  throw raise(
110
192
  "quasar-missing",
@@ -113,17 +195,18 @@ export async function quasarConnection<T>(
113
195
  }
114
196
 
115
197
  const connection = manager.connection(name);
116
- const missing = required.filter(
117
- (command) => typeof readMember(connection, command) !== "function",
118
- );
198
+ const missing = missingCommands(connection, required);
119
199
  if (missing.length > 0) {
120
200
  throw raise(
121
201
  "incomplete-connection",
122
202
  `[${pkg}] the quasar connection${name ? ` '${name}'` : ""} is missing ${missing.join(", ")}, which ${what} issues`,
123
203
  );
124
204
  }
125
- // Load-bearing: every member of `required` has just been checked to be a
126
- // function on this object. The caller names the type it needs because only
127
- // the caller knows which commands it asked for.
128
- return connection as T;
205
+ if (!isConnection(connection)) {
206
+ throw raise(
207
+ "incomplete-connection",
208
+ `[${pkg}] the quasar connection${name ? ` '${name}'` : ""} is not the client ${what} needs`,
209
+ );
210
+ }
211
+ return connection;
129
212
  }
@@ -12,6 +12,9 @@ export default defineConfig({
12
12
  expiresIn: process.env.JWT_EXPIRY ?? 3600,
13
13
  // TODO: wire these to your user model (e.g. via your ORM).
14
14
  // The JWT guard needs both to issue and verify tokens.
15
+ // For verifyCredentials, build on authFinder({ hash, findForAuth }) from
16
+ // '@c9up/warden': it pays a hash for an unknown email too, so the login
17
+ // response time does not reveal which accounts exist.
15
18
  findUser: async (_id) => {
16
19
  throw new Error('TODO: implement findUser(id) for the JWT guard in config/auth.ts')
17
20
  },
@@ -1,69 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Regenerate `src/native/generated.ts` from the Rust.
4
- *
5
- * Node rather than a shell script because this runs inside `build:napi`, and
6
- * that runs on the Windows prebuild runner too: a bash `mktemp` there hands
7
- * cargo a `/tmp/...` path the native proc-macro cannot write to, so the
8
- * type-def file comes back empty and the build fails for no visible reason.
9
- *
10
- * One crate at a time on purpose: with napi-derive 2 the writes all went to a
11
- * single `TYPE_DEF_TMP_PATH` and a parallel build interleaved them
12
- * while cargo compiles, and a parallel build interleaves the writes —
13
- * definitions go missing, silently, and the generated file comes out short.
14
- */
15
-
16
- import { execFileSync } from 'node:child_process'
17
- import { createRequire } from 'node:module'
18
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
19
- import { tmpdir } from 'node:os'
20
- import { dirname, join } from 'node:path'
21
- import { fileURLToPath } from 'node:url'
22
-
23
- const CRATES = ['warden-engine-napi']
24
-
25
- const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
26
- const output = join('src', 'native', 'generated.ts')
27
- const scratch = mkdtempSync(join(tmpdir(), 'napi-types-'))
28
-
29
- try {
30
- const lines = []
31
- for (const crate of CRATES) {
32
- const perCrate = join(scratch, crate)
33
- writeFileSync(perCrate, '')
34
- execFileSync('cargo', ['build', '-p', crate], {
35
- cwd: packageRoot,
36
- env: { ...process.env, NAPI_TYPE_DEF_TMP_FOLDER: scratch },
37
- stdio: ['ignore', 'ignore', 'inherit'],
38
- })
39
- const emitted = readFileSync(perCrate, 'utf8').split('\n').filter(Boolean)
40
- if (emitted.length === 0) {
41
- throw new Error(
42
- `[napi-types] ${crate} emitted nothing — is napi-derive's "type-def" feature on?`,
43
- )
44
- }
45
- lines.push(...emitted)
46
- }
47
-
48
- const combined = join(scratch, 'combined.jsonl')
49
- writeFileSync(combined, `${lines.join('\n')}\n`)
50
-
51
- execFileSync(
52
- process.execPath,
53
- [join('scripts', 'generate-napi-types.mjs'), combined, output],
54
- { cwd: packageRoot, stdio: 'inherit' },
55
- )
56
-
57
- // Formatted here rather than excluded from the linter: the file is checked
58
- // in, so it should read like the rest of the tree — and formatting it at
59
- // generation means it never shows up as a diff someone has to fix by hand.
60
- // Resolved through the package entry rather than `node_modules/.bin`, whose
61
- // shim is a shell script the Windows runner cannot execute directly.
62
- const biome = createRequire(import.meta.url).resolve('@biomejs/biome/bin/biome')
63
- execFileSync(process.execPath, [biome, 'format', '--write', output], {
64
- cwd: packageRoot,
65
- stdio: ['ignore', 'ignore', 'inherit'],
66
- })
67
- } finally {
68
- rmSync(scratch, { recursive: true, force: true })
69
- }