@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
package/src/standalone.ts CHANGED
@@ -28,6 +28,23 @@ import { ApiKeyStrategy } from "./strategies/ApiKeyStrategy.js";
28
28
  import { JwtStrategy } from "./strategies/JwtStrategy.js";
29
29
  import { SessionStrategy } from "./strategies/SessionStrategy.js";
30
30
 
31
+ /**
32
+ * The slice of an Express-style request the middleware reads and writes.
33
+ * Structural, so an Express, Connect or Polka request fits without a cast.
34
+ */
35
+ export interface StandaloneRequest {
36
+ headers?: Record<string, string | string[] | undefined>;
37
+ /** The verification result, set on success. */
38
+ auth?: AuthResult;
39
+ /** The authenticated user, set on success (Express convention). */
40
+ user?: UserPayload;
41
+ }
42
+
43
+ /** The slice of an Express-style response the middleware writes to. */
44
+ export interface StandaloneResponse {
45
+ status(code: number): { json(body: unknown): unknown };
46
+ }
47
+
31
48
  export interface Warden {
32
49
  /** Verify a bearer token. Returns auth result with user payload. */
33
50
  verify(token: string, strategy?: string): Promise<AuthResult>;
@@ -36,18 +53,32 @@ export interface Warden {
36
53
  credentials: Record<string, unknown>,
37
54
  strategy?: string,
38
55
  ): Promise<AuthResult>;
39
- /** Generate a JWT for a user (jwt strategy only). */
40
- generateToken(user: UserPayload): Promise<string>;
56
+ /**
57
+ * Mint a token for a user through a token-issuing guard: the one named, or
58
+ * the default guard. Rejects with `E_WARDEN_STRATEGY_CANNOT_ISSUE` when that
59
+ * guard mints no tokens (a session guard, an access-tokens guard).
60
+ */
61
+ generateToken(user: UserPayload, guard?: string): Promise<string>;
41
62
  /** The underlying AuthManager for advanced use. */
42
63
  manager: AuthManager;
43
64
  /** Express middleware — extracts Bearer token, verifies, attaches `req.auth`. */
44
65
  expressMiddleware(): (
45
- req: Record<string, unknown>,
46
- res: Record<string, unknown>,
66
+ req: StandaloneRequest,
67
+ res: StandaloneResponse,
47
68
  next: () => void,
48
69
  ) => void;
49
70
  }
50
71
 
72
+ /** Send one JSON error, shaped like the Ream middleware's. */
73
+ function fail(
74
+ res: StandaloneResponse,
75
+ status: number,
76
+ code: string,
77
+ message: string,
78
+ ): void {
79
+ res.status(status).json({ error: { code, message } });
80
+ }
81
+
51
82
  /**
52
83
  * Create a standalone Warden instance — no Ream container needed.
53
84
  */
@@ -86,46 +117,58 @@ export function createWarden(config: WardenConfig): Warden {
86
117
  authenticate: (credentials, strategy) =>
87
118
  manager.authenticate(credentials, strategy),
88
119
 
89
- async generateToken(user: UserPayload): Promise<string> {
90
- const jwt = manager.getStrategy("jwt") as JwtStrategy;
91
- return jwt.signToken(user);
120
+ async generateToken(user: UserPayload, guard?: string): Promise<string> {
121
+ // The guard the application configured, not one named `jwt`: a
122
+ // `guards: { api: jwtGuard(...) }` config has no guard by that name.
123
+ return manager.issueFor(user, guard);
92
124
  },
93
125
 
94
126
  manager,
95
127
 
96
128
  expressMiddleware() {
97
129
  return (req, res, next) => {
98
- const headers = req.headers as Record<string, string> | undefined;
99
- const authHeader = headers?.authorization ?? "";
130
+ const authHeader = req.headers?.authorization;
100
131
  const token =
101
132
  typeof authHeader === "string" && authHeader.startsWith("Bearer ")
102
133
  ? authHeader.slice(7)
103
134
  : "";
104
135
 
105
136
  if (!token) {
106
- (res as { status: (n: number) => { json: (d: unknown) => void } })
107
- .status(401)
108
- .json({
109
- error: {
110
- code: "E_WARDEN_UNAUTHORIZED",
111
- message: "Missing authentication token",
112
- },
113
- });
137
+ fail(
138
+ res,
139
+ 401,
140
+ "E_WARDEN_UNAUTHORIZED",
141
+ "Missing authentication token",
142
+ );
114
143
  return;
115
144
  }
116
145
 
117
146
  manager
118
147
  .verify(token)
119
148
  .then((result) => {
149
+ if (result.strategyCrash === true) {
150
+ // The guard threw — a database down, a bug — which is a
151
+ // server incident, not a bad credential: a 500, and a
152
+ // generic message. The thrown text (a host, a port, a
153
+ // query) is for the logs, never for the client.
154
+ console.error(
155
+ `[warden] strategy threw during verify(): ${result.error ?? "unknown error"}`,
156
+ );
157
+ fail(
158
+ res,
159
+ 500,
160
+ "E_WARDEN_AUTH_STRATEGY_ERROR",
161
+ "Authentication unavailable. Check server logs.",
162
+ );
163
+ return;
164
+ }
120
165
  if (!result.authenticated || !result.user) {
121
- (res as { status: (n: number) => { json: (d: unknown) => void } })
122
- .status(401)
123
- .json({
124
- error: {
125
- code: "E_WARDEN_UNAUTHORIZED",
126
- message: result.error ?? "Authentication failed",
127
- },
128
- });
166
+ fail(
167
+ res,
168
+ 401,
169
+ "E_WARDEN_UNAUTHORIZED",
170
+ result.error ?? "Authentication failed",
171
+ );
129
172
  return;
130
173
  }
131
174
  // Attach auth result to the request object (Express convention).
@@ -134,14 +177,12 @@ export function createWarden(config: WardenConfig): Warden {
134
177
  next();
135
178
  })
136
179
  .catch(() => {
137
- (res as { status: (n: number) => { json: (d: unknown) => void } })
138
- .status(500)
139
- .json({
140
- error: {
141
- code: "E_WARDEN_AUTH_ERROR",
142
- message: "Internal authentication error",
143
- },
144
- });
180
+ fail(
181
+ res,
182
+ 500,
183
+ "E_WARDEN_AUTH_ERROR",
184
+ "Internal authentication error",
185
+ );
145
186
  });
146
187
  };
147
188
  },
@@ -1,23 +1,54 @@
1
1
  /**
2
- * API Key authentication strategy.
2
+ * Access-tokens authentication strategy (opaque API tokens).
3
3
  *
4
- * Supports: Authorization: Bearer <key> or X-API-Key: <key>
4
+ * Reads the token from `Authorization: Bearer <token>` or the configured
5
+ * header (`x-api-key` by default), verifies it through an access-tokens
6
+ * provider — which stores only a hash, compares in constant time and checks
7
+ * expiry — then loads the user it belongs to.
8
+ *
9
+ * The token's abilities stay ON THE TOKEN: the user is handed to the request
10
+ * with `currentAccessToken`, and a handler asks it
11
+ * (`ctx.auth.user.currentAccessToken.allows('orders:write')`). They are never
12
+ * merged into `user.permissions`, which holds the user's own permissions: a
13
+ * token whose ability happened to share a permission's name would otherwise
14
+ * grant that permission to a user who does not hold it, and a token restricted
15
+ * to a few abilities would still carry every permission of its user. Warden's
16
+ * permission checks (`@Permission`, `hasPermission`) require both: the user's
17
+ * permission AND the token's ability (`tokenAllows`).
5
18
  *
6
19
  * @implements MISS-8
7
20
  */
8
21
 
22
+ import type {
23
+ AccessToken,
24
+ AccessTokensProviderContract,
25
+ CreateAccessTokenOptions,
26
+ TokenOwner,
27
+ } from "../AccessToken.js";
9
28
  import type {
10
29
  AuthClientResponse,
11
30
  AuthResult,
12
31
  AuthStrategy,
13
32
  UserPayload,
14
33
  } from "../AuthManager.js";
34
+ import { WardenError } from "../errors.js";
35
+ import { Secret } from "../Secret.js";
15
36
 
16
37
  export interface ApiKeyConfig {
38
+ /** Header read beside `Authorization: Bearer`. Default `x-api-key`. */
17
39
  headerName?: string;
18
- findByKey: (
19
- key: string,
20
- ) => Promise<{ user: UserPayload; scopes?: string[] } | null>;
40
+ /**
41
+ * Verifies a presented token and mints new ones — an
42
+ * `AccessTokensProvider` over the application's token table, or the
43
+ * application's own implementation of the contract.
44
+ */
45
+ tokens: AccessTokensProviderContract;
46
+ /**
47
+ * Load the user a verified token belongs to. Called on every request, so a
48
+ * token whose account was deleted or disabled stops working: answer `null`
49
+ * and the request is refused.
50
+ */
51
+ findUser: (id: string | number) => Promise<UserPayload | null>;
21
52
  }
22
53
 
23
54
  export class ApiKeyStrategy implements AuthStrategy {
@@ -25,10 +56,28 @@ export class ApiKeyStrategy implements AuthStrategy {
25
56
  // spelling is still accepted as a guard name / credential trigger by the
26
57
  // middleware and providers (see `API_KEY_GUARD_NAMES`) for back-compat.
27
58
  name = "access_tokens";
28
- #config: ApiKeyConfig;
29
- #headerName: string;
59
+ readonly #config: ApiKeyConfig;
60
+ readonly #headerName: string;
30
61
 
31
62
  constructor(config: ApiKeyConfig) {
63
+ // A config written for the earlier `findByKey` shape has no provider:
64
+ // refused at boot rather than at the first request.
65
+ const tokens: unknown = Reflect.get(Object(config), "tokens");
66
+ if (typeof Reflect.get(Object(tokens), "verify") !== "function") {
67
+ throw new WardenError(
68
+ "INVALID_CONFIG",
69
+ "The access-tokens guard needs `tokens`, a provider that verifies hashed tokens.",
70
+ {
71
+ hint: "apiKeyGuard({ tokens: new AccessTokensProvider({ store }), findUser: (id) => User.find(id) })",
72
+ },
73
+ );
74
+ }
75
+ if (typeof config.findUser !== "function") {
76
+ throw new WardenError(
77
+ "INVALID_CONFIG",
78
+ "The access-tokens guard needs `findUser`, to load the user a token belongs to.",
79
+ );
80
+ }
32
81
  this.#config = config;
33
82
  this.#headerName = config.headerName ?? "x-api-key";
34
83
  }
@@ -43,50 +92,71 @@ export class ApiKeyStrategy implements AuthStrategy {
43
92
  password: string;
44
93
  }): Promise<AuthResult> {
45
94
  throw new Error(
46
- "ApiKeyStrategy does not support credential-based auth. Use verify() with the API key.",
95
+ "ApiKeyStrategy does not support credential-based auth. Use verify() with the access token.",
47
96
  );
48
97
  }
49
98
 
50
99
  /**
51
- * The header a test client sends to present `key` (AdonisJS
52
- * `authenticateAsClient`).
100
+ * Mint a token for `user` through the provider. The returned token carries
101
+ * `value` this once: hand it to the client now.
102
+ */
103
+ createToken(
104
+ user: TokenOwner,
105
+ abilities?: string[],
106
+ options?: CreateAccessTokenOptions,
107
+ ): Promise<AccessToken> {
108
+ return this.#config.tokens.create(user, abilities, options);
109
+ }
110
+
111
+ /**
112
+ * Revoke the token behind `value`. Answers whether it existed.
53
113
  *
54
- * Takes the KEY, not a user: an API key is issued out of band, so a test
55
- * seeds one through `findByKey` and hands that same key here — inventing a
56
- * key the resolver has never seen would prove nothing.
114
+ * NAMED DEVIATION — upstream's guard is built per request and revokes the
115
+ * token it authenticated with, so it takes no argument. A warden strategy
116
+ * is shared by every request and keeps none of them, so the value is passed
117
+ * in; a sign-out handler has it, it is the request's credential.
57
118
  */
58
- authenticateAsClient(key: string): AuthClientResponse {
59
- return {
60
- headers: {
61
- authorization: `Bearer ${key}`,
62
- [this.#headerName]: key,
63
- },
64
- };
119
+ invalidateToken(value: string): Promise<boolean> {
120
+ return this.#config.tokens.invalidate(new Secret(value));
65
121
  }
66
122
 
67
- async verify(token: string): Promise<AuthResult> {
68
- const result = await this.#config.findByKey(token);
69
- if (!result) return { authenticated: false, error: "Invalid API key" };
123
+ /**
124
+ * What a test client sends to be `user`: a real token, minted through the
125
+ * provider, so the test authenticates the way the application will.
126
+ */
127
+ async authenticateAsClient(
128
+ user: TokenOwner,
129
+ abilities?: string[],
130
+ options?: CreateAccessTokenOptions,
131
+ ): Promise<AuthClientResponse> {
132
+ const token = await this.createToken(user, abilities, options);
133
+ const value = token.value?.release();
134
+ if (value === undefined) {
135
+ throw new WardenError(
136
+ "INVALID_CONFIG",
137
+ "The token provider returned a token without its value from create().",
138
+ );
139
+ }
140
+ return { headers: { authorization: `Bearer ${value}` } };
141
+ }
70
142
 
71
- const user: UserPayload = { ...result.user };
72
- if (result.scopes && result.scopes.length > 0) {
73
- // Expose the API key's scopes on `user.permissions` (without mutating
74
- // the source object) so APP code can read them via
75
- // `ctx.auth.user.permissions`.
76
- //
77
- // IMPORTANT — these scopes are a SEPARATE axis from the `@Permission`
78
- // route gate, by design (Adonis Bouncer parity): the gate flows through
79
- // RightsResolver, which resolves grants from the rights STORE and
80
- // deliberately ignores payload-carried permissions (see RightsResolver
81
- // D1). This mirrors AdonisJS, where token abilities are checked via
82
- // `currentAccessToken.allows(scope)` and are NOT consulted by Bouncer
83
- // ability/policy checks. So an API key carrying `orders.create` is NOT
84
- // auto-granted by `@Permission('orders.create')` — that's intentional,
85
- // not a bug. Gate API-key routes on scopes with an explicit app-level
86
- // check against `ctx.auth.user.permissions`.
87
- const merged = new Set([...(user.permissions ?? []), ...result.scopes]);
88
- user.permissions = [...merged];
143
+ async verify(token: string): Promise<AuthResult> {
144
+ const accessToken = await this.#config.tokens.verify(new Secret(token));
145
+ if (accessToken === null) {
146
+ return { authenticated: false, error: "Invalid access token" };
147
+ }
148
+ const user = await this.#config.findUser(accessToken.tokenableId);
149
+ if (!user) {
150
+ return {
151
+ authenticated: false,
152
+ error: "The account behind this token is no longer available",
153
+ };
89
154
  }
90
- return { authenticated: true, user };
155
+ // A copy: the provider's object is the application's, and attaching the
156
+ // token to it would leak one request's token into the next.
157
+ return {
158
+ authenticated: true,
159
+ user: { ...user, currentAccessToken: accessToken },
160
+ };
91
161
  }
92
162
  }
@@ -11,7 +11,7 @@ import type {
11
11
  UserPayload,
12
12
  } from "../AuthManager.js";
13
13
  import { resolveExpiresInSeconds, type TokenDuration } from "../duration.js";
14
- import { nativeWarden } from "../native.js";
14
+ import { nativeWarden, nativeWardenLoadError } from "../native.js";
15
15
  import type { TokenBlacklist } from "../TokenBlacklist.js";
16
16
 
17
17
  /**
@@ -47,6 +47,7 @@ function sign(payload: JwtClaims, secret: string): string {
47
47
  if (!rust) {
48
48
  throw new Error(
49
49
  "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
50
+ { cause: nativeWardenLoadError() },
50
51
  );
51
52
  }
52
53
  return rust.jwtSign(JSON.stringify(payload), secret);
@@ -57,6 +58,7 @@ function verify(token: string, secret: string): JwtClaims | null {
57
58
  if (!rust) {
58
59
  throw new Error(
59
60
  "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
61
+ { cause: nativeWardenLoadError() },
60
62
  );
61
63
  }
62
64
  try {
@@ -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>;
@@ -67,6 +84,32 @@ export interface SessionStrategyConfig {
67
84
  * rides a cross-site POST unless the app says so here.
68
85
  */
69
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;
70
113
  }
71
114
 
72
115
  /** What an app may set on the remember-me cookie. */
@@ -126,6 +169,16 @@ export class SessionStrategy implements AuthStrategy {
126
169
  `rememberMeAge must be a positive whole number of seconds, got ${String(age)}`,
127
170
  );
128
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
+ }
129
182
  this.#config = config;
130
183
  this.#sessionKey = config.sessionKey ?? "auth_user_id";
131
184
  }
@@ -257,6 +310,12 @@ export class SessionStrategy implements AuthStrategy {
257
310
  if (!userId) return { authenticated: false, error: "No session user" };
258
311
  if (typeof userId !== "string" && typeof userId !== "number")
259
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
+ }
260
319
  const user = await this.#config.findUser(userId);
261
320
  if (!user) return { authenticated: false, error: "User not found" };
262
321
  // `mfa` is this SESSION's step-up, whatever `findUser` said (see
@@ -286,8 +345,22 @@ export class SessionStrategy implements AuthStrategy {
286
345
  * exists to report.
287
346
  */
288
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
+ }
289
360
  session.regenerate();
290
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());
291
364
  // A new sign-in has not stepped up yet, whatever the session held before.
292
365
  session.forget(this.#mfaKey());
293
366
  }
@@ -306,6 +379,31 @@ export class SessionStrategy implements AuthStrategy {
306
379
  return `${this.#sessionKey}_mfa`;
307
380
  }
308
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);
405
+ }
406
+
309
407
  async login(
310
408
  user: UserPayload,
311
409
  session: SessionStore,
@@ -330,11 +428,22 @@ export class SessionStrategy implements AuthStrategy {
330
428
  * the guard's own logic rather than by the test knowing where the id lives.
331
429
  */
332
430
  authenticateAsClient(user: UserPayload): AuthClientResponse {
333
- return { session: { [this.#sessionKey]: user.id } };
431
+ return {
432
+ session: {
433
+ [this.#sessionKey]: user.id,
434
+ [this.#signInKey()]: randomUUID(),
435
+ },
436
+ };
334
437
  }
335
438
 
336
439
  /**
337
- * 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.
338
447
  *
339
448
  * The remember-me token is revoked separately through
340
449
  * {@link revokeRememberMeToken}, because only the caller holds the cookie.
@@ -343,8 +452,16 @@ export class SessionStrategy implements AuthStrategy {
343
452
  session: SessionStore,
344
453
  state?: SessionGuardState,
345
454
  ): Promise<void> {
346
- session.forget(this.#sessionKey);
347
- session.forget(this.#mfaKey());
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();
348
465
  if (state) {
349
466
  state.viaRemember = false;
350
467
  state.attemptedViaRemember = false;