@c9up/warden 0.2.4 → 0.2.6

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 (103) hide show
  1. package/README.md +70 -3
  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 +26 -12
  9. package/dist/AttemptStore.js.map +1 -1
  10. package/dist/AuthManager.d.ts +33 -2
  11. package/dist/AuthManager.d.ts.map +1 -1
  12. package/dist/AuthManager.js +23 -2
  13. package/dist/AuthManager.js.map +1 -1
  14. package/dist/Authenticator.d.ts +19 -1
  15. package/dist/Authenticator.d.ts.map +1 -1
  16. package/dist/Authenticator.js +37 -3
  17. package/dist/Authenticator.js.map +1 -1
  18. package/dist/Guard.d.ts.map +1 -1
  19. package/dist/Guard.js +17 -5
  20. package/dist/Guard.js.map +1 -1
  21. package/dist/ResilientBlacklistDriver.d.ts +23 -6
  22. package/dist/ResilientBlacklistDriver.d.ts.map +1 -1
  23. package/dist/ResilientBlacklistDriver.js +24 -8
  24. package/dist/ResilientBlacklistDriver.js.map +1 -1
  25. package/dist/WardenProvider.d.ts +2 -0
  26. package/dist/WardenProvider.d.ts.map +1 -1
  27. package/dist/WardenProvider.js +4 -58
  28. package/dist/WardenProvider.js.map +1 -1
  29. package/dist/config.d.ts +8 -4
  30. package/dist/config.d.ts.map +1 -1
  31. package/dist/config.js +4 -1
  32. package/dist/config.js.map +1 -1
  33. package/dist/index.d.ts +4 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +2 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/mfa/MfaManager.d.ts +16 -4
  38. package/dist/mfa/MfaManager.d.ts.map +1 -1
  39. package/dist/mfa/MfaManager.js +32 -6
  40. package/dist/mfa/MfaManager.js.map +1 -1
  41. package/dist/middleware.d.ts.map +1 -1
  42. package/dist/middleware.js +27 -5
  43. package/dist/middleware.js.map +1 -1
  44. package/dist/native.d.ts +6 -2
  45. package/dist/native.d.ts.map +1 -1
  46. package/dist/native.js +19 -2
  47. package/dist/native.js.map +1 -1
  48. package/dist/quasar.d.ts.map +1 -1
  49. package/dist/quasar.js +8 -1
  50. package/dist/quasar.js.map +1 -1
  51. package/dist/standalone.d.ts +24 -3
  52. package/dist/standalone.d.ts.map +1 -1
  53. package/dist/standalone.js +21 -29
  54. package/dist/standalone.js.map +1 -1
  55. package/dist/strategies/ApiKeyStrategy.d.ts +45 -12
  56. package/dist/strategies/ApiKeyStrategy.d.ts.map +1 -1
  57. package/dist/strategies/ApiKeyStrategy.js +71 -37
  58. package/dist/strategies/ApiKeyStrategy.js.map +1 -1
  59. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  60. package/dist/strategies/JwtStrategy.js +3 -3
  61. package/dist/strategies/JwtStrategy.js.map +1 -1
  62. package/dist/strategies/SessionStrategy.d.ts +48 -1
  63. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  64. package/dist/strategies/SessionStrategy.js +70 -4
  65. package/dist/strategies/SessionStrategy.js.map +1 -1
  66. package/dist/templateTags.d.ts +42 -0
  67. package/dist/templateTags.d.ts.map +1 -0
  68. package/dist/templateTags.js +82 -0
  69. package/dist/templateTags.js.map +1 -0
  70. package/dist/vendor/nativeBinary.d.ts +26 -2
  71. package/dist/vendor/nativeBinary.d.ts.map +1 -1
  72. package/dist/vendor/nativeBinary.js +63 -6
  73. package/dist/vendor/nativeBinary.js.map +1 -1
  74. package/dist/vendor/quasarConnection.d.ts +26 -3
  75. package/dist/vendor/quasarConnection.d.ts.map +1 -1
  76. package/dist/vendor/quasarConnection.js +44 -23
  77. package/dist/vendor/quasarConnection.js.map +1 -1
  78. package/index.darwin-arm64.node +0 -0
  79. package/index.darwin-x64.node +0 -0
  80. package/index.linux-arm64-gnu.node +0 -0
  81. package/index.linux-x64-gnu.node +0 -0
  82. package/index.win32-x64-msvc.node +0 -0
  83. package/package.json +8 -3
  84. package/src/AccessToken.ts +550 -0
  85. package/src/AttemptStore.ts +29 -13
  86. package/src/AuthManager.ts +40 -2
  87. package/src/Authenticator.ts +39 -3
  88. package/src/Guard.ts +18 -5
  89. package/src/ResilientBlacklistDriver.ts +28 -8
  90. package/src/WardenProvider.ts +6 -83
  91. package/src/config.ts +8 -4
  92. package/src/index.ts +18 -0
  93. package/src/mfa/MfaManager.ts +39 -6
  94. package/src/middleware.ts +36 -5
  95. package/src/native.ts +20 -4
  96. package/src/quasar.ts +13 -2
  97. package/src/standalone.ts +74 -33
  98. package/src/strategies/ApiKeyStrategy.ts +112 -42
  99. package/src/strategies/JwtStrategy.ts +3 -1
  100. package/src/strategies/SessionStrategy.ts +121 -4
  101. package/src/templateTags.ts +117 -0
  102. package/src/vendor/nativeBinary.ts +82 -6
  103. package/src/vendor/quasarConnection.ts +84 -22
@@ -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
+ }
@@ -13,7 +13,10 @@
13
13
 
14
14
  /** A window of attempts counted under one key. */
15
15
  export interface AttemptCount {
16
- /** Attempts in the current window, this one included. */
16
+ /**
17
+ * Attempts in the current window, this one included. `Infinity` when the
18
+ * store could not count the attempt at all, which refuses it.
19
+ */
17
20
  count: number;
18
21
  /** Seconds until the window ends and the count starts over. */
19
22
  resetSeconds: number;
@@ -34,7 +37,18 @@ export interface AttemptStore {
34
37
  /** Most keys the memory store holds before it makes room. */
35
38
  const DEFAULT_MAX_KEYS = 100_000;
36
39
 
37
- /** In this process's memory, bounded. Not shared across instances. */
40
+ /**
41
+ * In this process's memory, bounded. Not shared across instances.
42
+ *
43
+ * When the bound is reached and every window is still live, a NEW key is
44
+ * refused — its attempt reported as over any limit — rather than a live window
45
+ * evicted to make room. Evicting forgave the oldest counters, and the keys are
46
+ * attacker-chosen (`id:<identifier>`): a flood of made-up identifiers erased a
47
+ * victim's lockout, and the attacker's own, and the guessing resumed. Refusing
48
+ * keeps every lockout in place; what it costs during such a flood is that
49
+ * first attempts under new keys wait until windows expire. A deployment that
50
+ * cannot accept that uses {@link RedisAttemptStore}, which has no such bound.
51
+ */
38
52
  export class MemoryAttemptStore implements AttemptStore {
39
53
  readonly #entries = new Map<string, { count: number; resetAt: number }>();
40
54
  readonly #maxKeys: number;
@@ -48,7 +62,10 @@ export class MemoryAttemptStore implements AttemptStore {
48
62
  let entry = this.#entries.get(key);
49
63
  if (entry === undefined || entry.resetAt <= now) {
50
64
  this.#entries.delete(key);
51
- this.#makeRoom(now);
65
+ const wait = this.#makeRoom(now);
66
+ if (wait !== undefined) {
67
+ return { count: Number.POSITIVE_INFINITY, resetSeconds: wait };
68
+ }
52
69
  entry = { count: 0, resetAt: now + windowSeconds * 1000 };
53
70
  this.#entries.set(key, entry);
54
71
  }
@@ -74,20 +91,19 @@ export class MemoryAttemptStore implements AttemptStore {
74
91
  }
75
92
 
76
93
  /**
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.
94
+ * Make room for one more key by dropping the expired windows. A live window
95
+ * is never dropped: that would forgive its attempts. Returns `undefined`
96
+ * when there is room, else the seconds until the earliest live window ends.
81
97
  */
82
- #makeRoom(now: number): void {
83
- if (this.#entries.size < this.#maxKeys) return;
98
+ #makeRoom(now: number): number | undefined {
99
+ if (this.#entries.size < this.#maxKeys) return undefined;
100
+ let earliest = Number.POSITIVE_INFINITY;
84
101
  for (const [key, entry] of this.#entries) {
85
102
  if (entry.resetAt <= now) this.#entries.delete(key);
103
+ else earliest = Math.min(earliest, entry.resetAt);
86
104
  }
87
- for (const key of this.#entries.keys()) {
88
- if (this.#entries.size < this.#maxKeys) break;
89
- this.#entries.delete(key);
90
- }
105
+ if (this.#entries.size < this.#maxKeys) return undefined;
106
+ return Math.max(1, Math.ceil((earliest - now) / 1000));
91
107
  }
92
108
  }
93
109
 
@@ -16,10 +16,43 @@ import type {
16
16
  SessionStore,
17
17
  } from "./strategies/SessionStrategy.js";
18
18
 
19
+ /**
20
+ * The token a request authenticated with, when it authenticated with one: an
21
+ * access token, or an OAuth token from a guard such as visa's. Its abilities
22
+ * are what the TOKEN may do, a separate axis from `UserPayload.permissions`
23
+ * (what the USER may do): a request may act only where both agree.
24
+ */
25
+ export interface CurrentAccessToken {
26
+ readonly abilities: readonly string[];
27
+ /** Whether the token may do `ability` (`*` grants every ability). */
28
+ allows(ability: string): boolean;
29
+ denies(ability: string): boolean;
30
+ /** Throw unless the token may do `ability`. */
31
+ authorize(ability: string): void;
32
+ }
33
+
34
+ /**
35
+ * Whether the token the user authenticated with, if any, allows `permission`.
36
+ *
37
+ * A permission check on a request made with a token is an INTERSECTION: the
38
+ * user must hold the permission AND the token must allow it. The token never
39
+ * widens what the user may do (a same-named ability grants nothing the user
40
+ * lacks), and it narrows it: a token limited to a few abilities does not carry
41
+ * every permission of its user. A user with no `currentAccessToken` (a session,
42
+ * a JWT) is not restricted here.
43
+ */
44
+ export function tokenAllows(user: UserPayload, permission: string): boolean {
45
+ const token = user.currentAccessToken;
46
+ return token === undefined || token.allows(permission);
47
+ }
48
+
19
49
  export interface UserPayload {
20
50
  id: string;
21
51
  roles?: string[];
52
+ /** The user's own permissions. Never widened by a token's abilities. */
22
53
  permissions?: string[];
54
+ /** Set by a token guard: the token this request authenticated with. */
55
+ currentAccessToken?: CurrentAccessToken;
23
56
  [key: string]: unknown;
24
57
  }
25
58
 
@@ -335,25 +368,30 @@ export class AuthManager {
335
368
  /**
336
369
  * Check if a user has a specific permission within a scope (default
337
370
  * `"global"`). Derived from roles + store grants ONLY — token
338
- * `user.permissions` is NOT read (D1, cerebrum 459).
371
+ * `user.permissions` is NOT read (D1, cerebrum 459). When the user came in
372
+ * with a token (`currentAccessToken`), the token must allow it too: see
373
+ * {@link tokenAllows}.
339
374
  */
340
375
  async hasPermission(
341
376
  user: UserPayload,
342
377
  permission: string,
343
378
  scope: Scope = "global",
344
379
  ): Promise<boolean> {
380
+ if (!tokenAllows(user, permission)) return false;
345
381
  return (await this.resolvePermissions(user, scope)).has(permission);
346
382
  }
347
383
 
348
384
  /**
349
385
  * Check if a user has ALL required permissions within a scope (default
350
- * `"global"`). Empty list ⇒ vacuously true.
386
+ * `"global"`). Empty list ⇒ vacuously true. Intersected with the token's
387
+ * abilities like {@link hasPermission}.
351
388
  */
352
389
  async hasAllPermissions(
353
390
  user: UserPayload,
354
391
  permissions: string[],
355
392
  scope: Scope = "global",
356
393
  ): Promise<boolean> {
394
+ if (!permissions.every((p) => tokenAllows(user, p))) return false;
357
395
  return (await this.resolvePermissions(user, scope)).hasAll(permissions);
358
396
  }
359
397