@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
package/src/Guard.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * @implements FR50, FR51
5
5
  */
6
6
 
7
- // Side-effect import: registers the `Reflect.defineMetadata` / `getOwnMetadata`
7
+ // Side-effect import: registers the `Reflect.defineMetadata` / `getMetadata`
8
8
  // methods used below. Pulled in here (not transitively via the framework)
9
9
  // so warden remains self-sufficient when published / consumed standalone.
10
10
  import "reflect-metadata";
@@ -44,12 +44,25 @@ export function Role(...roles: string[]): MethodDecorator {
44
44
  };
45
45
  }
46
46
 
47
+ /*
48
+ * The readers below walk the prototype chain (`Reflect.getMetadata`), so an
49
+ * action a controller inherits keeps the guard and the authorization its parent
50
+ * declared: `class UsersController extends AdminController {}` routes
51
+ * `[UsersController, 'index']` to a method declared on `AdminController`, and
52
+ * reading only the subclass's own metadata made that route public.
53
+ *
54
+ * The metadata belongs to the action NAME, not to the function: an override
55
+ * that declares nothing inherits its parent's decorators too, so redefining a
56
+ * method can never drop a guard by accident. An override that declares its own
57
+ * decorator replaces the parent's for that decorator.
58
+ */
59
+
47
60
  /** Get guard metadata. */
48
61
  export function getGuardMetadata(
49
62
  target: object,
50
63
  propertyKey: string | symbol,
51
64
  ): string[] {
52
- return Reflect.getOwnMetadata(GUARD_KEY, target, propertyKey) ?? [];
65
+ return Reflect.getMetadata(GUARD_KEY, target, propertyKey) ?? [];
53
66
  }
54
67
 
55
68
  /** Get permission metadata. */
@@ -57,7 +70,7 @@ export function getPermissionMetadata(
57
70
  target: object,
58
71
  propertyKey: string | symbol,
59
72
  ): string[] {
60
- return Reflect.getOwnMetadata(PERMISSION_KEY, target, propertyKey) ?? [];
73
+ return Reflect.getMetadata(PERMISSION_KEY, target, propertyKey) ?? [];
61
74
  }
62
75
 
63
76
  /** Get role metadata. */
@@ -65,7 +78,7 @@ export function getRoleMetadata(
65
78
  target: object,
66
79
  propertyKey: string | symbol,
67
80
  ): string[] {
68
- return Reflect.getOwnMetadata(ROLE_KEY, target, propertyKey) ?? [];
81
+ return Reflect.getMetadata(ROLE_KEY, target, propertyKey) ?? [];
69
82
  }
70
83
 
71
84
  /**
@@ -85,5 +98,5 @@ export function getRequireMfaMetadata(
85
98
  target: object,
86
99
  propertyKey: string | symbol,
87
100
  ): boolean {
88
- return Reflect.getOwnMetadata(MFA_KEY, target, propertyKey) ?? false;
101
+ return Reflect.getMetadata(MFA_KEY, target, propertyKey) ?? false;
89
102
  }
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { BlacklistDriver } from "./TokenBlacklist.js";
12
+ import { hasEnded } from "./vendor/quasarConnection.js";
12
13
 
13
14
  /** The minimal ioredis-shaped surface this driver needs. */
14
15
  export interface RedisLikeClient {
@@ -49,8 +50,18 @@ export class RedisBlacklistDriver implements BlacklistDriver {
49
50
  /**
50
51
  * The client, resolved once. Two requests racing on a cold start must not
51
52
  * each open their own connection, so the in-flight promise is shared.
53
+ *
54
+ * Resolved AGAIN once the client it holds has ended for good: quasar
55
+ * retires a connection whose retry strategy gave up and hands out a fresh
56
+ * one, and keeping the dead client failed every revocation check with
57
+ * "Connection is closed." until restart. NAMED DEVIATION, better than
58
+ * upstream, whose Redis stores capture `ioConnection` once. A client handed
59
+ * in directly is kept whatever its state.
52
60
  */
53
61
  async #client(): Promise<RedisLikeClient> {
62
+ if (typeof this.#source === "function" && hasEnded(this.#resolved)) {
63
+ this.#resolved = undefined;
64
+ }
54
65
  if (this.#resolved) return this.#resolved;
55
66
  if (typeof this.#source !== "function") {
56
67
  this.#resolved = this.#source;
@@ -1,26 +1,49 @@
1
1
  /**
2
2
  * RefreshTokenStore — server-side opaque refresh token management.
3
3
  *
4
- * AdonisJS opaque token pattern:
4
+ * Opaque token pattern:
5
5
  * { accessToken, refreshToken, expiresIn }
6
6
  * POST /auth/refresh → new pair, old token invalidated
7
7
  *
8
+ * A refresh token is a bearer credential, so only `sha256(value)` is
9
+ * persisted, like access tokens, remember-me tokens, OTPs and backup codes: a
10
+ * dump of the table is not a set of working tokens. The driver is keyed by
11
+ * that hash and never sees the value; the application hashes what the client
12
+ * presents with {@link hashRefreshToken} before asking the driver.
13
+ *
14
+ * Cutover from a store that held the value itself: fail closed. Rows written
15
+ * before hashing are keyed by the clear value and no presented token hashes
16
+ * to it, so they simply stop refreshing and those clients sign in again.
17
+ * Nothing re-reads a clear value to upgrade it: that would keep the clear
18
+ * column, the very thing this removes, readable as a credential.
19
+ *
8
20
  * @implements MISS-5
9
21
  */
10
22
 
11
23
  import { randomBytes } from "node:crypto";
24
+ import { WardenError } from "./errors.js";
25
+ import { hashSecret } from "./RememberMeToken.js";
12
26
 
13
27
  export interface StoredRefreshToken {
14
- token: string;
28
+ /** `sha256(value)`, hex. The token itself is never stored. */
29
+ hash: string;
15
30
  userId: string | number;
16
31
  expiresAt: number;
17
32
  createdAt: number;
18
33
  }
19
34
 
35
+ /**
36
+ * What a store implements. Every token argument is the HASH from
37
+ * {@link hashRefreshToken}, never the value the client holds.
38
+ */
20
39
  export interface RefreshTokenDriver {
21
40
  store(token: StoredRefreshToken): Promise<void>;
22
- find(token: string): Promise<StoredRefreshToken | null>;
23
- revoke(token: string): Promise<void>;
41
+ find(hash: string): Promise<StoredRefreshToken | null>;
42
+ revoke(hash: string): Promise<void>;
43
+ /**
44
+ * Remove every token of `userId`. Ids are compared as strings: a row
45
+ * stored with `"1"` belongs to user `1`.
46
+ */
24
47
  revokeAllForUser(userId: string | number): Promise<void>;
25
48
  cleanup(): Promise<void>;
26
49
  }
@@ -30,33 +53,36 @@ export class MemoryRefreshTokenDriver implements RefreshTokenDriver {
30
53
  #tokens: Map<string, StoredRefreshToken> = new Map();
31
54
 
32
55
  async store(token: StoredRefreshToken): Promise<void> {
33
- this.#tokens.set(token.token, token);
56
+ this.#tokens.set(token.hash, token);
34
57
  }
35
58
 
36
- async find(token: string): Promise<StoredRefreshToken | null> {
37
- const stored = this.#tokens.get(token);
59
+ async find(hash: string): Promise<StoredRefreshToken | null> {
60
+ const stored = this.#tokens.get(hash);
38
61
  if (!stored) return null;
39
- if (stored.expiresAt < Date.now()) {
40
- this.#tokens.delete(token);
62
+ // "Not in the future" rather than "in the past": an expiry that is not
63
+ // a number counts as expired instead of as never.
64
+ if (!(stored.expiresAt > Date.now())) {
65
+ this.#tokens.delete(hash);
41
66
  return null;
42
67
  }
43
68
  return stored;
44
69
  }
45
70
 
46
- async revoke(token: string): Promise<void> {
47
- this.#tokens.delete(token);
71
+ async revoke(hash: string): Promise<void> {
72
+ this.#tokens.delete(hash);
48
73
  }
49
74
 
50
75
  async revokeAllForUser(userId: string | number): Promise<void> {
76
+ const owner = String(userId);
51
77
  for (const [key, val] of this.#tokens) {
52
- if (val.userId === userId) this.#tokens.delete(key);
78
+ if (String(val.userId) === owner) this.#tokens.delete(key);
53
79
  }
54
80
  }
55
81
 
56
82
  async cleanup(): Promise<void> {
57
83
  const now = Date.now();
58
84
  for (const [key, val] of this.#tokens) {
59
- if (val.expiresAt < now) this.#tokens.delete(key);
85
+ if (!(val.expiresAt > now)) this.#tokens.delete(key);
60
86
  }
61
87
  }
62
88
  }
@@ -65,3 +91,43 @@ export class MemoryRefreshTokenDriver implements RefreshTokenDriver {
65
91
  export function generateRefreshToken(): string {
66
92
  return randomBytes(48).toString("base64url");
67
93
  }
94
+
95
+ /** `sha256(value)` as hex: what is stored, and what the driver is asked for. */
96
+ export function hashRefreshToken(value: string): string {
97
+ return hashSecret(value);
98
+ }
99
+
100
+ /** A freshly minted refresh token: what to store, and what to hand the client. */
101
+ export interface MintedRefreshToken {
102
+ stored: StoredRefreshToken;
103
+ /** Goes to the client. Never persisted. */
104
+ value: string;
105
+ }
106
+
107
+ /** Mint a refresh token for `userId`, valid for `ttlSeconds`. */
108
+ export function mintRefreshToken(
109
+ userId: string | number,
110
+ ttlSeconds: number,
111
+ ): MintedRefreshToken {
112
+ // NaN or Infinity is not a lifetime: the row would never expire.
113
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
114
+ throw new WardenError(
115
+ "E_WARDEN_TOKEN_TTL_INVALID",
116
+ `ttlSeconds must be a positive finite number, got ${String(ttlSeconds)}.`,
117
+ {
118
+ hint: "Give the refresh token a lifetime in seconds, e.g. 2592000 (30 days).",
119
+ },
120
+ );
121
+ }
122
+ const value = generateRefreshToken();
123
+ const now = Date.now();
124
+ return {
125
+ stored: {
126
+ hash: hashRefreshToken(value),
127
+ userId,
128
+ expiresAt: now + ttlSeconds * 1000,
129
+ createdAt: now,
130
+ },
131
+ value,
132
+ };
133
+ }
@@ -3,7 +3,7 @@
3
3
  * `RedisBlacklistDriver`) with an in-memory fallback so a cache outage never
4
4
  * takes the whole app down.
5
5
  *
6
- * Policy (fail-open on reads):
6
+ * Policy (fail-closed on reads, unless `failOpen`):
7
7
  * - `add()` — records the revocation in BOTH, always. The fallback is this
8
8
  * instance's own record of what it has revoked, not a log of its
9
9
  * outages: writing only on failure meant a token revoked while
@@ -12,11 +12,23 @@
12
12
  * through. A primary failure still does not fail the logout.
13
13
  * - `has()` — asks the fallback FIRST: what this instance revoked is known
14
14
  * locally and needs no round trip. Otherwise it asks the
15
- * primary, and if that throws, allows the token through
16
- * (fail-open). Access tokens are short-lived, so the window a
17
- * revocation missed by BOTH survives is bounded by the token TTL
18
- * — the blacklist is defense-in-depth above expiry, not the
19
- * primary boundary.
15
+ * primary, and if that throws, rethrows: the guard asking treats
16
+ * it as a crashed strategy (a 500, or a guest under silent auth),
17
+ * never as "not revoked".
18
+ *
19
+ * Answering "not revoked" (fail-open) assumed every consumer was
20
+ * a short-lived access token. The same blacklist backs a session
21
+ * guard's logout under the cookie store, listed for twice the
22
+ * session lifetime, and JWTs issued for days: during an outage
23
+ * every sign-in revoked by ANOTHER instance, or before this
24
+ * process started, was accepted again. Answering "revoked"
25
+ * instead would not do either: a session guard forgets a revoked
26
+ * sign-in, so an outage would log every user out for good.
27
+ *
28
+ * `failOpen: true` restores the old answer for a deployment whose
29
+ * only consumer is a JWT guard with a short `expiresIn`, where
30
+ * availability through an outage is worth more than a revocation
31
+ * missed for at most one token lifetime.
20
32
  *
21
33
  * Every degradation invokes `onDegrade`. The default reports the first failure
22
34
  * per operation and then a periodic count: an outage that logs on every request
@@ -36,6 +48,11 @@ export interface BlacklistDegradeEvent {
36
48
  export interface ResilientBlacklistConfig {
37
49
  /** Invoked whenever the primary driver fails and the fallback is used. */
38
50
  onDegrade?: (event: BlacklistDegradeEvent) => void;
51
+ /**
52
+ * Let a credential through when the primary cannot answer and this instance
53
+ * never revoked it. Off by default: see the policy above for what it costs.
54
+ */
55
+ failOpen?: boolean;
39
56
  }
40
57
 
41
58
  /** How long a repeat of the same failing operation stays folded into a count. */
@@ -74,6 +91,7 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
74
91
  readonly #primary: BlacklistDriver;
75
92
  readonly #fallback: BlacklistDriver;
76
93
  readonly #onDegrade: (event: BlacklistDegradeEvent) => void;
94
+ readonly #failOpen: boolean;
77
95
 
78
96
  constructor(
79
97
  primary: BlacklistDriver,
@@ -83,13 +101,15 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
83
101
  this.#primary = primary;
84
102
  this.#fallback = fallback;
85
103
  this.#onDegrade = config.onDegrade ?? makeDefaultOnDegrade();
104
+ this.#failOpen = config.failOpen === true;
86
105
  }
87
106
 
88
107
  async add(jti: string, expiresAt: number): Promise<void> {
89
108
  // The fallback first, and unconditionally: it is what this instance
90
109
  // knows it revoked. Recording only on failure left every revocation made
91
110
  // while the primary was healthy invisible to the fallback — and those are
92
- // most of them.
111
+ // most of them. The default fallback sweeps expired entries on write,
112
+ // so recording every revocation keeps only the live ones.
93
113
  await this.#fallback.add(jti, expiresAt);
94
114
  try {
95
115
  await this.#primary.add(jti, expiresAt);
@@ -108,8 +128,9 @@ export class ResilientBlacklistDriver implements BlacklistDriver {
108
128
  return await this.#primary.has(jti);
109
129
  } catch (error) {
110
130
  this.#onDegrade({ op: "has", error });
111
- // Fail-open on what neither knows: access tokens are short-lived.
112
- return false;
131
+ // Neither store can say the credential was not revoked.
132
+ if (this.#failOpen) return false;
133
+ throw error;
113
134
  }
114
135
  }
115
136
 
@@ -16,12 +16,34 @@ export interface BlacklistDriver {
16
16
  cleanup?(): Promise<void>;
17
17
  }
18
18
 
19
- /** In-memory blacklist for development. */
19
+ /** In-memory blacklist for development, and the resilient driver's fallback. */
20
20
  export class MemoryBlacklistDriver implements BlacklistDriver {
21
21
  #entries: Map<string, number> = new Map();
22
22
 
23
+ /**
24
+ * Size at which the next sweep runs, doubling each time.
25
+ *
26
+ * Expired entries used to leave only on a `has()` of that exact jti or an
27
+ * explicit `cleanup()`, which nothing calls. Every logout and every
28
+ * `revoke()` added one, and `ResilientBlacklistDriver` writes every
29
+ * revocation into this store, so a long-lived process grew without bound.
30
+ * Sweeping on write bounds the map by the revocations still live, without
31
+ * a timer that would hold the event loop open. There is no ceiling that
32
+ * evicts: dropping a live entry would un-revoke a token.
33
+ */
34
+ #sweepAt = 64;
35
+
36
+ /** Entries currently held, live or not yet swept. */
37
+ get size(): number {
38
+ return this.#entries.size;
39
+ }
40
+
23
41
  async add(jti: string, expiresAt: number): Promise<void> {
42
+ // Already past its deadline: `has()` would answer false for it anyway,
43
+ // so storing it only costs memory.
44
+ if (expiresAt < Date.now()) return;
24
45
  this.#entries.set(jti, expiresAt);
46
+ if (this.#entries.size > this.#sweepAt) this.#sweep();
25
47
  }
26
48
 
27
49
  async has(jti: string): Promise<boolean> {
@@ -35,10 +57,15 @@ export class MemoryBlacklistDriver implements BlacklistDriver {
35
57
  }
36
58
 
37
59
  async cleanup(): Promise<void> {
60
+ this.#sweep();
61
+ }
62
+
63
+ #sweep(): void {
38
64
  const now = Date.now();
39
65
  for (const [jti, exp] of this.#entries) {
40
66
  if (exp < now) this.#entries.delete(jti);
41
67
  }
68
+ this.#sweepAt = Math.max(64, this.#entries.size * 2);
42
69
  }
43
70
  }
44
71
 
@@ -10,6 +10,7 @@ import { clearAuth, getAuth, setAuth } from "./services/main.js";
10
10
  import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
11
11
  import { JwtStrategy } from "./strategies/JwtStrategy.js";
12
12
  import { SessionStrategy } from "./strategies/SessionStrategy.js";
13
+ import { installBouncerTemplateTags } from "./templateTags.js";
13
14
 
14
15
  interface WardenContainer {
15
16
  singleton(token: unknown, factory: () => unknown): void;
@@ -23,6 +24,8 @@ interface WardenConfigStore {
23
24
  export interface WardenAppContext {
24
25
  container: WardenContainer;
25
26
  config: WardenConfigStore;
27
+ /** Set by the template engine's provider constructor (`InkerProvider`). */
28
+ usingInker?: boolean;
26
29
  }
27
30
 
28
31
  export default class WardenProvider {
@@ -184,90 +187,10 @@ export default class WardenProvider {
184
187
 
185
188
  /**
186
189
  * Publish `@can` / `@cannot` to the template engine, as AdonisJS's bouncer
187
- * does. A migrated template keeps `@can('PostPolicy.edit', post) … @endcan`
188
- * unchanged.
189
- *
190
- * Both are BLOCK tags and both AWAIT — the check returns a promise — so they
191
- * render on the async path and raise on a synchronous one, matching upstream
192
- * (which emits `await bouncer.can(...)`). The checks themselves come from
193
- * `ctx.bouncer.templateHelpers`, shared into the view per request.
194
- *
195
- * Resolved through the container: warden must not depend on the engine, and
196
- * an app with no template layer simply skips this.
190
+ * does — through the engine package's module singleton, guarded by
191
+ * `usingInker` (see `installBouncerTemplateTags`).
197
192
  */
198
193
  async #registerTemplateTags(): Promise<void> {
199
- const engine = await this.#resolveTemplateEngine();
200
- if (engine === undefined) return;
201
- for (const tagName of ["can", "cannot"] as const) {
202
- engine.registerTag({
203
- tagName,
204
- block: true,
205
- seekable: true,
206
- async compile(_parser, buffer, token) {
207
- // The shared bag lives in the render scope under `bouncer`.
208
- const bouncer = token.evaluate(
209
- "typeof bouncer === 'undefined' ? undefined : bouncer",
210
- );
211
- const check = Reflect.get(Object(bouncer), tagName);
212
- if (typeof check !== "function") {
213
- // No bouncer on this request: deny rather than render an
214
- // unguarded body.
215
- return;
216
- }
217
- const args = token.evaluate(`[${token.properties.jsArg}]`);
218
- const allowed = await check.apply(
219
- bouncer,
220
- Array.isArray(args) ? args : [],
221
- );
222
- if (allowed === true) buffer.writeRaw(await token.renderBody());
223
- },
224
- });
225
- }
194
+ await installBouncerTemplateTags(this.app.usingInker === true);
226
195
  }
227
-
228
- /** The template engine, if the host installed one. */
229
- async #resolveTemplateEngine(): Promise<TemplateEngineLike | undefined> {
230
- for (const token of ["inker", "view"]) {
231
- try {
232
- const binding: unknown = await this.app.container.resolve(token);
233
- for (const candidate of [
234
- binding,
235
- Reflect.get(Object(binding), "_templates"),
236
- ]) {
237
- if (
238
- typeof candidate === "object" &&
239
- candidate !== null &&
240
- typeof Reflect.get(candidate, "registerTag") === "function"
241
- ) {
242
- return {
243
- registerTag: Reflect.get(candidate, "registerTag").bind(
244
- candidate,
245
- ),
246
- };
247
- }
248
- }
249
- } catch {
250
- // A host without a template layer is not an error.
251
- }
252
- }
253
- return undefined;
254
- }
255
- }
256
-
257
- /** The only surface warden needs of a template engine. */
258
- interface TemplateEngineLike {
259
- registerTag(tag: {
260
- tagName: string;
261
- block: boolean;
262
- seekable: boolean;
263
- compile(
264
- parser: unknown,
265
- buffer: { writeRaw(text: string): void },
266
- token: {
267
- properties: { jsArg: string };
268
- renderBody(): string | Promise<string>;
269
- evaluate(expression: string): unknown;
270
- },
271
- ): void | Promise<void>;
272
- }): void;
273
196
  }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Timing-safe credential lookup — the counterpart of the upstream
3
+ * `withAuthFinder` mixin's `verifyCredentials`, without the ORM.
4
+ *
5
+ * Why it exists: a login that returns early for an unknown account answers in
6
+ * microseconds, and one that verifies a password hash for a known account
7
+ * answers in ~100 ms. That difference alone lets an anonymous caller list the
8
+ * registered emails, with no rate limit to bypass. The counter-measure is to pay
9
+ * one hash for an unknown uid too, and to fail every case with the same error.
10
+ *
11
+ * Upstream mixes the methods into a Lucid model; warden knows no ORM, so the
12
+ * lookup is passed in (`findForAuth`) and the methods come back as plain
13
+ * functions, bound, ready to hand to a guard:
14
+ *
15
+ * ```ts
16
+ * const users = authFinder({ hash, findForAuth: (email) => User.findBy('email', email) })
17
+ * jwtGuard({ secret, findUser, verifyCredentials: users.verifyCredentials })
18
+ * ```
19
+ */
20
+
21
+ import { E_INVALID_CREDENTIALS } from "./errors.js";
22
+
23
+ /** What `authFinder` hashes with — `make` and `verify`, AdonisJS argument order. */
24
+ export interface AuthFinderHasher {
25
+ make(value: string): Promise<string>;
26
+ verify(hashedValue: string, plainValue: string): Promise<boolean>;
27
+ }
28
+
29
+ export interface AuthFinderOptions<User extends object> {
30
+ /** The hasher the passwords were made with (a sigil `Hash`, for one). */
31
+ hash: AuthFinderHasher;
32
+ /**
33
+ * Find the user a sign-in names — by email, username, whatever the uid is.
34
+ * `null` or `undefined` for none.
35
+ */
36
+ findForAuth: (uid: string) => Promise<User | null | undefined>;
37
+ /** The property the password hash lives under. Default `password`. */
38
+ passwordColumnName?: string;
39
+ }
40
+
41
+ export interface AuthFinder<User extends object> {
42
+ /**
43
+ * Find the user by `uid` and verify `password`. Safe from timing attacks:
44
+ * an unknown uid pays the same one hash a known one does. Every failure
45
+ * throws {@link E_INVALID_CREDENTIALS}.
46
+ */
47
+ verifyCredentials(uid: string, password: string): Promise<User>;
48
+ /** Whether `password` matches `user`'s stored hash. */
49
+ verifyPassword(user: User, password: string): Promise<boolean>;
50
+ }
51
+
52
+ export function authFinder<User extends object>(
53
+ options: AuthFinderOptions<User>,
54
+ ): AuthFinder<User> {
55
+ const { hash, findForAuth } = options;
56
+ const column = options.passwordColumnName ?? "password";
57
+
58
+ const storedHash = (user: User): string | undefined => {
59
+ const value: unknown = Reflect.get(user, column);
60
+ return typeof value === "string" && value.length > 0 ? value : undefined;
61
+ };
62
+
63
+ const verifyPassword = async (
64
+ user: User,
65
+ password: string,
66
+ ): Promise<boolean> => {
67
+ const hashed = storedHash(user);
68
+ if (hashed === undefined) {
69
+ // NAMED DEVIATION — upstream throws a RuntimeException (a 500) for
70
+ // a row without a hash. An account that signs in elsewhere (SSO)
71
+ // has none, and a distinct 500 for it would tell a caller the
72
+ // account exists. It is a password that does not match, and it
73
+ // pays the hash a match would have cost.
74
+ await hash.make(password);
75
+ return false;
76
+ }
77
+ return hash.verify(hashed, password);
78
+ };
79
+
80
+ const verifyCredentials = async (
81
+ uid: string,
82
+ password: string,
83
+ ): Promise<User> => {
84
+ if (!uid || !password) throw new E_INVALID_CREDENTIALS();
85
+ const user = await findForAuth(uid);
86
+ if (user === null || user === undefined) {
87
+ // The hash a known uid would cost, paid for nothing: without it the
88
+ // response time says whether the account exists.
89
+ await hash.make(password);
90
+ throw new E_INVALID_CREDENTIALS();
91
+ }
92
+ if (await verifyPassword(user, password)) return user;
93
+ throw new E_INVALID_CREDENTIALS();
94
+ };
95
+
96
+ return { verifyCredentials, verifyPassword };
97
+ }
98
+
99
+ /**
100
+ * A guard's `verifyCredentials` answers a wrong credential with `null`; one
101
+ * built on {@link authFinder} throws {@link E_INVALID_CREDENTIALS} instead, as
102
+ * upstream's does. Both mean the same rejection, so a guard reads them alike.
103
+ *
104
+ * NAMED DEVIATION — upstream's user provider swallows EVERY error into `null`,
105
+ * so a database outage reads as a wrong password. Only E_INVALID_CREDENTIALS
106
+ * is a rejection here; anything else propagates and the auth manager reports it
107
+ * as the strategy crash it is.
108
+ */
109
+ export async function rejectedAsNull<User>(
110
+ verification: Promise<User | null>,
111
+ ): Promise<User | null> {
112
+ try {
113
+ return await verification;
114
+ } catch (error) {
115
+ if (error instanceof E_INVALID_CREDENTIALS) return null;
116
+ throw error;
117
+ }
118
+ }
package/src/bearer.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Read the token out of an `Authorization: Bearer <token>` header.
3
+ *
4
+ * The scheme is matched case-insensitively (RFC 7235: auth-schemes are
5
+ * case-insensitive), so `bearer` and `BEARER` are the same credential, as
6
+ * `Basic` already was. Split on the first spaces like the reference guard:
7
+ * the scheme, then the token; a header with no token is no credential.
8
+ *
9
+ * @returns The token, or `""` when the header carries no bearer credential.
10
+ */
11
+ export function readBearerToken(header: unknown): string {
12
+ if (typeof header !== "string") return "";
13
+ const [type, token] = header.split(" ");
14
+ if (type?.toLowerCase() !== "bearer" || !token) return "";
15
+ return token;
16
+ }
@@ -5,7 +5,7 @@
5
5
  * 2026-06-01): standalone abilities via `Bouncer.ability`, class-based policies
6
6
  * via `with(Policy)`, the four verbs `allows`/`denies`/`authorize`/`execute`,
7
7
  * and guest-denied-by-default. The user is `UserPayload | null` (guest = null,
8
- * D3); `authorize` throws `AUTHORIZATION_FAILURE` carrying `status: 403`
8
+ * D3); `authorize` throws `E_AUTHORIZATION_FAILURE` carrying `status: 403`
9
9
  * (D2). 56.2 ships PURE mechanics — it does NOT consult the Layer-1
10
10
  * `RightsResolver` (D4); abilities/policy methods receive `(user, ...args)` and
11
11
  * the developer writes the predicate, exactly as Adonis does.
@@ -13,7 +13,10 @@
13
13
 
14
14
  import type { UserPayload } from "../AuthManager.js";
15
15
  import { WardenError } from "../errors.js";
16
- import type { RightsResolver } from "../rights/RightsResolver.js";
16
+ import {
17
+ narrowToAccessToken,
18
+ type RightsResolver,
19
+ } from "../rights/RightsResolver.js";
17
20
  import type { EffectivePermissions, Scope } from "../rights/types.js";
18
21
  import { AbilitiesBuilder } from "./AbilitiesBuilder.js";
19
22
  import { AuthorizationResponse } from "./AuthorizationResponse.js";
@@ -133,9 +136,14 @@ export class Bouncer {
133
136
  #resolvePermissions(): Promise<EffectivePermissions> {
134
137
  if (this.#resolved === undefined) {
135
138
  const user = this.#getUser();
139
+ // Narrowed by the request's access token, exactly as the coarse
140
+ // `hasPermission` is: a token minted for `orders:read` must not pass
141
+ // a policy that asks `this.permissions.has('orders:delete')`.
136
142
  this.#resolved =
137
143
  this.#resolver !== undefined && user !== null
138
- ? this.#resolver.resolve(user, this.#scope)
144
+ ? this.#resolver
145
+ .resolve(user, this.#scope)
146
+ .then((effective) => narrowToAccessToken(effective, user))
139
147
  : Promise.resolve(emptyPermissions(this.#scope));
140
148
  }
141
149
  return this.#resolved;
@@ -321,7 +329,7 @@ export class Bouncer {
321
329
  return !(await this.#evaluateAbility(ability, args)).authorized;
322
330
  }
323
331
 
324
- /** Resolves on allow; throws `AUTHORIZATION_FAILURE` on deny (D2). */
332
+ /** Resolves on allow; throws `E_AUTHORIZATION_FAILURE` on deny (D2). */
325
333
  authorize<Args extends unknown[]>(
326
334
  ability: Ability<Args>,
327
335
  ...args: Args
@@ -357,7 +365,12 @@ export class Bouncer {
357
365
  }
358
366
 
359
367
  #resolveAbility(name: string): Ability<never[]> {
360
- const found = this.#abilities[name];
368
+ // Own keys only: the registry is a plain object, and a name never
369
+ // registered ("constructor", "toString") must not resolve to an
370
+ // Object.prototype member and fail as a TypeError.
371
+ const found = Object.hasOwn(this.#abilities, name)
372
+ ? this.#abilities[name]
373
+ : undefined;
361
374
  if (found === undefined) {
362
375
  throw new WardenError(
363
376
  "UNKNOWN_ABILITY",
@@ -373,7 +386,9 @@ export class Bouncer {
373
386
  // name surfaces as a promise rejection (like every other verb error),
374
387
  // not a synchronous throw at `with()` time.
375
388
  return () => {
376
- const ctor = this.#policies[name];
389
+ const ctor = Object.hasOwn(this.#policies, name)
390
+ ? this.#policies[name]
391
+ : undefined;
377
392
  if (ctor === undefined) {
378
393
  throw new WardenError(
379
394
  "UNKNOWN_POLICY",