@c9up/warden 0.2.6 → 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 (142) hide show
  1. package/README.md +4 -2
  2. package/dist/AttemptStore.d.ts.map +1 -1
  3. package/dist/AttemptStore.js +12 -0
  4. package/dist/AttemptStore.js.map +1 -1
  5. package/dist/AuthManager.d.ts +11 -6
  6. package/dist/AuthManager.d.ts.map +1 -1
  7. package/dist/AuthManager.js +19 -9
  8. package/dist/AuthManager.js.map +1 -1
  9. package/dist/AuthRateLimiter.d.ts +16 -3
  10. package/dist/AuthRateLimiter.d.ts.map +1 -1
  11. package/dist/AuthRateLimiter.js +25 -6
  12. package/dist/AuthRateLimiter.js.map +1 -1
  13. package/dist/Authenticator.d.ts +79 -9
  14. package/dist/Authenticator.d.ts.map +1 -1
  15. package/dist/Authenticator.js +186 -16
  16. package/dist/Authenticator.js.map +1 -1
  17. package/dist/RedisBlacklistDriver.d.ts.map +1 -1
  18. package/dist/RedisBlacklistDriver.js +11 -0
  19. package/dist/RedisBlacklistDriver.js.map +1 -1
  20. package/dist/RefreshTokenStore.d.ts +37 -6
  21. package/dist/RefreshTokenStore.d.ts.map +1 -1
  22. package/dist/RefreshTokenStore.js +51 -10
  23. package/dist/RefreshTokenStore.js.map +1 -1
  24. package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
  25. package/dist/ResilientBlacklistDriver.js +2 -1
  26. package/dist/ResilientBlacklistDriver.js.map +1 -1
  27. package/dist/TokenBlacklist.d.ts +3 -1
  28. package/dist/TokenBlacklist.d.ts.map +1 -1
  29. package/dist/TokenBlacklist.js +27 -1
  30. package/dist/TokenBlacklist.js.map +1 -1
  31. package/dist/authFinder.d.ts +58 -0
  32. package/dist/authFinder.d.ts.map +1 -0
  33. package/dist/authFinder.js +77 -0
  34. package/dist/authFinder.js.map +1 -0
  35. package/dist/bearer.d.ts +12 -0
  36. package/dist/bearer.d.ts.map +1 -0
  37. package/dist/bearer.js +19 -0
  38. package/dist/bearer.js.map +1 -0
  39. package/dist/bouncer/Bouncer.d.ts +2 -2
  40. package/dist/bouncer/Bouncer.d.ts.map +1 -1
  41. package/dist/bouncer/Bouncer.js +17 -4
  42. package/dist/bouncer/Bouncer.js.map +1 -1
  43. package/dist/bouncer/PolicyAuthorizer.d.ts +1 -1
  44. package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
  45. package/dist/bouncer/PolicyAuthorizer.js +1 -1
  46. package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
  47. package/dist/bouncer/evaluate.d.ts +5 -1
  48. package/dist/bouncer/evaluate.d.ts.map +1 -1
  49. package/dist/bouncer/evaluate.js +7 -6
  50. package/dist/bouncer/evaluate.js.map +1 -1
  51. package/dist/errors.d.ts +28 -0
  52. package/dist/errors.d.ts.map +1 -1
  53. package/dist/errors.js +63 -2
  54. package/dist/errors.js.map +1 -1
  55. package/dist/index.d.ts +6 -4
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +4 -3
  58. package/dist/index.js.map +1 -1
  59. package/dist/mfa/MfaManager.d.ts +17 -4
  60. package/dist/mfa/MfaManager.d.ts.map +1 -1
  61. package/dist/mfa/MfaManager.js +37 -14
  62. package/dist/mfa/MfaManager.js.map +1 -1
  63. package/dist/mfa/TotpProvider.d.ts.map +1 -1
  64. package/dist/mfa/TotpProvider.js +8 -0
  65. package/dist/mfa/TotpProvider.js.map +1 -1
  66. package/dist/mfa/WebauthnProvider.d.ts +22 -0
  67. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  68. package/dist/mfa/WebauthnProvider.js +57 -12
  69. package/dist/mfa/WebauthnProvider.js.map +1 -1
  70. package/dist/middleware.d.ts +13 -3
  71. package/dist/middleware.d.ts.map +1 -1
  72. package/dist/middleware.js +1 -1
  73. package/dist/middleware.js.map +1 -1
  74. package/dist/rights/RightsResolver.d.ts +10 -0
  75. package/dist/rights/RightsResolver.d.ts.map +1 -1
  76. package/dist/rights/RightsResolver.js +23 -0
  77. package/dist/rights/RightsResolver.js.map +1 -1
  78. package/dist/sanitize.d.ts.map +1 -1
  79. package/dist/sanitize.js +3 -1
  80. package/dist/sanitize.js.map +1 -1
  81. package/dist/services/main.d.ts.map +1 -1
  82. package/dist/services/main.js +12 -2
  83. package/dist/services/main.js.map +1 -1
  84. package/dist/standalone.d.ts.map +1 -1
  85. package/dist/standalone.js +2 -4
  86. package/dist/standalone.js.map +1 -1
  87. package/dist/strategies/ApiKeyStrategy.d.ts +5 -4
  88. package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
  89. package/dist/strategies/ApiKeyStrategy.js +10 -5
  90. package/dist/strategies/ApiKeyStrategy.js.map +1 -1
  91. package/dist/strategies/BasicAuthStrategy.d.ts.map +1 -1
  92. package/dist/strategies/BasicAuthStrategy.js +5 -2
  93. package/dist/strategies/BasicAuthStrategy.js.map +1 -1
  94. package/dist/strategies/JwtStrategy.d.ts +6 -2
  95. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  96. package/dist/strategies/JwtStrategy.js +55 -8
  97. package/dist/strategies/JwtStrategy.js.map +1 -1
  98. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  99. package/dist/strategies/SessionStrategy.js +4 -1
  100. package/dist/strategies/SessionStrategy.js.map +1 -1
  101. package/dist/vendor/quasarConnection.d.ts +18 -0
  102. package/dist/vendor/quasarConnection.d.ts.map +1 -1
  103. package/dist/vendor/quasarConnection.js +20 -0
  104. package/dist/vendor/quasarConnection.js.map +1 -1
  105. package/index.darwin-arm64.node +0 -0
  106. package/index.darwin-x64.node +0 -0
  107. package/index.linux-arm64-gnu.node +0 -0
  108. package/index.linux-x64-gnu.node +0 -0
  109. package/index.win32-x64-msvc.node +0 -0
  110. package/package.json +3 -4
  111. package/src/AttemptStore.ts +13 -0
  112. package/src/AuthManager.ts +35 -16
  113. package/src/AuthRateLimiter.ts +24 -8
  114. package/src/Authenticator.ts +243 -19
  115. package/src/RedisBlacklistDriver.ts +11 -0
  116. package/src/RefreshTokenStore.ts +79 -13
  117. package/src/ResilientBlacklistDriver.ts +2 -1
  118. package/src/TokenBlacklist.ts +28 -1
  119. package/src/authFinder.ts +118 -0
  120. package/src/bearer.ts +16 -0
  121. package/src/bouncer/Bouncer.ts +21 -6
  122. package/src/bouncer/PolicyAuthorizer.ts +1 -1
  123. package/src/bouncer/evaluate.ts +7 -10
  124. package/src/errors.ts +80 -2
  125. package/src/index.ts +11 -0
  126. package/src/mfa/MfaManager.ts +59 -16
  127. package/src/mfa/TotpProvider.ts +15 -2
  128. package/src/mfa/WebauthnProvider.ts +77 -13
  129. package/src/middleware.ts +16 -3
  130. package/src/rights/RightsResolver.ts +27 -0
  131. package/src/sanitize.ts +4 -2
  132. package/src/services/main.ts +14 -2
  133. package/src/standalone.ts +2 -5
  134. package/src/strategies/ApiKeyStrategy.ts +10 -5
  135. package/src/strategies/BasicAuthStrategy.ts +7 -2
  136. package/src/strategies/JwtStrategy.ts +58 -9
  137. package/src/strategies/SessionStrategy.ts +4 -1
  138. package/src/vendor/quasarConnection.ts +21 -0
  139. package/stubs/config/auth.stub +3 -0
  140. package/scripts/build-napi-types.mjs +0 -69
  141. package/scripts/copy-napi.mjs +0 -75
  142. package/scripts/generate-napi-types.mjs +0 -156
package/src/middleware.ts CHANGED
@@ -176,11 +176,24 @@ export interface WardenContext {
176
176
  [key: string]: unknown;
177
177
  };
178
178
  roles?: string[];
179
+ /** What the payload carries — not an authorization input. */
179
180
  permissions?: string[];
180
- authenticate?(): Promise<void>;
181
+ /**
182
+ * The permission check a gate must use: resolved through the rights
183
+ * resolver and narrowed by the request's access token. Optional, like the
184
+ * rest of this structural slot, so a host's own auth state still fits.
185
+ */
186
+ hasPermission?(permission: string, scope?: Scope): Promise<boolean>;
187
+ /** {@link hasPermission} for a list: true only when every one holds. */
188
+ hasAllPermissions?(
189
+ permissions: readonly string[],
190
+ scope?: Scope,
191
+ ): Promise<boolean>;
192
+ /** Resolves to the user (warden's Authenticator); a host's may resolve to nothing. */
193
+ authenticate?(): Promise<unknown>;
181
194
  check?(): Promise<boolean>;
182
195
  getUserOrFail?(): { id: string; [key: string]: unknown } | undefined;
183
- use?(name: string): unknown;
196
+ use?(name?: string): unknown;
184
197
  readonly authenticationAttempted?: boolean;
185
198
  };
186
199
  /**
@@ -479,7 +492,7 @@ export interface BouncerRegistry {
479
492
  * from the authenticated user (`ctx.auth?.user`, or `null` for a guest), the
480
493
  * shared `RightsResolver`, and the registered abilities/policies, then attaches
481
494
  * it as `ctx.bouncer`. Handlers authorize via `await ctx.bouncer.authorize(...)`
482
- * (throws `AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
495
+ * (throws `E_AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
483
496
  * ExceptionHandler maps to a 403 response) or branch on `ctx.bouncer.allows(...)`.
484
497
  *
485
498
  * Unlike `wardenMiddleware` (a per-route GUARD that short-circuits public
@@ -43,6 +43,33 @@ class ResolvedPermissions implements EffectivePermissions {
43
43
  }
44
44
  }
45
45
 
46
+ /**
47
+ * `effective` as the REQUEST may use it: when the user came in with an access
48
+ * token, every permission must also be allowed by that token.
49
+ *
50
+ * The one place the intersection happens for a resolved set, so the coarse
51
+ * helpers (`AuthManager.hasPermission`, the decorator gate) and a policy's
52
+ * `this.permissions` cannot answer differently for the same request. Roles stay
53
+ * the user's: a token restricts what may be DONE, not who the user is.
54
+ */
55
+ export function narrowToAccessToken(
56
+ effective: EffectivePermissions,
57
+ user: UserPayload,
58
+ ): EffectivePermissions {
59
+ const token = user.currentAccessToken;
60
+ if (token === undefined) return effective;
61
+ const allowed = (permission: string): boolean =>
62
+ effective.has(permission) && token.allows(permission);
63
+ return {
64
+ has: allowed,
65
+ hasAll: (permissions) => permissions.every(allowed),
66
+ hasAny: (permissions) => permissions.some(allowed),
67
+ permissions: new Set([...effective.permissions].filter(allowed)),
68
+ roles: effective.roles,
69
+ scope: effective.scope,
70
+ };
71
+ }
72
+
46
73
  export class RightsResolver {
47
74
  constructor(private readonly store: RightsStore) {}
48
75
 
package/src/sanitize.ts CHANGED
@@ -10,8 +10,10 @@ import type { UserPayload } from "./AuthManager.js";
10
10
 
11
11
  export function sanitizePayload(user: UserPayload): void {
12
12
  for (const key of ["__proto__", "constructor", "prototype"]) {
13
- if (key in user) {
14
- delete (user as Record<string, unknown>)[key];
13
+ // Own keys only: `constructor` is always reachable through the
14
+ // prototype, and deleting an inherited name is a no-op anyway.
15
+ if (Object.hasOwn(user, key)) {
16
+ delete user[key];
15
17
  }
16
18
  }
17
19
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import type { AuthManager } from "../AuthManager.js";
14
+ import { WardenError } from "../errors.js";
14
15
 
15
16
  let instance: AuthManager | undefined;
16
17
 
@@ -37,10 +38,21 @@ export function clearAuth(): void {
37
38
  instance = undefined;
38
39
  }
39
40
 
40
- const auth: AuthManager = new Proxy({} as AuthManager, {
41
+ // The target is never read through — every trap forwards to `instance`.
42
+ const target: AuthManager = Object.create(null);
43
+
44
+ const auth: AuthManager = new Proxy(target, {
41
45
  get(_target, prop) {
46
+ // Whatever inspects a value before using it reads `then` (a promise or an
47
+ // async factory resolving with it decides whether it is thenable) and
48
+ // symbols (inspection, coercion, module interop). None is a member of
49
+ // AuthManager, so answer undefined and let a genuine access report.
50
+ if (typeof prop === "symbol" || prop === "then") {
51
+ return undefined;
52
+ }
42
53
  if (!instance) {
43
- throw new Error(
54
+ throw new WardenError(
55
+ "NOT_BOOTED",
44
56
  "[warden] AuthManager singleton accessed before WardenProvider.boot() ran. " +
45
57
  "Check that `@c9up/warden/provider` is listed in your reamrc.ts providers.",
46
58
  );
package/src/standalone.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  type AuthStrategy,
24
24
  type UserPayload,
25
25
  } from "./AuthManager.js";
26
+ import { readBearerToken } from "./bearer.js";
26
27
  import type { WardenConfig } from "./config.js";
27
28
  import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
28
29
  import { JwtStrategy } from "./strategies/JwtStrategy.js";
@@ -127,11 +128,7 @@ export function createWarden(config: WardenConfig): Warden {
127
128
 
128
129
  expressMiddleware() {
129
130
  return (req, res, next) => {
130
- const authHeader = req.headers?.authorization;
131
- const token =
132
- typeof authHeader === "string" && authHeader.startsWith("Bearer ")
133
- ? authHeader.slice(7)
134
- : "";
131
+ const token = readBearerToken(req.headers?.authorization);
135
132
 
136
133
  if (!token) {
137
134
  fail(
@@ -111,10 +111,11 @@ export class ApiKeyStrategy implements AuthStrategy {
111
111
  /**
112
112
  * Revoke the token behind `value`. Answers whether it existed.
113
113
  *
114
- * NAMED DEVIATION — upstream's guard is built per request and revokes the
115
- * token it authenticated with, so it takes no argument. A warden strategy
116
- * is shared by every request and keeps none of them, so the value is passed
117
- * in; a sign-out handler has it, it is the request's credential.
114
+ * Upstream's guard is built per request and revokes the token it
115
+ * authenticated with, so it takes no argument: that shape is the request's
116
+ * guard, `ctx.auth.use('api').invalidateToken()`. A warden strategy is
117
+ * shared by every request and keeps none of them, so here the value is
118
+ * passed in.
118
119
  */
119
120
  invalidateToken(value: string): Promise<boolean> {
120
121
  return this.#config.tokens.invalidate(new Secret(value));
@@ -154,9 +155,13 @@ export class ApiKeyStrategy implements AuthStrategy {
154
155
  }
155
156
  // A copy: the provider's object is the application's, and attaching the
156
157
  // token to it would leak one request's token into the next.
158
+ //
159
+ // `mfa` is the step-up of THIS credential, and an access token carries
160
+ // none: whatever `findUser` said (an "MFA enabled" column, typically)
161
+ // must not satisfy `@RequireMfa()`.
157
162
  return {
158
163
  authenticated: true,
159
- user: { ...user, currentAccessToken: accessToken },
164
+ user: { ...user, currentAccessToken: accessToken, mfa: false },
160
165
  };
161
166
  }
162
167
  }
@@ -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,6 +10,7 @@ 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
15
  import { nativeWarden, nativeWardenLoadError } from "../native.js";
15
16
  import type { TokenBlacklist } from "../TokenBlacklist.js";
@@ -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
 
@@ -61,14 +66,56 @@ function verify(token: string, secret: string): JwtClaims | null {
61
66
  { cause: nativeWardenLoadError() },
62
67
  );
63
68
  }
69
+ let parsed: unknown;
64
70
  try {
65
- const payloadJson = rust.jwtVerify(token, secret);
66
- const payload = JSON.parse(payloadJson) as JwtClaims;
67
- if (typeof payload.sub !== "string" || !payload.sub) return null;
68
- return payload;
71
+ parsed = JSON.parse(rust.jwtVerify(token, secret));
69
72
  } catch {
70
73
  return null;
71
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
+ };
72
119
  }
73
120
 
74
121
  export interface JwtStrategyConfig {
@@ -176,7 +223,7 @@ export class JwtStrategy implements AuthStrategy {
176
223
  return { authenticated: false, error: "Email and password are required" };
177
224
  }
178
225
 
179
- const user = await this.#verifyCredentials(email, password);
226
+ const user = await rejectedAsNull(this.#verifyCredentials(email, password));
180
227
  if (!user) {
181
228
  return { authenticated: false, error: "Invalid credentials" };
182
229
  }
@@ -201,7 +248,7 @@ export class JwtStrategy implements AuthStrategy {
201
248
  // trust such a token — reject it rather than let an
202
249
  // unrevocable token through. (signToken always sets a jti;
203
250
  // this guards legacy / externally-signed tokens.)
204
- if (typeof payload.jti !== "string" || payload.jti.length === 0) {
251
+ if (payload.jti === undefined) {
205
252
  return { authenticated: false, error: "Token missing jti claim" };
206
253
  }
207
254
  if (await this.#blacklist.isRevoked(payload.jti)) {
@@ -270,7 +317,9 @@ export class JwtStrategy implements AuthStrategy {
270
317
  );
271
318
  }
272
319
  const payload = this.#verifyWithRotation(token);
273
- 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;
274
323
  const expMs = payload.exp * 1000;
275
324
  if (expMs <= Date.now()) return false;
276
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
  /**
@@ -86,6 +86,27 @@ export function hasCommands(
86
86
  return missingCommands(value, commands).length === 0;
87
87
  }
88
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
+
89
110
  export interface QuasarConnectionRequest<T> {
90
111
  /** The package asking. It prefixes every message this can raise. */
91
112
  pkg: string;
@@ -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
- }
@@ -1,75 +0,0 @@
1
- import { copyFileSync, existsSync } from 'node:fs'
2
- import { dirname, join, resolve } from 'node:path'
3
- import { arch, env, platform } from 'node:process'
4
- import { fileURLToPath } from 'node:url'
5
-
6
- const here = dirname(fileURLToPath(import.meta.url))
7
- const root = join(here, '..')
8
- const CRATE = 'warden_engine_napi'
9
- const TAG = '[warden:napi]'
10
-
11
- // Rust target triple -> { suffix, os }. Set CARGO_BUILD_TARGET to cross-compile
12
- // (e.g. build the x86_64-apple-darwin binary on an arm64 macOS runner). When
13
- // unset we fall back to the host platform/arch and the default target/release.
14
- const tripleMap = {
15
- 'x86_64-unknown-linux-gnu': { suffix: 'linux-x64-gnu', os: 'linux' },
16
- 'aarch64-unknown-linux-gnu': { suffix: 'linux-arm64-gnu', os: 'linux' },
17
- 'x86_64-apple-darwin': { suffix: 'darwin-x64', os: 'darwin' },
18
- 'aarch64-apple-darwin': { suffix: 'darwin-arm64', os: 'darwin' },
19
- 'x86_64-pc-windows-msvc': { suffix: 'win32-x64-msvc', os: 'win32' },
20
- }
21
-
22
- const hostSuffixMap = {
23
- 'linux-x64': 'linux-x64-gnu',
24
- 'linux-arm64': 'linux-arm64-gnu',
25
- 'darwin-x64': 'darwin-x64',
26
- 'darwin-arm64': 'darwin-arm64',
27
- 'win32-x64': 'win32-x64-msvc',
28
- }
29
-
30
- // Cargo writes its artifacts under CARGO_TARGET_DIR when that is set — a
31
- // shared cache, a CI mount — so they are not under this package's `target/` at
32
- // all. A relative value is resolved against the directory cargo ran in, which
33
- // is this package root.
34
- const targetDir = env.CARGO_TARGET_DIR
35
- ? resolve(root, env.CARGO_TARGET_DIR)
36
- : join(root, 'target')
37
-
38
- const triple = env.CARGO_BUILD_TARGET ?? ''
39
- let suffix
40
- let os
41
- let releaseDir
42
- if (triple) {
43
- const entry = tripleMap[triple]
44
- if (!entry) {
45
- throw new Error(`${TAG} unsupported CARGO_BUILD_TARGET: ${triple}`)
46
- }
47
- suffix = entry.suffix
48
- os = entry.os
49
- releaseDir = join(targetDir, triple, 'release')
50
- } else {
51
- suffix = hostSuffixMap[`${platform}-${arch}`]
52
- os = platform
53
- releaseDir = join(targetDir, 'release')
54
- if (!suffix) {
55
- throw new Error(`${TAG} unsupported platform/arch: ${platform}-${arch}`)
56
- }
57
- }
58
-
59
- const candidates =
60
- os === 'win32'
61
- ? [join(releaseDir, `${CRATE}.dll`), join(releaseDir, `lib${CRATE}.dll`)]
62
- : os === 'darwin'
63
- ? [join(releaseDir, `lib${CRATE}.dylib`)]
64
- : [join(releaseDir, `lib${CRATE}.so`)]
65
-
66
- const source = candidates.find((candidate) => existsSync(candidate))
67
- if (!source) {
68
- throw new Error(
69
- `${TAG} native library not found. Looked for:\n${candidates.map((p) => `- ${p}`).join('\n')}`,
70
- )
71
- }
72
-
73
- const target = join(root, `index.${suffix}.node`)
74
- copyFileSync(source, target)
75
- console.log(`${TAG} copied ${source} -> ${target}`)
@@ -1,156 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Generate the TypeScript surface of the native module FROM the Rust.
4
- *
5
- * `napi-derive`'s `type-def` feature emits one JSON line per exported item
6
- * while cargo compiles. Those lines are the source of truth: they are derived
7
- * from the `#[napi]` items themselves, so a signature cannot drift from the
8
- * Rust without this file changing.
9
- *
10
- * Hand-written interfaces are what this replaces, and they do drift — nothing
11
- * on the TypeScript side notices when a `pub fn` gains a parameter or stops
12
- * being `async`.
13
- *
14
- * One thing napi-rs cannot infer: the shape of a `JsFunction` callback. It
15
- * emits `(...args: any[]) => any`. Any such parameter is refined below, by
16
- * name, and the script fails if a refinement no longer matches anything — so
17
- * the table cannot rot either.
18
- *
19
- * TYPE_DEF_TMP_PATH=<file> cargo build -p <crate>
20
- * node scripts/generate-napi-types.mjs <file> <out.d.ts>
21
- */
22
-
23
- import { readFileSync, writeFileSync } from 'node:fs'
24
-
25
- /**
26
- * Callback signatures napi-rs erases to `any`, restored here.
27
- *
28
- * Keyed by `<owner>.<method>`; the value replaces the whole parameter. Every
29
- * entry must match, or the script fails: a stale refinement is how a hand
30
- * annotation quietly stops describing the Rust.
31
- *
32
- * Empty while this crate exposes no `JsFunction` parameter — add an entry the
33
- * day one appears, rather than letting an `any` through.
34
- */
35
- const CALLBACK_REFINEMENTS = {}
36
-
37
- const [input, output] = process.argv.slice(2)
38
- if (!input || !output) {
39
- console.error('usage: generate-napi-types.mjs <type-def file> <out.d.ts>')
40
- process.exit(2)
41
- }
42
-
43
- const entries = readFileSync(input, 'utf8')
44
- .split('\n')
45
- .map((l) => l.trim())
46
- .filter(Boolean)
47
- .map((l) => JSON.parse(l))
48
-
49
- const used = new Set()
50
-
51
- /** Apply the refinements that belong to `owner`, tracking which ones matched. */
52
- function refine(owner, body) {
53
- let out = body
54
- for (const [key, { from, to }] of Object.entries(CALLBACK_REFINEMENTS)) {
55
- const [entryOwner] = key.split('.')
56
- if (entryOwner !== owner) continue
57
- if (out.includes(from)) {
58
- out = out.replace(from, to)
59
- used.add(key)
60
- }
61
- }
62
- return out
63
- }
64
-
65
- /**
66
- * JSDoc as emitted by napi-derive, indented to sit above its member.
67
- *
68
- * `*` followed by `/` inside the text closes the comment early — a Rust doc
69
- * example holding a cron expression (`0 *​/5 * * *`) is enough to do it, and
70
- * the generated file then fails to parse. Escaped rather than stripped, so the
71
- * example still reads correctly.
72
- */
73
- function docBlock(doc, indent = '') {
74
- if (!doc) return ''
75
- // Escape every `*/` EXCEPT the one that closes the block. A Rust doc example
76
- // holding a cron expression (`0 */5 * * *`) closes the comment early
77
- // otherwise, and the generated file stops parsing — but escaping the closer
78
- // too breaks it just as thoroughly, whether the block spans one line or many.
79
- const closer = doc.lastIndexOf('*/')
80
- const escaped =
81
- closer === -1
82
- ? doc
83
- : doc.slice(0, closer).replaceAll('*/', '*\\/') + doc.slice(closer)
84
- return (
85
- escaped
86
- .split('\n')
87
- .filter((l) => l.length > 0)
88
- .map((l) => `${indent}${l}`)
89
- .join('\n') + '\n'
90
- )
91
- }
92
-
93
- const interfaces = entries.filter((e) => e.kind === 'interface')
94
- const structs = entries.filter((e) => e.kind === 'struct')
95
- const impls = new Map(entries.filter((e) => e.kind === 'impl').map((e) => [e.name, e]))
96
- const fns = entries.filter((e) => e.kind === 'fn')
97
-
98
- const out = [
99
- '// GENERATED FROM THE RUST — do not edit.',
100
- '//',
101
- "// Produced by scripts/generate-napi-types.mjs from napi-derive's type-def",
102
- '// output. Editing this file by hand puts it back where it started: a',
103
- '// description that can disagree with the code it describes.',
104
- '',
105
- ]
106
-
107
- for (const iface of interfaces) {
108
- out.push(docBlock(iface.js_doc))
109
- out.push(`export interface ${iface.name} {`)
110
- for (const line of iface.def.split('\n')) {
111
- out.push(line ? ` ${line.trim()}` : '')
112
- }
113
- out.push('}', '')
114
- }
115
-
116
- for (const struct of structs) {
117
- const impl = impls.get(struct.name)
118
- out.push(docBlock(struct.js_doc))
119
- out.push(`export declare class ${struct.name} {`)
120
- if (impl) {
121
- for (const line of refine(struct.name, impl.def).split('\n')) {
122
- out.push(line ? ` ${line.trim()}` : '')
123
- }
124
- }
125
- out.push('}', '')
126
- }
127
-
128
- for (const fn of fns) {
129
- out.push(docBlock(fn.js_doc))
130
- // napi-derive emits the whole declaration for a function, unlike a struct
131
- // where `def` holds only the members.
132
- const declaration = fn.def.trim()
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};`, '')
142
- }
143
-
144
- const stale = Object.keys(CALLBACK_REFINEMENTS).filter((k) => !used.has(k))
145
- if (stale.length > 0) {
146
- console.error(
147
- `[napi-types] refinement(s) that matched nothing: ${stale.join(', ')}\n` +
148
- '[napi-types] the Rust changed under them — update or remove the entry.',
149
- )
150
- process.exit(1)
151
- }
152
-
153
- writeFileSync(output, out.join('\n'))
154
- console.log(
155
- `[napi-types] ${output} — ${interfaces.length} interface(s), ${structs.length} class(es), ${fns.length} function(s)`,
156
- )