@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
@@ -145,7 +145,7 @@ export class PolicyAuthorizer {
145
145
  return !(await this.execute(action, ...args)).authorized;
146
146
  }
147
147
 
148
- /** Resolves on allow; throws `AUTHORIZATION_FAILURE` on deny (D2). */
148
+ /** Resolves on allow; throws `E_AUTHORIZATION_FAILURE` on deny (D2). */
149
149
  async authorize(action: string, ...args: unknown[]): Promise<void> {
150
150
  const response = await this.execute(action, ...args);
151
151
  if (!response.authorized) {
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { UserPayload } from "../AuthManager.js";
12
- import { WardenError } from "../errors.js";
12
+ import { E_AUTHORIZATION_FAILURE } from "../errors.js";
13
13
  import { AuthorizationResponse } from "./AuthorizationResponse.js";
14
14
  import type { AuthorizerResponse, HookResponse } from "./types.js";
15
15
 
@@ -56,18 +56,15 @@ export function isAction(value: unknown): value is Action {
56
56
  return typeof value === "function";
57
57
  }
58
58
 
59
- /** Throw the canonical authorization failure for a denied response (D2). */
59
+ /**
60
+ * Throw the canonical authorization failure for a denied response (D2) —
61
+ * `E_AUTHORIZATION_FAILURE`, carrying the response so its status, message and
62
+ * translation reach whoever handles the error.
63
+ */
60
64
  export function throwAuthorizationFailure(
61
65
  response: AuthorizationResponse,
62
66
  ): never {
63
- throw new WardenError(
64
- "AUTHORIZATION_FAILURE",
65
- response.message ?? "Authorization failed",
66
- {
67
- hint: "The current user is not authorized for this action.",
68
- status: response.status ?? 403,
69
- },
70
- );
67
+ throw new E_AUTHORIZATION_FAILURE(response);
71
68
  }
72
69
 
73
70
  /** Run the D5 evaluation pipeline and resolve to the final response. */
package/src/config.ts CHANGED
@@ -86,7 +86,10 @@ export function sessionGuard(config: SessionStrategyConfig): GuardFactory {
86
86
  return new SessionStrategy(config);
87
87
  }
88
88
 
89
- /** Build an API-key / access-tokens guard from its config. */
89
+ /**
90
+ * Build an access-tokens guard from its config (AdonisJS `tokensGuard()`
91
+ * shape): `apiKeyGuard({ tokens: new AccessTokensProvider({ store }), findUser })`.
92
+ */
90
93
  export function apiKeyGuard(config: ApiKeyConfig): GuardFactory {
91
94
  return new ApiKeyStrategy(config);
92
95
  }
@@ -126,9 +129,10 @@ export interface WardenConfig {
126
129
  */
127
130
  session?: SessionStrategyConfig;
128
131
  /**
129
- * API-key strategy configuration. Supply `findByKey` so `@Guard('api-key')`
130
- * routes resolve the user (and scopes) from the request header. Without this,
131
- * the `api-key` strategy is unregistered and `@Guard('api-key')` throws.
132
+ * Access-tokens strategy configuration: a `tokens` provider (hashed,
133
+ * prefixed, expiring tokens with abilities) and `findUser`. Registered as
134
+ * `access_tokens` and `api-key`; without it, `@Guard('access_tokens')`
135
+ * throws.
132
136
  */
133
137
  apiKey?: ApiKeyConfig;
134
138
  /**
package/src/errors.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { AuthorizationResponse } from "./bouncer/AuthorizationResponse.js";
2
+
1
3
  /**
2
4
  * WardenError — structured error for Warden auth.
3
5
  */
@@ -23,8 +25,9 @@ export class WardenError extends Error {
23
25
  // alone would mean three different things across the ecosystem and an
24
26
  // application could not tell them apart.
25
27
  //
26
- // The AdonisJS auth identifiers (`E_UNAUTHORIZED_ACCESS`,
27
- // `E_INVALID_CREDENTIALS`) are PRESERVED verbatim — they already start
28
+ // The AdonisJS identifiers (`E_UNAUTHORIZED_ACCESS`,
29
+ // `E_INVALID_CREDENTIALS`, bouncer's `E_AUTHORIZATION_FAILURE`) are
30
+ // PRESERVED verbatim — they already start
28
31
  // with `E_` and fall through untouched — so a consumer branching on
29
32
  // `error.code === 'E_UNAUTHORIZED_ACCESS'` sees the same string it
30
33
  // would under `@adonisjs/auth`.
@@ -79,3 +82,78 @@ export class E_INVALID_CREDENTIALS extends WardenError {
79
82
  super("E_INVALID_CREDENTIALS", message, { status: 400 });
80
83
  }
81
84
  }
85
+
86
+ /**
87
+ * The slice of an i18n service {@link E_AUTHORIZATION_FAILURE} translates
88
+ * through: `ctx.i18n.t(identifier, data, { defaultValue })`, the shape of the
89
+ * ecosystem's i18n package. Structural, so warden imports none.
90
+ */
91
+ interface Translator {
92
+ t(
93
+ identifier: string,
94
+ data?: Record<string, unknown>,
95
+ options?: { defaultValue?: string },
96
+ ): string;
97
+ }
98
+
99
+ function translatorOf(ctx: unknown): Translator | undefined {
100
+ const i18n: unknown =
101
+ typeof ctx === "object" && ctx !== null
102
+ ? Reflect.get(ctx, "i18n")
103
+ : undefined;
104
+ if (typeof i18n !== "object" || i18n === null) return undefined;
105
+ const t: unknown = Reflect.get(i18n, "t");
106
+ if (typeof t !== "function") return undefined;
107
+ return {
108
+ t: (identifier, data, options) => {
109
+ const translated: unknown = t.call(i18n, identifier, data, options);
110
+ return typeof translated === "string"
111
+ ? translated
112
+ : (options?.defaultValue ?? identifier);
113
+ },
114
+ };
115
+ }
116
+
117
+ /**
118
+ * `E_AUTHORIZATION_FAILURE` — thrown by a denied `authorize()` (AdonisJS
119
+ * `@adonisjs/bouncer` parity: same class name, same `code`, same
120
+ * `identifier`). Carries the {@link AuthorizationResponse} it was thrown for,
121
+ * so a handler reads the denial's `status`, `message` and `translation`.
122
+ *
123
+ * NAMED DEVIATION — upstream's class fields override what the constructor
124
+ * passed, so its `error.message` is always "Access denied" and `error.status`
125
+ * always 403; only its own `handle()` reads the response. Here `message` and
126
+ * `status` ARE the response's (falling back to "Access denied" / 403), because
127
+ * warden ships no renderer: the host's exception handler renders the error from
128
+ * those two fields, and a `deny('Not found', 404)` must reach it as a 404.
129
+ */
130
+ export class E_AUTHORIZATION_FAILURE extends WardenError {
131
+ /** The i18n key looked up when the response sets no translation. */
132
+ readonly identifier = "errors.E_AUTHORIZATION_FAILURE";
133
+ /** The denial this error was thrown for. */
134
+ readonly response: AuthorizationResponse;
135
+
136
+ constructor(response: AuthorizationResponse) {
137
+ super("E_AUTHORIZATION_FAILURE", response.message || "Access denied", {
138
+ hint: "The current user is not authorized for this action.",
139
+ status: response.status || 403,
140
+ });
141
+ this.name = "E_AUTHORIZATION_FAILURE";
142
+ this.response = response;
143
+ }
144
+
145
+ /**
146
+ * The message to send for this denial (AdonisJS `getResponseMessage`): the
147
+ * response's translation when the context carries an i18n service, its
148
+ * message otherwise. The translation falls back to the static identifier,
149
+ * then to the message when the catalog has neither.
150
+ */
151
+ getResponseMessage(ctx: unknown): string {
152
+ const message = this.response.message || this.message;
153
+ const translator = translatorOf(ctx);
154
+ if (translator === undefined) return message;
155
+ const identifier = this.response.translation?.identifier || this.identifier;
156
+ const data = this.response.translation?.data || {};
157
+ return translator.t(identifier, data, { defaultValue: message });
158
+ }
159
+ }
package/src/index.ts CHANGED
@@ -6,6 +6,22 @@
6
6
 
7
7
  import "./augmentations.js";
8
8
 
9
+ export type {
10
+ AccessTokenAttributes,
11
+ AccessTokenStore,
12
+ AccessTokensProviderContract,
13
+ AccessTokensProviderOptions,
14
+ CreateAccessTokenOptions,
15
+ StoredAccessToken,
16
+ TokenOwner,
17
+ } from "./AccessToken.js";
18
+ export {
19
+ AccessToken,
20
+ AccessTokensProvider,
21
+ crc32,
22
+ MemoryAccessTokenStore,
23
+ } from "./AccessToken.js";
24
+
9
25
  export type {
10
26
  AttemptCount,
11
27
  AttemptRedisClient,
@@ -24,11 +40,13 @@ export type {
24
40
  AuthConfig,
25
41
  AuthResult,
26
42
  AuthStrategy,
43
+ CurrentAccessToken,
27
44
  UserPayload,
28
45
  } from "./AuthManager.js";
29
46
  export {
30
47
  AuthManager,
31
48
  authEventPrefix,
49
+ tokenAllows,
32
50
  type WardenEmitter,
33
51
  } from "./AuthManager.js";
34
52
  export type {
@@ -36,6 +54,12 @@ export type {
36
54
  AuthRateLimiterConfig,
37
55
  } from "./AuthRateLimiter.js";
38
56
  export { AuthRateLimiter } from "./AuthRateLimiter.js";
57
+ export type {
58
+ AuthFinder,
59
+ AuthFinderHasher,
60
+ AuthFinderOptions,
61
+ } from "./authFinder.js";
62
+ export { authFinder } from "./authFinder.js";
39
63
  export { AbilitiesBuilder } from "./bouncer/AbilitiesBuilder.js";
40
64
  export { AuthorizationResponse } from "./bouncer/AuthorizationResponse.js";
41
65
  export { BasePolicy } from "./bouncer/BasePolicy.js";
@@ -69,6 +93,7 @@ export { configure } from "./configure.js";
69
93
  export type { TokenDuration } from "./duration.js";
70
94
  export { parseDurationSeconds } from "./duration.js";
71
95
  export {
96
+ E_AUTHORIZATION_FAILURE,
72
97
  E_INVALID_CREDENTIALS,
73
98
  E_UNAUTHORIZED_ACCESS,
74
99
  WardenError,
@@ -134,6 +159,7 @@ export type {
134
159
  export {
135
160
  MemoryWebauthnChallengeStore,
136
161
  MemoryWebauthnCredentialStore,
162
+ WebauthnCredentialExistsError,
137
163
  WebauthnProvider,
138
164
  } from "./mfa/WebauthnProvider.js";
139
165
  export { quasarConnection } from "./quasar.js";
@@ -143,12 +169,15 @@ export type {
143
169
  } from "./RedisBlacklistDriver.js";
144
170
  export { RedisBlacklistDriver } from "./RedisBlacklistDriver.js";
145
171
  export type {
172
+ MintedRefreshToken,
146
173
  RefreshTokenDriver,
147
174
  StoredRefreshToken,
148
175
  } from "./RefreshTokenStore.js";
149
176
  export {
150
177
  generateRefreshToken,
178
+ hashRefreshToken,
151
179
  MemoryRefreshTokenDriver,
180
+ mintRefreshToken,
152
181
  } from "./RefreshTokenStore.js";
153
182
  export {
154
183
  DEFAULT_SECRET_LENGTH,
@@ -106,7 +106,11 @@ export interface MfaManagerConfig {
106
106
  totp?: TotpProvider;
107
107
  backupCodes?: BackupCodesProvider;
108
108
  store?: MfaFactorStore;
109
- /** Per-user brute-force protection on `verify()`. Defaults to 5 / 15 min. */
109
+ /**
110
+ * Per-user brute-force protection on `verify()`, `verifyTotp()`,
111
+ * `verifyBackupCode()` and `confirmTotp()`, one shared count. Defaults to
112
+ * 5 / 15 min.
113
+ */
110
114
  rateLimit?: MfaRateLimitConfig;
111
115
  }
112
116
 
@@ -157,10 +161,26 @@ export class MfaManager {
157
161
  return { factorId: factor.id, secret, uri };
158
162
  }
159
163
 
160
- /** Confirm a pending TOTP factor by verifying a first code. */
161
- async confirmTotp(factorId: string, code: string): Promise<boolean> {
164
+ /**
165
+ * Confirm a pending TOTP factor of `userId` by verifying a first code.
166
+ *
167
+ * Takes the owner beside the factor id and refuses a factor that belongs
168
+ * to someone else: a factor id is something an application passes through
169
+ * a request, and one leaked through a log or a support tool must not let
170
+ * another account act on it. The attempt counts against the same lockout
171
+ * as {@link verify}, so the first code cannot be guessed without limit.
172
+ */
173
+ async confirmTotp(
174
+ userId: string,
175
+ factorId: string,
176
+ code: string,
177
+ ): Promise<boolean> {
162
178
  const totp = this.#requireTotp();
163
- const factor = await this.#store.findById(factorId);
179
+ const key = lockoutKey(userId);
180
+ if (!(await this.#limiter.attempt(key)).allowed) {
181
+ return false;
182
+ }
183
+ const factor = await this.#ownedFactor(userId, factorId);
164
184
  if (factor?.kind !== "totp" || !factor.secret) {
165
185
  return false;
166
186
  }
@@ -168,12 +188,27 @@ export class MfaManager {
168
188
  return false;
169
189
  }
170
190
  await this.#store.save({ ...factor, confirmedAt: Date.now() });
191
+ await this.#limiter.clear(key);
171
192
  return true;
172
193
  }
173
194
 
174
- /** Verify a TOTP code against the user's confirmed authenticator factors. */
195
+ /**
196
+ * Verify a TOTP code against the user's confirmed authenticator factors.
197
+ *
198
+ * Counts against the same per-user lockout as {@link verify}: an app
199
+ * calling this directly (to tell the factors apart in its UI) must not get
200
+ * unlimited guesses at a six-digit code.
201
+ */
175
202
  async verifyTotp(userId: string, code: string): Promise<boolean> {
176
203
  const totp = this.#requireTotp();
204
+ return this.#limited(userId, () => this.#checkTotp(totp, userId, code));
205
+ }
206
+
207
+ async #checkTotp(
208
+ totp: TotpProvider,
209
+ userId: string,
210
+ code: string,
211
+ ): Promise<boolean> {
177
212
  const factors = await this.#store.findByUser(userId);
178
213
  // Sequential, not Promise.all: the replay guard must see one accepted
179
214
  // code at a time, and stopping at the first match avoids burning the
@@ -220,9 +255,22 @@ export class MfaManager {
220
255
  return codes;
221
256
  }
222
257
 
223
- /** Verify and consume one backup code for the user. */
258
+ /**
259
+ * Verify and consume one backup code for the user. Counts against the same
260
+ * per-user lockout as {@link verify}.
261
+ */
224
262
  async verifyBackupCode(userId: string, code: string): Promise<boolean> {
225
263
  const provider = this.#requireBackupCodes();
264
+ return this.#limited(userId, () =>
265
+ this.#checkBackupCode(provider, userId, code),
266
+ );
267
+ }
268
+
269
+ async #checkBackupCode(
270
+ provider: BackupCodesProvider,
271
+ userId: string,
272
+ code: string,
273
+ ): Promise<boolean> {
226
274
  const factors = await this.#store.findByUser(userId);
227
275
  for (const factor of factors) {
228
276
  if (factor.kind !== "backup_codes" || !factor.backupHashes) {
@@ -248,28 +296,40 @@ export class MfaManager {
248
296
  * factors first, then falls back to consuming a backup code.
249
297
  */
250
298
  async verify(userId: string, code: string): Promise<boolean> {
251
- // Counted BEFORE the code is checked, by one atomic increment: reading
252
- // "not locked" first and counting the failure after let a burst of
253
- // concurrent attempts all reach the providers.
299
+ // One attempt for the code, whichever factor ends up answering it.
300
+ return this.#limited(userId, async () => {
301
+ const totp = this.#totp;
302
+ if (totp && (await this.#checkTotp(totp, userId, code))) return true;
303
+ const backupCodes = this.#backupCodes;
304
+ return (
305
+ backupCodes !== undefined &&
306
+ (await this.#checkBackupCode(backupCodes, userId, code))
307
+ );
308
+ });
309
+ }
310
+
311
+ /**
312
+ * Run one code check under the per-user lockout.
313
+ *
314
+ * Counted BEFORE the code is checked, by one atomic increment: reading
315
+ * "not locked" first and counting the failure after let a burst of
316
+ * concurrent attempts all reach the providers. A success clears the count.
317
+ */
318
+ async #limited(
319
+ userId: string,
320
+ check: () => Promise<boolean>,
321
+ ): Promise<boolean> {
254
322
  const key = lockoutKey(userId);
255
323
  if (!(await this.#limiter.attempt(key)).allowed) {
256
324
  return false;
257
325
  }
258
- let ok = false;
259
- if (this.#totp && (await this.verifyTotp(userId, code))) {
260
- ok = true;
261
- } else if (
262
- this.#backupCodes &&
263
- (await this.verifyBackupCode(userId, code))
264
- ) {
265
- ok = true;
266
- }
326
+ const ok = await check();
267
327
  if (ok) await this.#limiter.clear(key);
268
328
  return ok;
269
329
  }
270
330
 
271
331
  /**
272
- * Whether the user is currently locked out of `verify()` after too many
332
+ * Whether the user is currently locked out of the code checks after too many
273
333
  * failed attempts. Use it to surface a "try again later" message.
274
334
  */
275
335
  isLocked(userId: string): Promise<boolean> {
@@ -293,9 +353,25 @@ export class MfaManager {
293
353
  return factors.some((f) => f.confirmedAt !== undefined);
294
354
  }
295
355
 
296
- /** Remove a factor (e.g. the user disables their authenticator). */
297
- async disableFactor(factorId: string): Promise<void> {
298
- await this.#store.delete(factorId);
356
+ /**
357
+ * Remove one of `userId`'s factors (e.g. the user disables their
358
+ * authenticator). Answers whether a factor was removed: `false` for an
359
+ * unknown id or one owned by another user, which is left in place.
360
+ */
361
+ async disableFactor(userId: string, factorId: string): Promise<boolean> {
362
+ const factor = await this.#ownedFactor(userId, factorId);
363
+ if (factor === null) return false;
364
+ await this.#store.delete(factor.id);
365
+ return true;
366
+ }
367
+
368
+ /** The factor, only when it belongs to `userId`. */
369
+ async #ownedFactor(
370
+ userId: string,
371
+ factorId: string,
372
+ ): Promise<MfaFactor | null> {
373
+ const factor = await this.#store.findById(factorId);
374
+ return factor !== null && factor.userId === userId ? factor : null;
299
375
  }
300
376
 
301
377
  #requireTotp(): TotpProvider {
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
11
11
  import { WardenError } from "../errors.js";
12
+ import { hasEnded } from "../vendor/quasarConnection.js";
12
13
  import { base32Decode, base32Encode } from "./base32.js";
13
14
 
14
15
  export type TotpAlgorithm = "SHA1" | "SHA256" | "SHA512";
@@ -124,6 +125,13 @@ export class RedisTotpReplayGuard implements TotpReplayGuard {
124
125
  }
125
126
 
126
127
  async claim(key: string, ttlMs: number): Promise<boolean> {
128
+ // Resolved again once the client has ended for good: quasar retires
129
+ // a connection whose retry strategy gave up and hands out a fresh one,
130
+ // and keeping the dead client refused every code until restart. A
131
+ // client handed in directly is kept whatever its state.
132
+ if (typeof this.#source === "function" && hasEnded(this.#resolved)) {
133
+ this.#resolved = undefined;
134
+ }
127
135
  if (this.#resolved === undefined) {
128
136
  this.#resolved =
129
137
  typeof this.#source === "function"
@@ -149,8 +157,13 @@ export interface TotpEnrollment {
149
157
  uri: string;
150
158
  }
151
159
 
152
- const DEFAULTS = {
153
- algorithm: "SHA1" as TotpAlgorithm,
160
+ const DEFAULTS: {
161
+ algorithm: TotpAlgorithm;
162
+ digits: number;
163
+ period: number;
164
+ window: number;
165
+ } = {
166
+ algorithm: "SHA1",
154
167
  digits: 6,
155
168
  period: 30,
156
169
  window: 1,
@@ -117,6 +117,24 @@ export interface WebauthnChallengeStore {
117
117
  take(state: string): Promise<WebauthnCeremony | null>;
118
118
  }
119
119
 
120
+ /**
121
+ * Thrown by `WebauthnCredentialStore.save` when the credential id is already
122
+ * registered. `finishRegistration` turns it into `{ verified: false }`; any
123
+ * other error from the store is an outage and propagates.
124
+ */
125
+ export class WebauthnCredentialExistsError extends WardenError {
126
+ constructor(credentialId: string) {
127
+ super(
128
+ "E_WARDEN_WEBAUTHN_CREDENTIAL_EXISTS",
129
+ `The WebAuthn credential "${credentialId}" is already registered.`,
130
+ {
131
+ hint: "A credential id belongs to the account that registered it first. Keep it unique in the store (INSERT, never upsert).",
132
+ },
133
+ );
134
+ this.name = "WebauthnCredentialExistsError";
135
+ }
136
+ }
137
+
120
138
  /** A registered passkey, persisted between ceremonies. */
121
139
  export interface StoredPasskey {
122
140
  /** Base64URL credential id. */
@@ -131,6 +149,19 @@ export interface StoredPasskey {
131
149
  }
132
150
 
133
151
  export interface WebauthnCredentialStore {
152
+ /**
153
+ * Persist a NEW passkey. This is an INSERT, never an upsert.
154
+ *
155
+ * The credential id comes from authenticator data the client chose
156
+ * (attestation is `none`), and a victim's ids are listed to anyone who
157
+ * starts an authentication ceremony for them. A store that replaced an
158
+ * existing row let an attacker register their own key under the victim's
159
+ * id and take the passkey over. `finishRegistration` checks `findById`
160
+ * first; the store closes the race between that check and this write: a
161
+ * persistent store keeps `id` unique (primary key / unique index, Redis
162
+ * `SET … NX`) and throws `WebauthnCredentialExistsError` when the id is
163
+ * already taken, so a concurrent registration of the same id fails.
164
+ */
134
165
  save(passkey: StoredPasskey): Promise<void>;
135
166
  findById(id: string): Promise<StoredPasskey | null>;
136
167
  findByUser(userId: string): Promise<StoredPasskey[]>;
@@ -277,6 +308,11 @@ export class MemoryWebauthnChallengeStore implements WebauthnChallengeStore {
277
308
  export class MemoryWebauthnCredentialStore implements WebauthnCredentialStore {
278
309
  #store = new Map<string, StoredPasskey>();
279
310
  async save(passkey: StoredPasskey): Promise<void> {
311
+ // Check and write with no `await` between them: atomic on a
312
+ // single-threaded runtime, so two registrations of one id cannot both land.
313
+ if (this.#store.has(passkey.id)) {
314
+ throw new WebauthnCredentialExistsError(passkey.id);
315
+ }
280
316
  this.#store.set(passkey.id, passkey);
281
317
  }
282
318
  async findById(id: string): Promise<StoredPasskey | null> {
@@ -494,14 +530,31 @@ export class WebauthnProvider {
494
530
  if (parsed === null || !this.#algorithms.includes(parsed.alg)) {
495
531
  return { verified: false };
496
532
  }
497
- await this.#credentials.save({
498
- id: bufferToBase64url(parsed.credentialId),
499
- userId,
500
- publicKey: bufferToBase64url(parsed.publicKeyBytes),
501
- alg: parsed.alg,
502
- counter: parsed.signCount,
503
- transports: response.response.transports,
504
- });
533
+ // WebAuthn L2 7.1 step 22: a credential id already registered, for ANY
534
+ // user, fails the ceremony. The id is client-chosen; replacing the row
535
+ // handed the victim's passkey to whoever sent it, and re-registering
536
+ // one's own id reset the counter that betrays a cloned authenticator.
537
+ const id = bufferToBase64url(parsed.credentialId);
538
+ if ((await this.#credentials.findById(id)) !== null) {
539
+ return { verified: false };
540
+ }
541
+ try {
542
+ await this.#credentials.save({
543
+ id,
544
+ userId,
545
+ publicKey: bufferToBase64url(parsed.publicKeyBytes),
546
+ alg: parsed.alg,
547
+ counter: parsed.signCount,
548
+ transports: response.response.transports,
549
+ });
550
+ } catch (error) {
551
+ // A concurrent registration took the id between the check and the
552
+ // insert. Any other store failure is infrastructure and propagates.
553
+ if (error instanceof WebauthnCredentialExistsError) {
554
+ return { verified: false };
555
+ }
556
+ throw error;
557
+ }
505
558
  return { verified: true };
506
559
  }
507
560
 
@@ -640,17 +693,28 @@ export class WebauthnProvider {
640
693
  expectedType: "webauthn.create" | "webauthn.get",
641
694
  expectedChallenge: string,
642
695
  ): boolean {
643
- let parsed: { type?: string; challenge?: string; origin?: string };
696
+ let parsed: unknown;
644
697
  try {
645
698
  parsed = JSON.parse(base64urlToBuffer(clientDataB64).toString("utf8"));
646
699
  } catch {
647
700
  return false;
648
701
  }
702
+ // Attacker-supplied: `null`, an array or a scalar parse fine and are not
703
+ // client data. Reading a field off `null` threw a TypeError that escaped
704
+ // the ceremony as a 500 instead of a plain refusal.
705
+ if (
706
+ typeof parsed !== "object" ||
707
+ parsed === null ||
708
+ Array.isArray(parsed)
709
+ ) {
710
+ return false;
711
+ }
712
+ const origin: unknown = Reflect.get(parsed, "origin");
649
713
  return (
650
- parsed.type === expectedType &&
651
- parsed.challenge === expectedChallenge &&
652
- typeof parsed.origin === "string" &&
653
- this.#origins.includes(parsed.origin)
714
+ Reflect.get(parsed, "type") === expectedType &&
715
+ Reflect.get(parsed, "challenge") === expectedChallenge &&
716
+ typeof origin === "string" &&
717
+ this.#origins.includes(origin)
654
718
  );
655
719
  }
656
720