@c9up/warden 0.2.3 → 0.2.5

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 (98) hide show
  1. package/README.md +5 -3
  2. package/dist/AttemptStore.d.ts +64 -0
  3. package/dist/AttemptStore.d.ts.map +1 -0
  4. package/dist/AttemptStore.js +117 -0
  5. package/dist/AttemptStore.js.map +1 -0
  6. package/dist/AuthManager.d.ts +5 -3
  7. package/dist/AuthManager.d.ts.map +1 -1
  8. package/dist/AuthManager.js +5 -4
  9. package/dist/AuthManager.js.map +1 -1
  10. package/dist/AuthRateLimiter.d.ts +44 -10
  11. package/dist/AuthRateLimiter.d.ts.map +1 -1
  12. package/dist/AuthRateLimiter.js +58 -73
  13. package/dist/AuthRateLimiter.js.map +1 -1
  14. package/dist/Authenticator.d.ts +8 -11
  15. package/dist/Authenticator.d.ts.map +1 -1
  16. package/dist/Authenticator.js +72 -9
  17. package/dist/Authenticator.js.map +1 -1
  18. package/dist/RememberMeToken.d.ts +15 -4
  19. package/dist/RememberMeToken.d.ts.map +1 -1
  20. package/dist/RememberMeToken.js +20 -7
  21. package/dist/RememberMeToken.js.map +1 -1
  22. package/dist/bouncer/evaluate.d.ts +0 -8
  23. package/dist/bouncer/evaluate.d.ts.map +1 -1
  24. package/dist/bouncer/evaluate.js +1 -1
  25. package/dist/bouncer/evaluate.js.map +1 -1
  26. package/dist/duration.d.ts.map +1 -1
  27. package/dist/duration.js +6 -0
  28. package/dist/duration.js.map +1 -1
  29. package/dist/errors.d.ts +6 -0
  30. package/dist/errors.d.ts.map +1 -1
  31. package/dist/errors.js +6 -0
  32. package/dist/errors.js.map +1 -1
  33. package/dist/index.d.ts +8 -6
  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/BackupCodesProvider.d.ts +8 -1
  38. package/dist/mfa/BackupCodesProvider.d.ts.map +1 -1
  39. package/dist/mfa/BackupCodesProvider.js +5 -7
  40. package/dist/mfa/BackupCodesProvider.js.map +1 -1
  41. package/dist/mfa/MfaManager.d.ts +18 -2
  42. package/dist/mfa/MfaManager.d.ts.map +1 -1
  43. package/dist/mfa/MfaManager.js +38 -35
  44. package/dist/mfa/MfaManager.js.map +1 -1
  45. package/dist/mfa/TotpProvider.d.ts +30 -6
  46. package/dist/mfa/TotpProvider.d.ts.map +1 -1
  47. package/dist/mfa/TotpProvider.js +48 -19
  48. package/dist/mfa/TotpProvider.js.map +1 -1
  49. package/dist/mfa/WebauthnProvider.d.ts.map +1 -1
  50. package/dist/mfa/WebauthnProvider.js +4 -1
  51. package/dist/mfa/WebauthnProvider.js.map +1 -1
  52. package/dist/middleware.d.ts +2 -0
  53. package/dist/middleware.d.ts.map +1 -1
  54. package/dist/middleware.js +3 -0
  55. package/dist/middleware.js.map +1 -1
  56. package/dist/native/generated.d.ts +0 -5
  57. package/dist/native/generated.d.ts.map +1 -1
  58. package/dist/native.d.ts +0 -2
  59. package/dist/native.d.ts.map +1 -1
  60. package/dist/native.js +0 -4
  61. package/dist/native.js.map +1 -1
  62. package/dist/strategies/JwtStrategy.d.ts +11 -1
  63. package/dist/strategies/JwtStrategy.d.ts.map +1 -1
  64. package/dist/strategies/JwtStrategy.js +9 -2
  65. package/dist/strategies/JwtStrategy.js.map +1 -1
  66. package/dist/strategies/SessionStrategy.d.ts +70 -1
  67. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  68. package/dist/strategies/SessionStrategy.js +100 -4
  69. package/dist/strategies/SessionStrategy.js.map +1 -1
  70. package/dist/vendor/nodeEnv.d.ts +5 -0
  71. package/dist/vendor/nodeEnv.d.ts.map +1 -0
  72. package/dist/vendor/nodeEnv.js +38 -0
  73. package/dist/vendor/nodeEnv.js.map +1 -0
  74. package/index.darwin-arm64.node +0 -0
  75. package/index.darwin-x64.node +0 -0
  76. package/index.linux-arm64-gnu.node +0 -0
  77. package/index.linux-x64-gnu.node +0 -0
  78. package/index.win32-x64-msvc.node +0 -0
  79. package/package.json +2 -2
  80. package/src/AttemptStore.ts +158 -0
  81. package/src/AuthManager.ts +9 -7
  82. package/src/AuthRateLimiter.ts +85 -80
  83. package/src/Authenticator.ts +92 -13
  84. package/src/RememberMeToken.ts +36 -8
  85. package/src/bouncer/evaluate.ts +1 -1
  86. package/src/duration.ts +8 -0
  87. package/src/errors.ts +11 -1
  88. package/src/index.ts +24 -3
  89. package/src/mfa/BackupCodesProvider.ts +13 -14
  90. package/src/mfa/MfaManager.ts +58 -43
  91. package/src/mfa/TotpProvider.ts +90 -22
  92. package/src/mfa/WebauthnProvider.ts +4 -1
  93. package/src/middleware.ts +9 -0
  94. package/src/native/generated.ts +0 -14
  95. package/src/native.ts +0 -5
  96. package/src/strategies/JwtStrategy.ts +20 -2
  97. package/src/strategies/SessionStrategy.ts +172 -4
  98. package/src/vendor/nodeEnv.ts +37 -0
@@ -31,6 +31,17 @@ export interface JwtClaims {
31
31
  [key: string]: unknown;
32
32
  }
33
33
 
34
+ /** What a token asserts beyond who its user is. */
35
+ export interface SignTokenOptions {
36
+ /**
37
+ * The user completed an MFA step-up for this session (`MfaManager.verify()`
38
+ * succeeded). Sets the `mfa` claim `@RequireMfa()` reads. It says the step
39
+ * was DONE, not that the account has MFA enabled — so it comes from the
40
+ * step-up flow and never from `findUser`.
41
+ */
42
+ mfa?: boolean;
43
+ }
44
+
34
45
  function sign(payload: JwtClaims, secret: string): string {
35
46
  const rust = nativeWarden();
36
47
  if (!rust) {
@@ -204,10 +215,16 @@ export class JwtStrategy implements AuthStrategy {
204
215
  return { authenticated: false, error: "User not found" };
205
216
  }
206
217
 
207
- return { authenticated: true, user };
218
+ // `mfa` is the TOKEN's step-up claim, whatever `findUser` said: an app
219
+ // that returns the account's "MFA enabled" flag there would otherwise
220
+ // unlock @RequireMfa routes for a token that never stepped up.
221
+ return {
222
+ authenticated: true,
223
+ user: { ...user, mfa: payload.mfa === true },
224
+ };
208
225
  }
209
226
 
210
- signToken(user: UserPayload): string {
227
+ signToken(user: UserPayload, options: SignTokenOptions = {}): string {
211
228
  const now = Math.floor(Date.now() / 1000);
212
229
  return sign(
213
230
  {
@@ -217,6 +234,7 @@ export class JwtStrategy implements AuthStrategy {
217
234
  iat: now,
218
235
  exp: now + this.#expiresIn,
219
236
  jti: randomUUID(),
237
+ ...(options.mfa === true ? { mfa: true } : {}),
220
238
  },
221
239
  this.#secret,
222
240
  );
@@ -7,6 +7,7 @@
7
7
  * @implements MISS-7
8
8
  */
9
9
 
10
+ import { randomUUID } from "node:crypto";
10
11
  import type {
11
12
  AuthClientResponse,
12
13
  AuthResult,
@@ -20,6 +21,7 @@ import {
20
21
  type RememberMeTokenDriver,
21
22
  verifyAndRecycleRememberMeToken,
22
23
  } from "../RememberMeToken.js";
24
+ import type { TokenBlacklist } from "../TokenBlacklist.js";
23
25
 
24
26
  export interface SessionStore {
25
27
  get(key: string): unknown;
@@ -39,8 +41,23 @@ export interface SessionStore {
39
41
  * directly so this is wired automatically.
40
42
  */
41
43
  regenerate(): void;
44
+ /**
45
+ * The session's lifetime in seconds, which a revocation has to outlast.
46
+ * Ream's `Session` carries it; another store may leave it out and set
47
+ * `sessionAge` instead.
48
+ */
49
+ readonly config?: { readonly ttl: number };
50
+ /**
51
+ * Whether ending the session on the server ends every copy of it. Ream's
52
+ * `Session` answers `false` under the cookie store; a store that leaves it
53
+ * out is taken to keep its sessions on the server.
54
+ */
55
+ readonly revocable?: boolean;
42
56
  }
43
57
 
58
+ /** Ream's default session lifetime, two hours. */
59
+ const DEFAULT_SESSION_AGE_SECONDS = 7200;
60
+
44
61
  export interface SessionStrategyConfig {
45
62
  sessionKey?: string;
46
63
  findUser: (id: string | number) => Promise<UserPayload | null>;
@@ -60,6 +77,47 @@ export interface SessionStrategyConfig {
60
77
  * default matches the `web` guard an app is most likely migrating.
61
78
  */
62
79
  rememberMeCookieName?: string;
80
+ /**
81
+ * Attributes of the remember-me cookie, over the defaults: `path: "/"`,
82
+ * `sameSite: "lax"`, and `secure` in production. The cookie is a bearer
83
+ * credential that lives for years, so it never leaves over plain HTTP or
84
+ * rides a cross-site POST unless the app says so here.
85
+ */
86
+ rememberMeCookie?: RememberMeCookieAttributes;
87
+ /**
88
+ * Revoke each sign-in at logout, as `JwtStrategy`'s `blacklist` revokes a
89
+ * token: every login gets an id, logout lists it until every copy of the
90
+ * session has expired, and a session carrying a listed id is signed out.
91
+ *
92
+ * What makes a logout hold under the COOKIE session driver, where the
93
+ * session lives in the browser and nothing on the server can delete it — a
94
+ * copy taken before the logout, or a request that was running across it and
95
+ * re-sent the signed-in cookie after, would otherwise be signed in still.
96
+ * The server-side drivers do not need it: logout rotates the session id and
97
+ * a request still in flight cannot write the old entry back.
98
+ *
99
+ * NAMED DEVIATION: upstream's session guard has no revocation; its cookie
100
+ * store has both holes.
101
+ */
102
+ blacklist?: TokenBlacklist;
103
+ /**
104
+ * Session lifetime in SECONDS, when the session does not carry it (Ream's
105
+ * does). A revocation is kept for twice this, so it outlives the cookie a
106
+ * request running across the logout re-issued: Ream's cookie store dates
107
+ * that cookie from when the request read the session, so it ends within one
108
+ * lifetime of the logout, however long the request ran. A store that dated
109
+ * it from the response would need a listing kept as long as its slowest
110
+ * request.
111
+ */
112
+ sessionAge?: number;
113
+ }
114
+
115
+ /** What an app may set on the remember-me cookie. */
116
+ export interface RememberMeCookieAttributes {
117
+ path?: string;
118
+ domain?: string;
119
+ sameSite?: "lax" | "strict" | "none" | false;
120
+ secure?: boolean;
63
121
  }
64
122
 
65
123
  /** Two years, Adonis' `rememberMeTokensAge` default. */
@@ -102,6 +160,25 @@ export class SessionStrategy implements AuthStrategy {
102
160
  #sessionKey: string;
103
161
 
104
162
  constructor(config: SessionStrategyConfig) {
163
+ // A NaN age made every token's expiry NaN, which no "is it past?" test
164
+ // ever caught: the token never expired.
165
+ const age = config.rememberMeAge;
166
+ if (age !== undefined && (!Number.isSafeInteger(age) || age <= 0)) {
167
+ throw new WardenError(
168
+ "INVALID_CONFIG",
169
+ `rememberMeAge must be a positive whole number of seconds, got ${String(age)}`,
170
+ );
171
+ }
172
+ const sessionAge = config.sessionAge;
173
+ if (
174
+ sessionAge !== undefined &&
175
+ (!Number.isSafeInteger(sessionAge) || sessionAge <= 0)
176
+ ) {
177
+ throw new WardenError(
178
+ "INVALID_CONFIG",
179
+ `sessionAge must be a positive whole number of seconds, got ${String(sessionAge)}`,
180
+ );
181
+ }
105
182
  this.#config = config;
106
183
  this.#sessionKey = config.sessionKey ?? "auth_user_id";
107
184
  }
@@ -111,6 +188,11 @@ export class SessionStrategy implements AuthStrategy {
111
188
  return this.#config.rememberMeCookieName ?? "remember_web";
112
189
  }
113
190
 
191
+ /** The remember-me cookie's attributes the app configured, if any. */
192
+ get rememberMeCookie(): RememberMeCookieAttributes | undefined {
193
+ return this.#config.rememberMeCookie;
194
+ }
195
+
114
196
  /** Whether "keep me signed in" is wired at all. */
115
197
  get usesRememberMeTokens(): boolean {
116
198
  return this.#config.rememberMeTokens !== undefined;
@@ -228,9 +310,20 @@ export class SessionStrategy implements AuthStrategy {
228
310
  if (!userId) return { authenticated: false, error: "No session user" };
229
311
  if (typeof userId !== "string" && typeof userId !== "number")
230
312
  return { authenticated: false, error: "Invalid session data" };
313
+ if (await this.#revoked(context.session)) {
314
+ // Forgotten, not just refused: a cookie session re-sent as it came in
315
+ // would carry the revoked sign-in on, and outlive its listing.
316
+ this.#unseat(context.session);
317
+ return { authenticated: false, error: "Session revoked" };
318
+ }
231
319
  const user = await this.#config.findUser(userId);
232
320
  if (!user) return { authenticated: false, error: "User not found" };
233
- return { authenticated: true, user };
321
+ // `mfa` is this SESSION's step-up, whatever `findUser` said (see
322
+ // markMfaVerified).
323
+ return {
324
+ authenticated: true,
325
+ user: { ...user, mfa: context.session.get(this.#mfaKey()) === true },
326
+ };
234
327
  }
235
328
 
236
329
  /**
@@ -252,8 +345,63 @@ export class SessionStrategy implements AuthStrategy {
252
345
  * exists to report.
253
346
  */
254
347
  seatSession(user: UserPayload, session: SessionStore): void {
348
+ if (session.revocable === false && !this.#config.blacklist) {
349
+ // Refused rather than signed in: on this store a logout could never
350
+ // hold — a copy of the cookie, or one re-sent by a request running
351
+ // across the logout, would stay signed in until it expired.
352
+ throw new WardenError(
353
+ "INVALID_CONFIG",
354
+ "This session store keeps the session in the browser and cannot revoke a sign-in. Give the session guard a `blacklist`, or use a server-side session store (database, redis).",
355
+ {
356
+ hint: "new SessionStrategy({ findUser, blacklist: new TokenBlacklist(new RedisBlacklistDriver(client)) })",
357
+ },
358
+ );
359
+ }
255
360
  session.regenerate();
256
361
  session.put(this.#sessionKey, user.id);
362
+ // What a logout revokes: one sign-in, not the user's every device.
363
+ session.put(this.#signInKey(), randomUUID());
364
+ // A new sign-in has not stepped up yet, whatever the session held before.
365
+ session.forget(this.#mfaKey());
366
+ }
367
+
368
+ /**
369
+ * Record that this session completed an MFA step-up (`MfaManager.verify()`
370
+ * succeeded), which `@RequireMfa()` requires. Cleared by the next sign-in
371
+ * and by logout.
372
+ */
373
+ markMfaVerified(session: SessionStore): void {
374
+ session.put(this.#mfaKey(), true);
375
+ }
376
+
377
+ /** The session key of the step-up marker, beside the user id's. */
378
+ #mfaKey(): string {
379
+ return `${this.#sessionKey}_mfa`;
380
+ }
381
+
382
+ /** The session key of this sign-in's id, which a logout revokes. */
383
+ #signInKey(): string {
384
+ return `${this.#sessionKey}_sid`;
385
+ }
386
+
387
+ /** Drop every key a sign-in wrote. */
388
+ #unseat(session: SessionStore): void {
389
+ session.forget(this.#sessionKey);
390
+ session.forget(this.#mfaKey());
391
+ session.forget(this.#signInKey());
392
+ }
393
+
394
+ /**
395
+ * Whether the blacklist refuses this session's sign-in. A session with no
396
+ * sign-in id is refused too, as `JwtStrategy` refuses a token with no `jti`:
397
+ * it could never be revoked, so letting it through would keep the hole open.
398
+ */
399
+ async #revoked(session: SessionStore): Promise<boolean> {
400
+ const blacklist = this.#config.blacklist;
401
+ if (!blacklist) return false;
402
+ const signIn = session.get(this.#signInKey());
403
+ if (typeof signIn !== "string" || signIn.length === 0) return true;
404
+ return blacklist.isRevoked(signIn);
257
405
  }
258
406
 
259
407
  async login(
@@ -280,11 +428,22 @@ export class SessionStrategy implements AuthStrategy {
280
428
  * the guard's own logic rather than by the test knowing where the id lives.
281
429
  */
282
430
  authenticateAsClient(user: UserPayload): AuthClientResponse {
283
- return { session: { [this.#sessionKey]: user.id } };
431
+ return {
432
+ session: {
433
+ [this.#sessionKey]: user.id,
434
+ [this.#signInKey()]: randomUUID(),
435
+ },
436
+ };
284
437
  }
285
438
 
286
439
  /**
287
- * Logout — remove the user id from the session.
440
+ * Logout — remove the user id from the session, and rotate its id.
441
+ *
442
+ * Rotating is the named deviation (upstream only forgets the key): the old
443
+ * id is what a request still running holds, and with the old entry gone it
444
+ * has nothing to write its signed-in copy back to. A copy of the old id
445
+ * points at nothing either. With a `blacklist`, the sign-in is also listed,
446
+ * which is what holds under the cookie driver.
288
447
  *
289
448
  * The remember-me token is revoked separately through
290
449
  * {@link revokeRememberMeToken}, because only the caller holds the cookie.
@@ -293,7 +452,16 @@ export class SessionStrategy implements AuthStrategy {
293
452
  session: SessionStore,
294
453
  state?: SessionGuardState,
295
454
  ): Promise<void> {
296
- session.forget(this.#sessionKey);
455
+ const signIn = session.get(this.#signInKey());
456
+ if (this.#config.blacklist && typeof signIn === "string") {
457
+ const age =
458
+ session.config?.ttl ??
459
+ this.#config.sessionAge ??
460
+ DEFAULT_SESSION_AGE_SECONDS;
461
+ await this.#config.blacklist.revoke(signIn, Date.now() + age * 2000);
462
+ }
463
+ this.#unseat(session);
464
+ session.regenerate();
297
465
  if (state) {
298
466
  state.viaRemember = false;
299
467
  state.attemptedViaRemember = false;
@@ -0,0 +1,37 @@
1
+ // Generated from scripts/vendor/nodeEnv.ts — do not edit.
2
+ //
3
+ // This package is published and built from its own repository, so the file
4
+ // has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
5
+ // and `pnpm vendor:check` fails if this copy has drifted from the original.
6
+
7
+ /**
8
+ * `NODE_ENV`, read the way every runtime actually spells it.
9
+ *
10
+ * `NODE_ENV=prod` is ordinary in a Dockerfile or a platform dashboard, and a
11
+ * bare `=== "production"` answers "not production" for it. What that costs
12
+ * differs per package, so the consequence is stated where the decision is
13
+ * taken, not here.
14
+ *
15
+ * The tables mirror the framework's (`@c9up/ream`, src/env/nodeEnv.ts), which
16
+ * is the origin rather than a peer: it formats to different rules and exposes
17
+ * `currentNodeEnv()` instead of `inProduction()`.
18
+ */
19
+
20
+ const DEV_ENVS = ["dev", "develop", "development"];
21
+ const PROD_ENVS = ["prod", "production"];
22
+ const TEST_ENVS = ["test", "testing"];
23
+
24
+ /** The canonical name for whatever `NODE_ENV` holds. */
25
+ export function normalizeNodeEnv(value: string | undefined): string {
26
+ if (!value || typeof value !== "string") return "unknown";
27
+ const env = value.toLowerCase();
28
+ if (DEV_ENVS.includes(env)) return "development";
29
+ if (PROD_ENVS.includes(env)) return "production";
30
+ if (TEST_ENVS.includes(env)) return "test";
31
+ return env;
32
+ }
33
+
34
+ /** Whether this process is running in production, under any spelling. */
35
+ export function inProduction(): boolean {
36
+ return normalizeNodeEnv(process.env.NODE_ENV) === "production";
37
+ }