@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
@@ -0,0 +1,550 @@
1
+ /**
2
+ * Access tokens — opaque, revocable bearer tokens an application issues to its
3
+ * own users (API keys, personal access tokens, mobile app tokens).
4
+ *
5
+ * Modelled on `@adonisjs/auth`'s access-tokens guard (`AccessToken` +
6
+ * `DbAccessTokensProvider`), so an app moving over keeps its token format:
7
+ *
8
+ * value = prefix + base64url(identifier) + "." + base64url(secret)
9
+ * secret = random(tokenSecretLength) + crc32(random) in decimal
10
+ * stored = sha256(secret), never the secret itself
11
+ *
12
+ * What makes it safe, all taken from upstream:
13
+ *
14
+ * 1. **Only a hash is stored.** A dump of the tokens table hands out no
15
+ * working token: the secret exists only in the hands of whoever received
16
+ * the value when it was minted.
17
+ * 2. **The comparison is constant-time**, so a timing side channel cannot
18
+ * forge a secret one byte at a time.
19
+ * 3. **The value is recognisable.** The `oat_` prefix and the CRC32 suffix let
20
+ * secret scanners (GitHub's, a pre-commit hook) flag a leaked token.
21
+ * 4. **Abilities, expiry and last use travel with the token**, and the guard
22
+ * hands the token to the request as `user.currentAccessToken`, where a
23
+ * handler checks `allows()` / `authorize()`.
24
+ *
25
+ * Two places go further than upstream, both named where they happen: the row
26
+ * identifier is random rather than a database counter, and neither verifying
27
+ * nor invalidating touches a row before its secret has been checked.
28
+ *
29
+ * Warden owns no database: rows go through an {@link AccessTokenStore} the
30
+ * application implements over its own table. {@link MemoryAccessTokenStore}
31
+ * serves tests and single-process tools.
32
+ */
33
+
34
+ import { createHash, randomBytes } from "node:crypto";
35
+ import { resolveExpiresInSeconds, type TokenDuration } from "./duration.js";
36
+ import { E_UNAUTHORIZED_ACCESS, WardenError } from "./errors.js";
37
+ import {
38
+ decodeTokenValue,
39
+ encodeTokenValue,
40
+ safeCompareHashes,
41
+ } from "./RememberMeToken.js";
42
+ import { Secret } from "./Secret.js";
43
+
44
+ /** The polynomial of CRC-32 (IEEE 802.3), reflected. */
45
+ const CRC32_POLYNOMIAL = 0xedb88320;
46
+
47
+ const CRC32_TABLE: readonly number[] = Array.from({ length: 256 }, (_, n) => {
48
+ let c = n;
49
+ for (let k = 0; k < 8; k++) {
50
+ c = c & 1 ? CRC32_POLYNOMIAL ^ (c >>> 1) : c >>> 1;
51
+ }
52
+ return c >>> 0;
53
+ });
54
+
55
+ /**
56
+ * CRC-32 of a string's UTF-8 bytes, as an unsigned integer.
57
+ *
58
+ * Not a security measure — a checksum anyone can compute. It is there so a
59
+ * scanner can tell a real token from random text that happens to carry the
60
+ * prefix, which is what keeps leaked-token alerts precise.
61
+ */
62
+ export function crc32(input: string): number {
63
+ let crc = 0xffffffff;
64
+ for (const byte of new TextEncoder().encode(input)) {
65
+ crc = (CRC32_TABLE[(crc ^ byte) & 0xff] ?? 0) ^ (crc >>> 8);
66
+ }
67
+ return (crc ^ 0xffffffff) >>> 0;
68
+ }
69
+
70
+ /** `sha256(secret)` as hex — what gets stored. */
71
+ function hashOf(secret: string): string {
72
+ return createHash("sha256").update(secret).digest("hex");
73
+ }
74
+
75
+ /** A random URL-safe string of exactly `size` characters. */
76
+ function randomString(size: number): string {
77
+ return randomBytes(size).toString("base64url").slice(0, size);
78
+ }
79
+
80
+ /** Attributes an {@link AccessToken} is built from. */
81
+ export interface AccessTokenAttributes {
82
+ /** Unique id of the row; the public half of the token value. */
83
+ identifier: string;
84
+ /** Whose token this is. */
85
+ tokenableId: string | number;
86
+ /** The kind of token, so one table can hold several (`auth_token`). */
87
+ type: string;
88
+ /** A label the user recognises it by ("CI deploy key"), if any. */
89
+ name: string | null;
90
+ /** `sha256(secret)`, hex. */
91
+ hash: string;
92
+ /** What the token may do. Absent means everything (`["*"]`). */
93
+ abilities?: string[];
94
+ createdAt: Date;
95
+ updatedAt: Date;
96
+ lastUsedAt: Date | null;
97
+ /** `null` for a token that never expires. */
98
+ expiresAt: Date | null;
99
+ /** Required with `secret`: the prefix the value starts with. */
100
+ prefix?: string;
101
+ /** The secret, only on a token just minted; it builds {@link AccessToken.value}. */
102
+ secret?: Secret<string>;
103
+ }
104
+
105
+ /**
106
+ * One access token. Hands out `value` only right after it was minted, because
107
+ * nothing stored can rebuild it.
108
+ */
109
+ export class AccessToken {
110
+ /**
111
+ * Split a token value into its identifier and secret, or `null` for
112
+ * anything that is not one of ours — a missing prefix, a malformed body.
113
+ * A bad token is an ordinary event, not an exception.
114
+ */
115
+ static decode(
116
+ prefix: string,
117
+ value: unknown,
118
+ ): { identifier: string; secret: Secret<string> } | null {
119
+ if (typeof value !== "string" || !value.startsWith(prefix)) return null;
120
+ const decoded = decodeTokenValue(value.slice(prefix.length));
121
+ if (!decoded) return null;
122
+ return {
123
+ identifier: decoded.identifier,
124
+ secret: new Secret(decoded.secret),
125
+ };
126
+ }
127
+
128
+ /** A fresh secret, checksummed, and the hash to store for it. */
129
+ static seed(size: number): { secret: Secret<string>; hash: string } {
130
+ const seed = randomString(size);
131
+ const secret = `${seed}${crc32(seed)}`;
132
+ return { secret: new Secret(secret), hash: hashOf(secret) };
133
+ }
134
+
135
+ /**
136
+ * Everything the persistence layer needs for a new token, without deciding
137
+ * how it is stored. `expiresIn` is in SECONDS; absent, the token never
138
+ * expires.
139
+ */
140
+ static createTransientToken(
141
+ userId: string | number,
142
+ size: number,
143
+ expiresIn?: number,
144
+ ): {
145
+ userId: string | number;
146
+ expiresAt: Date | undefined;
147
+ secret: Secret<string>;
148
+ hash: string;
149
+ } {
150
+ const expiresAt =
151
+ expiresIn === undefined
152
+ ? undefined
153
+ : new Date(Date.now() + expiresIn * 1000);
154
+ return { userId, expiresAt, ...AccessToken.seed(size) };
155
+ }
156
+
157
+ readonly identifier: string;
158
+ readonly tokenableId: string | number;
159
+ readonly type: string;
160
+ readonly name: string | null;
161
+ readonly hash: string;
162
+ readonly abilities: string[];
163
+ readonly createdAt: Date;
164
+ readonly updatedAt: Date;
165
+ readonly lastUsedAt: Date | null;
166
+ readonly expiresAt: Date | null;
167
+ /** The public token value — only on a token just minted. */
168
+ readonly value?: Secret<string>;
169
+
170
+ constructor(attributes: AccessTokenAttributes) {
171
+ this.identifier = attributes.identifier;
172
+ this.tokenableId = attributes.tokenableId;
173
+ this.type = attributes.type;
174
+ this.name = attributes.name;
175
+ this.hash = attributes.hash;
176
+ this.abilities = [...(attributes.abilities ?? ["*"])];
177
+ this.createdAt = attributes.createdAt;
178
+ this.updatedAt = attributes.updatedAt;
179
+ this.lastUsedAt = attributes.lastUsedAt;
180
+ this.expiresAt = attributes.expiresAt;
181
+ if (attributes.secret) {
182
+ if (attributes.prefix === undefined) {
183
+ throw new WardenError(
184
+ "INVALID_CONFIG",
185
+ "Cannot compute the token value without its prefix.",
186
+ );
187
+ }
188
+ this.value = new Secret(
189
+ `${attributes.prefix}${encodeTokenValue(
190
+ attributes.identifier,
191
+ attributes.secret.release(),
192
+ )}`,
193
+ );
194
+ }
195
+ }
196
+
197
+ /** Whether the token may do `ability`. `*` means every ability. */
198
+ allows(ability: string): boolean {
199
+ return this.abilities.includes(ability) || this.abilities.includes("*");
200
+ }
201
+
202
+ /** The negation of {@link allows}. */
203
+ denies(ability: string): boolean {
204
+ return !this.allows(ability);
205
+ }
206
+
207
+ /** Throw `E_UNAUTHORIZED_ACCESS` unless the token may do `ability`. */
208
+ authorize(ability: string): void {
209
+ if (this.denies(ability)) {
210
+ throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
211
+ guardDriverName: "access_tokens",
212
+ });
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Whether the token is past its expiry. A token with none never expires; an
218
+ * expiry that is not a valid date counts as past, never as "no expiry".
219
+ */
220
+ isExpired(): boolean {
221
+ if (this.expiresAt === null) return false;
222
+ return !(this.expiresAt.getTime() > Date.now());
223
+ }
224
+
225
+ /** Constant-time check of a presented secret against the stored hash. */
226
+ verify(secret: Secret<string>): boolean {
227
+ return safeCompareHashes(this.hash, hashOf(secret.release()));
228
+ }
229
+
230
+ /** What a client receives. `token` is present only on a token just minted. */
231
+ toJSON(): {
232
+ type: "bearer";
233
+ name: string | null;
234
+ token: string | undefined;
235
+ abilities: string[];
236
+ lastUsedAt: Date | null;
237
+ expiresAt: Date | null;
238
+ } {
239
+ return {
240
+ type: "bearer",
241
+ name: this.name,
242
+ token: this.value?.release(),
243
+ abilities: this.abilities,
244
+ lastUsedAt: this.lastUsedAt,
245
+ expiresAt: this.expiresAt,
246
+ };
247
+ }
248
+ }
249
+
250
+ /** A token as persisted. The secret is NOT here — only its hash. */
251
+ export interface StoredAccessToken {
252
+ identifier: string;
253
+ tokenableId: string | number;
254
+ type: string;
255
+ name: string | null;
256
+ /** `sha256(secret)`, hex. */
257
+ hash: string;
258
+ abilities: string[];
259
+ /** Epoch milliseconds, like every timestamp below. */
260
+ createdAt: number;
261
+ updatedAt: number;
262
+ lastUsedAt: number | null;
263
+ expiresAt: number | null;
264
+ }
265
+
266
+ /** What a token table must offer. Structural: warden owns no database. */
267
+ export interface AccessTokenStore {
268
+ create(token: StoredAccessToken): Promise<void>;
269
+ find(identifier: string): Promise<StoredAccessToken | null>;
270
+ /** Record a use of the token. */
271
+ touch(identifier: string, lastUsedAt: number): Promise<void>;
272
+ /** Delete a row; answers whether one was there. */
273
+ delete(identifier: string): Promise<boolean>;
274
+ /** Every row of the user, whatever its type. */
275
+ listForUser(userId: string | number): Promise<StoredAccessToken[]>;
276
+ }
277
+
278
+ /** In-memory store — for tests and single-process tools. Not for a cluster. */
279
+ export class MemoryAccessTokenStore implements AccessTokenStore {
280
+ readonly #rows = new Map<string, StoredAccessToken>();
281
+
282
+ async create(token: StoredAccessToken): Promise<void> {
283
+ this.#rows.set(token.identifier, {
284
+ ...token,
285
+ abilities: [...token.abilities],
286
+ });
287
+ }
288
+
289
+ async find(identifier: string): Promise<StoredAccessToken | null> {
290
+ const row = this.#rows.get(identifier);
291
+ return row ? { ...row, abilities: [...row.abilities] } : null;
292
+ }
293
+
294
+ async touch(identifier: string, lastUsedAt: number): Promise<void> {
295
+ const row = this.#rows.get(identifier);
296
+ if (row) this.#rows.set(identifier, { ...row, lastUsedAt });
297
+ }
298
+
299
+ async delete(identifier: string): Promise<boolean> {
300
+ return this.#rows.delete(identifier);
301
+ }
302
+
303
+ async listForUser(userId: string | number): Promise<StoredAccessToken[]> {
304
+ return [...this.#rows.values()]
305
+ .filter((row) => String(row.tokenableId) === String(userId))
306
+ .map((row) => ({ ...row, abilities: [...row.abilities] }));
307
+ }
308
+ }
309
+
310
+ /** Whose token: anything carrying the user's id. */
311
+ export interface TokenOwner {
312
+ id: string | number;
313
+ }
314
+
315
+ /** Options of a single {@link AccessTokensProvider.create} call. */
316
+ export interface CreateAccessTokenOptions {
317
+ name?: string;
318
+ /** Seconds, or a duration string (`'30 days'`). Overrides the provider's. */
319
+ expiresIn?: TokenDuration;
320
+ }
321
+
322
+ /**
323
+ * What the access-tokens guard needs from a provider. {@link AccessTokensProvider}
324
+ * is the one shipped; an application with its own token scheme implements this
325
+ * and returns {@link AccessToken}s.
326
+ */
327
+ export interface AccessTokensProviderContract {
328
+ create(
329
+ user: TokenOwner,
330
+ abilities?: string[],
331
+ options?: CreateAccessTokenOptions,
332
+ ): Promise<AccessToken>;
333
+ /** The token behind a presented value, or `null` if it does not verify. */
334
+ verify(tokenValue: Secret<string>): Promise<AccessToken | null>;
335
+ /** Revoke the token behind a presented value; answers whether it existed. */
336
+ invalidate(tokenValue: Secret<string>): Promise<boolean>;
337
+ }
338
+
339
+ export interface AccessTokensProviderOptions {
340
+ /** Where the rows live. */
341
+ store: AccessTokenStore;
342
+ /** The value's prefix, for secret scanners. Default `oat_`. */
343
+ prefix?: string;
344
+ /** The row type, so one table can hold several kinds. Default `auth_token`. */
345
+ type?: string;
346
+ /**
347
+ * Characters of randomness in a secret. Default 40.
348
+ *
349
+ * NAMED DEVIATION — upstream takes any length; fewer than 32 is refused
350
+ * here, because a short secret is one an attacker can guess.
351
+ */
352
+ tokenSecretLength?: number;
353
+ /** Default lifetime: seconds or a duration string. Absent: never expires. */
354
+ expiresIn?: TokenDuration;
355
+ }
356
+
357
+ /** Fewer random characters than this and a secret becomes guessable. */
358
+ const MIN_SECRET_LENGTH = 32;
359
+
360
+ /**
361
+ * Mints, verifies, lists and revokes access tokens over an
362
+ * {@link AccessTokenStore}.
363
+ */
364
+ export class AccessTokensProvider implements AccessTokensProviderContract {
365
+ readonly prefix: string;
366
+ readonly type: string;
367
+ readonly tokenSecretLength: number;
368
+ readonly #store: AccessTokenStore;
369
+ readonly #expiresIn: TokenDuration | undefined;
370
+
371
+ constructor(options: AccessTokensProviderOptions) {
372
+ this.#store = options.store;
373
+ this.prefix = options.prefix ?? "oat_";
374
+ this.type = options.type ?? "auth_token";
375
+ this.tokenSecretLength = options.tokenSecretLength ?? 40;
376
+ this.#expiresIn = options.expiresIn;
377
+ if (this.prefix.length === 0 || this.prefix.includes(".")) {
378
+ // The value is split on its first dot after the prefix.
379
+ throw new WardenError(
380
+ "INVALID_CONFIG",
381
+ `The access-token prefix must be non-empty and carry no ".", got ${JSON.stringify(this.prefix)}`,
382
+ );
383
+ }
384
+ if (
385
+ !Number.isSafeInteger(this.tokenSecretLength) ||
386
+ this.tokenSecretLength < MIN_SECRET_LENGTH
387
+ ) {
388
+ throw new WardenError(
389
+ "INVALID_CONFIG",
390
+ `tokenSecretLength must be a whole number of at least ${MIN_SECRET_LENGTH}, got ${String(this.tokenSecretLength)}`,
391
+ );
392
+ }
393
+ // A lifetime that does not parse fails at boot, not at the first mint.
394
+ if (this.#expiresIn !== undefined) this.#lifetimeSeconds(this.#expiresIn);
395
+ }
396
+
397
+ #lifetimeSeconds(value: TokenDuration): number {
398
+ return resolveExpiresInSeconds(value, undefined, 0);
399
+ }
400
+
401
+ #toToken(row: StoredAccessToken): AccessToken {
402
+ return new AccessToken(this.#attributes(row));
403
+ }
404
+
405
+ #attributes(row: StoredAccessToken): AccessTokenAttributes {
406
+ return {
407
+ identifier: row.identifier,
408
+ tokenableId: row.tokenableId,
409
+ type: row.type,
410
+ name: row.name,
411
+ hash: row.hash,
412
+ abilities: row.abilities,
413
+ createdAt: new Date(row.createdAt),
414
+ updatedAt: new Date(row.updatedAt),
415
+ lastUsedAt: row.lastUsedAt === null ? null : new Date(row.lastUsedAt),
416
+ expiresAt: row.expiresAt === null ? null : new Date(row.expiresAt),
417
+ };
418
+ }
419
+
420
+ /** The row, only when it is of this provider's type and belongs to `user`. */
421
+ async #ownedRow(
422
+ user: TokenOwner,
423
+ identifier: string,
424
+ ): Promise<StoredAccessToken | null> {
425
+ const row = await this.#store.find(identifier);
426
+ if (row === null || row.type !== this.type) return null;
427
+ return String(row.tokenableId) === String(user.id) ? row : null;
428
+ }
429
+
430
+ /**
431
+ * Mint a token for `user`. The returned token is the only one that carries
432
+ * `value`: hand it to the client now, it cannot be read back later.
433
+ *
434
+ * NAMED DEVIATION — the identifier is 128 random bits, not the row's
435
+ * auto-increment id: a guessable identifier lets anyone enumerate rows and
436
+ * aim at a given user's token.
437
+ */
438
+ async create(
439
+ user: TokenOwner,
440
+ abilities: string[] = ["*"],
441
+ options: CreateAccessTokenOptions = {},
442
+ ): Promise<AccessToken> {
443
+ const expiresIn = options.expiresIn ?? this.#expiresIn;
444
+ const transient = AccessToken.createTransientToken(
445
+ user.id,
446
+ this.tokenSecretLength,
447
+ expiresIn === undefined ? undefined : this.#lifetimeSeconds(expiresIn),
448
+ );
449
+ const now = Date.now();
450
+ const row: StoredAccessToken = {
451
+ identifier: randomBytes(16).toString("hex"),
452
+ tokenableId: transient.userId,
453
+ type: this.type,
454
+ name: options.name ?? null,
455
+ hash: transient.hash,
456
+ abilities: [...abilities],
457
+ createdAt: now,
458
+ updatedAt: now,
459
+ lastUsedAt: null,
460
+ expiresAt: transient.expiresAt?.getTime() ?? null,
461
+ };
462
+ await this.#store.create(row);
463
+ return new AccessToken({
464
+ ...this.#attributes(row),
465
+ prefix: this.prefix,
466
+ secret: transient.secret,
467
+ });
468
+ }
469
+
470
+ /** One of `user`'s tokens by identifier, or `null`. */
471
+ async find(
472
+ user: TokenOwner,
473
+ identifier: string,
474
+ ): Promise<AccessToken | null> {
475
+ const row = await this.#ownedRow(user, identifier);
476
+ return row === null ? null : this.#toToken(row);
477
+ }
478
+
479
+ /** Delete one of `user`'s tokens; answers how many rows went (0 or 1). */
480
+ async delete(user: TokenOwner, identifier: string): Promise<number> {
481
+ const row = await this.#ownedRow(user, identifier);
482
+ if (row === null) return 0;
483
+ return (await this.#store.delete(row.identifier)) ? 1 : 0;
484
+ }
485
+
486
+ /** Delete every token of `user` of this provider's type. */
487
+ async deleteAll(user: TokenOwner): Promise<number> {
488
+ let deleted = 0;
489
+ for (const row of await this.#store.listForUser(user.id)) {
490
+ if (row.type !== this.type) continue;
491
+ if (await this.#store.delete(row.identifier)) deleted++;
492
+ }
493
+ return deleted;
494
+ }
495
+
496
+ /**
497
+ * Every token of `user` of this provider's type: most recently used first,
498
+ * never-used ones last, newest first among equals.
499
+ */
500
+ async all(user: TokenOwner): Promise<AccessToken[]> {
501
+ const rows = (await this.#store.listForUser(user.id)).filter(
502
+ (row) => row.type === this.type,
503
+ );
504
+ rows.sort(
505
+ (a, b) =>
506
+ (b.lastUsedAt ?? Number.NEGATIVE_INFINITY) -
507
+ (a.lastUsedAt ?? Number.NEGATIVE_INFINITY) ||
508
+ b.createdAt - a.createdAt,
509
+ );
510
+ return rows.map((row) => this.#toToken(row));
511
+ }
512
+
513
+ /**
514
+ * The token behind a presented value, or `null` for anything wrong: not one
515
+ * of ours, unknown, of another type, a secret that does not match, expired.
516
+ * The caller cannot tell these apart, which is deliberate.
517
+ *
518
+ * NAMED DEVIATION — upstream records the use before it compares the secret,
519
+ * so anyone who knows an identifier can move a token's "last used" date.
520
+ * Here only a verified token is touched.
521
+ */
522
+ async verify(tokenValue: Secret<string>): Promise<AccessToken | null> {
523
+ const decoded = AccessToken.decode(this.prefix, tokenValue.release());
524
+ if (!decoded) return null;
525
+ const row = await this.#store.find(decoded.identifier);
526
+ if (row === null || row.type !== this.type) return null;
527
+ const token = this.#toToken(row);
528
+ if (!token.verify(decoded.secret) || token.isExpired()) return null;
529
+ const now = Date.now();
530
+ await this.#store.touch(row.identifier, now);
531
+ return this.#toToken({ ...row, lastUsedAt: now });
532
+ }
533
+
534
+ /**
535
+ * Revoke the token behind a presented value. Answers whether one went.
536
+ *
537
+ * NAMED DEVIATION — upstream deletes from the identifier alone. Here the
538
+ * secret must match first: an identifier is not a credential, and without
539
+ * the check anyone who learned one (a log line, a token listing) could
540
+ * revoke someone else's token.
541
+ */
542
+ async invalidate(tokenValue: Secret<string>): Promise<boolean> {
543
+ const decoded = AccessToken.decode(this.prefix, tokenValue.release());
544
+ if (!decoded) return false;
545
+ const row = await this.#store.find(decoded.identifier);
546
+ if (row === null || row.type !== this.type) return false;
547
+ if (!this.#toToken(row).verify(decoded.secret)) return false;
548
+ return this.#store.delete(row.identifier);
549
+ }
550
+ }
@@ -11,9 +11,14 @@
11
11
  * so a lockout holds whichever instance the next attempt lands on.
12
12
  */
13
13
 
14
+ import { hasEnded } from "./vendor/quasarConnection.js";
15
+
14
16
  /** A window of attempts counted under one key. */
15
17
  export interface AttemptCount {
16
- /** Attempts in the current window, this one included. */
18
+ /**
19
+ * Attempts in the current window, this one included. `Infinity` when the
20
+ * store could not count the attempt at all, which refuses it.
21
+ */
17
22
  count: number;
18
23
  /** Seconds until the window ends and the count starts over. */
19
24
  resetSeconds: number;
@@ -34,7 +39,18 @@ export interface AttemptStore {
34
39
  /** Most keys the memory store holds before it makes room. */
35
40
  const DEFAULT_MAX_KEYS = 100_000;
36
41
 
37
- /** In this process's memory, bounded. Not shared across instances. */
42
+ /**
43
+ * In this process's memory, bounded. Not shared across instances.
44
+ *
45
+ * When the bound is reached and every window is still live, a NEW key is
46
+ * refused — its attempt reported as over any limit — rather than a live window
47
+ * evicted to make room. Evicting forgave the oldest counters, and the keys are
48
+ * attacker-chosen (`id:<identifier>`): a flood of made-up identifiers erased a
49
+ * victim's lockout, and the attacker's own, and the guessing resumed. Refusing
50
+ * keeps every lockout in place; what it costs during such a flood is that
51
+ * first attempts under new keys wait until windows expire. A deployment that
52
+ * cannot accept that uses {@link RedisAttemptStore}, which has no such bound.
53
+ */
38
54
  export class MemoryAttemptStore implements AttemptStore {
39
55
  readonly #entries = new Map<string, { count: number; resetAt: number }>();
40
56
  readonly #maxKeys: number;
@@ -48,7 +64,10 @@ export class MemoryAttemptStore implements AttemptStore {
48
64
  let entry = this.#entries.get(key);
49
65
  if (entry === undefined || entry.resetAt <= now) {
50
66
  this.#entries.delete(key);
51
- this.#makeRoom(now);
67
+ const wait = this.#makeRoom(now);
68
+ if (wait !== undefined) {
69
+ return { count: Number.POSITIVE_INFINITY, resetSeconds: wait };
70
+ }
52
71
  entry = { count: 0, resetAt: now + windowSeconds * 1000 };
53
72
  this.#entries.set(key, entry);
54
73
  }
@@ -74,20 +93,19 @@ export class MemoryAttemptStore implements AttemptStore {
74
93
  }
75
94
 
76
95
  /**
77
- * Keep the map under its bound: drop the expired windows, and if every
78
- * window is still live, the oldest ones — a Map iterates in insertion
79
- * order. Evicting a live window forgives its attempts; growing without
80
- * bound would take the process down instead.
96
+ * Make room for one more key by dropping the expired windows. A live window
97
+ * is never dropped: that would forgive its attempts. Returns `undefined`
98
+ * when there is room, else the seconds until the earliest live window ends.
81
99
  */
82
- #makeRoom(now: number): void {
83
- if (this.#entries.size < this.#maxKeys) return;
100
+ #makeRoom(now: number): number | undefined {
101
+ if (this.#entries.size < this.#maxKeys) return undefined;
102
+ let earliest = Number.POSITIVE_INFINITY;
84
103
  for (const [key, entry] of this.#entries) {
85
104
  if (entry.resetAt <= now) this.#entries.delete(key);
105
+ else earliest = Math.min(earliest, entry.resetAt);
86
106
  }
87
- for (const key of this.#entries.keys()) {
88
- if (this.#entries.size < this.#maxKeys) break;
89
- this.#entries.delete(key);
90
- }
107
+ if (this.#entries.size < this.#maxKeys) return undefined;
108
+ return Math.max(1, Math.ceil((earliest - now) / 1000));
91
109
  }
92
110
  }
93
111
 
@@ -119,7 +137,18 @@ export class RedisAttemptStore implements AttemptStore {
119
137
  this.#prefix = options.prefix ?? "warden:attempts";
120
138
  }
121
139
 
140
+ /**
141
+ * The client, resolved on first use and again once it has ended for good:
142
+ * quasar retires a connection whose retry strategy gave up and hands out a
143
+ * fresh one, and keeping the dead client failed every call with "Connection
144
+ * is closed." until restart. NAMED DEVIATION, better than upstream, whose
145
+ * Redis stores capture `ioConnection` once. A client handed in directly is
146
+ * kept whatever its state.
147
+ */
122
148
  async #client(): Promise<AttemptRedisClient> {
149
+ if (typeof this.#source === "function" && hasEnded(this.#resolved)) {
150
+ this.#resolved = undefined;
151
+ }
123
152
  if (this.#resolved) return this.#resolved;
124
153
  this.#resolved =
125
154
  typeof this.#source === "function" ? await this.#source() : this.#source;