@c9up/warden 0.1.22 → 0.1.24

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 (81) hide show
  1. package/README.md +1 -1
  2. package/dist/AuthManager.d.ts +14 -3
  3. package/dist/AuthManager.d.ts.map +1 -1
  4. package/dist/AuthManager.js +32 -4
  5. package/dist/AuthManager.js.map +1 -1
  6. package/dist/Authenticator.d.ts +49 -5
  7. package/dist/Authenticator.d.ts.map +1 -1
  8. package/dist/Authenticator.js +235 -26
  9. package/dist/Authenticator.js.map +1 -1
  10. package/dist/WardenProvider.js +1 -1
  11. package/dist/WardenProvider.js.map +1 -1
  12. package/dist/bouncer/Bouncer.d.ts +2 -2
  13. package/dist/bouncer/Bouncer.d.ts.map +1 -1
  14. package/dist/bouncer/Bouncer.js +1 -1
  15. package/dist/bouncer/PolicyAuthorizer.d.ts +1 -1
  16. package/dist/bouncer/PolicyAuthorizer.d.ts.map +1 -1
  17. package/dist/bouncer/PolicyAuthorizer.js +1 -1
  18. package/dist/bouncer/PolicyAuthorizer.js.map +1 -1
  19. package/dist/config.d.ts +8 -1
  20. package/dist/config.d.ts.map +1 -1
  21. package/dist/config.js.map +1 -1
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +11 -7
  24. package/dist/errors.js.map +1 -1
  25. package/dist/index.d.ts +3 -7
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +1 -4
  28. package/dist/index.js.map +1 -1
  29. package/dist/middleware.d.ts +14 -1
  30. package/dist/middleware.d.ts.map +1 -1
  31. package/dist/middleware.js +7 -5
  32. package/dist/middleware.js.map +1 -1
  33. package/dist/native.js +2 -2
  34. package/dist/native.js.map +1 -1
  35. package/dist/standalone.js +3 -3
  36. package/dist/standalone.js.map +1 -1
  37. package/dist/strategies/JwtStrategy.js +2 -2
  38. package/dist/strategies/JwtStrategy.js.map +1 -1
  39. package/dist/strategies/SessionStrategy.d.ts +37 -25
  40. package/dist/strategies/SessionStrategy.d.ts.map +1 -1
  41. package/dist/strategies/SessionStrategy.js +43 -44
  42. package/dist/strategies/SessionStrategy.js.map +1 -1
  43. package/index.darwin-arm64.node +0 -0
  44. package/index.darwin-x64.node +0 -0
  45. package/index.linux-arm64-gnu.node +0 -0
  46. package/index.linux-x64-gnu.node +0 -0
  47. package/index.win32-x64-msvc.node +0 -0
  48. package/package.json +1 -1
  49. package/src/AuthManager.ts +68 -6
  50. package/src/Authenticator.ts +299 -28
  51. package/src/WardenProvider.ts +1 -1
  52. package/src/bouncer/Bouncer.ts +2 -2
  53. package/src/bouncer/PolicyAuthorizer.ts +1 -1
  54. package/src/config.ts +8 -1
  55. package/src/errors.ts +11 -7
  56. package/src/index.ts +9 -11
  57. package/src/middleware.ts +24 -5
  58. package/src/native.ts +2 -2
  59. package/src/standalone.ts +3 -3
  60. package/src/strategies/JwtStrategy.ts +2 -2
  61. package/src/strategies/SessionStrategy.ts +73 -46
  62. package/dist/firstcontact/FirstContactManager.d.ts +0 -25
  63. package/dist/firstcontact/FirstContactManager.d.ts.map +0 -1
  64. package/dist/firstcontact/FirstContactManager.js +0 -38
  65. package/dist/firstcontact/FirstContactManager.js.map +0 -1
  66. package/dist/firstcontact/drivers/GitHubDriver.d.ts +0 -14
  67. package/dist/firstcontact/drivers/GitHubDriver.d.ts.map +0 -1
  68. package/dist/firstcontact/drivers/GitHubDriver.js +0 -60
  69. package/dist/firstcontact/drivers/GitHubDriver.js.map +0 -1
  70. package/dist/firstcontact/drivers/GoogleDriver.d.ts +0 -14
  71. package/dist/firstcontact/drivers/GoogleDriver.d.ts.map +0 -1
  72. package/dist/firstcontact/drivers/GoogleDriver.js +0 -63
  73. package/dist/firstcontact/drivers/GoogleDriver.js.map +0 -1
  74. package/dist/firstcontact/types.d.ts +0 -44
  75. package/dist/firstcontact/types.d.ts.map +0 -1
  76. package/dist/firstcontact/types.js +0 -22
  77. package/dist/firstcontact/types.js.map +0 -1
  78. package/src/firstcontact/FirstContactManager.ts +0 -54
  79. package/src/firstcontact/drivers/GitHubDriver.ts +0 -77
  80. package/src/firstcontact/drivers/GoogleDriver.ts +0 -80
  81. package/src/firstcontact/types.ts +0 -62
@@ -23,7 +23,11 @@ import type {
23
23
  import { E_UNAUTHORIZED_ACCESS, WardenError } from "./errors.js";
24
24
  import type { WardenContext } from "./middleware.js";
25
25
  import { sanitizePayload } from "./sanitize.js";
26
- import type { SessionStore } from "./strategies/SessionStrategy.js";
26
+ import {
27
+ createSessionGuardState,
28
+ type SessionGuardState,
29
+ type SessionStore,
30
+ } from "./strategies/SessionStrategy.js";
27
31
 
28
32
  /**
29
33
  * Guard names Warden accepts for the API-key / access-tokens driver. AdonisJS
@@ -39,6 +43,66 @@ interface StrategyWithContext extends AuthStrategy {
39
43
  verifyWithContext(token: string, ctx: unknown): Promise<AuthResult>;
40
44
  }
41
45
 
46
+ /**
47
+ * The strategy behind a guard name, or `undefined` when nothing is registered
48
+ * under it.
49
+ *
50
+ * `getStrategy()` throws for an unknown name — correct when an application
51
+ * asks for a guard by name, wrong here: this is a capability probe across a
52
+ * list, and a name that resolves to nothing simply is not a session guard.
53
+ */
54
+ function strategyOrUndefined(
55
+ auth: AuthManager,
56
+ name: string,
57
+ ): AuthStrategy | undefined {
58
+ try {
59
+ return auth.getStrategy(name);
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * A guard that can keep a user signed in: mint a token, name its cookie, read
67
+ * one back, and seat the session that follows.
68
+ */
69
+ interface RememberMeIssuer {
70
+ issueRememberMeToken(user: UserPayload): Promise<string | null>;
71
+ authenticateViaRememberMeToken(
72
+ cookieValue: unknown,
73
+ state?: SessionGuardState,
74
+ ): Promise<{ user: UserPayload; cookieValue: string } | null>;
75
+ seatSession(user: UserPayload, session: SessionStore): void;
76
+ revokeRememberMeToken(cookieValue: unknown): Promise<void>;
77
+ readonly rememberMeCookieName: string;
78
+ readonly rememberMeAgeSeconds: number;
79
+ }
80
+
81
+ /**
82
+ * Structural, like every other capability probe here: a guard an application
83
+ * wrote itself, carrying the same three members, keeps users signed in just as
84
+ * well as the one shipped with the package.
85
+ */
86
+ function isRememberMeIssuer(
87
+ strategy: AuthStrategy,
88
+ ): strategy is AuthStrategy & RememberMeIssuer {
89
+ return (
90
+ typeof Reflect.get(strategy, "issueRememberMeToken") === "function" &&
91
+ typeof Reflect.get(strategy, "authenticateViaRememberMeToken") ===
92
+ "function" &&
93
+ typeof Reflect.get(strategy, "seatSession") === "function" &&
94
+ typeof Reflect.get(strategy, "revokeRememberMeToken") === "function" &&
95
+ typeof Reflect.get(strategy, "rememberMeCookieName") === "string" &&
96
+ typeof Reflect.get(strategy, "rememberMeAgeSeconds") === "number"
97
+ );
98
+ }
99
+
100
+ /** Whether the guard behind `name` authenticates from the request context. */
101
+ function isSessionGuard(auth: AuthManager, name: string): boolean {
102
+ const strategy = strategyOrUndefined(auth, name);
103
+ return strategy !== undefined && hasVerifyWithContext(strategy);
104
+ }
105
+
42
106
  function hasVerifyWithContext(
43
107
  strategy: AuthStrategy,
44
108
  ): strategy is StrategyWithContext {
@@ -115,7 +179,6 @@ export async function tryAuthenticate(
115
179
  bearerToken: string;
116
180
  apiKey: string;
117
181
  session: SessionStore | undefined;
118
- hasSessionStrategy: boolean;
119
182
  },
120
183
  ): Promise<AuthAttempt> {
121
184
  const { bearerToken, apiKey, session } = creds;
@@ -126,21 +189,22 @@ export async function tryAuthenticate(
126
189
  for (const strategyName of strategies) {
127
190
  try {
128
191
  let r: AuthResult;
129
- if (strategyName === "session") {
130
- const strategy = auth.getStrategy(strategyName);
131
- const verifyWithContext =
132
- strategy && hasVerifyWithContext(strategy)
133
- ? strategy.verifyWithContext
134
- : undefined;
135
- if (verifyWithContext) {
136
- attemptCount++;
137
- r = await verifyWithContext.call(strategy, "", { session });
138
- // The session path bypasses AuthManager.verify(), so apply the
139
- // same prototype-pollution guard JWT / api-key users get there.
140
- if (r.user) sanitizePayload(r.user);
141
- } else {
142
- continue;
143
- }
192
+ // A session guard is one that can verify FROM THE REQUEST CONTEXT,
193
+ // not one registered under a particular name. `guards: { web:
194
+ // sessionGuard(...) }` is the documented config shape, and matching
195
+ // on the literal "session" sent it down the bearer-token path — so
196
+ // `auth.use('web').authenticate()` never read the session at all.
197
+ const strategy = strategyOrUndefined(auth, strategyName);
198
+ const verifyWithContext =
199
+ strategy && hasVerifyWithContext(strategy)
200
+ ? strategy.verifyWithContext
201
+ : undefined;
202
+ if (verifyWithContext !== undefined) {
203
+ attemptCount++;
204
+ r = await verifyWithContext.call(strategy, "", { session });
205
+ // The session path bypasses AuthManager.verify(), so apply the
206
+ // same prototype-pollution guard JWT / api-key users get there.
207
+ if (r.user) sanitizePayload(r.user);
144
208
  } else {
145
209
  // Native-first credential, other transport as fallback so a
146
210
  // single-credential client still authenticates (and an invalid
@@ -185,6 +249,12 @@ export class GuardAccessor {
185
249
  readonly #auth: AuthManager;
186
250
  readonly #name: string;
187
251
  readonly #parent: Authenticator;
252
+ /**
253
+ * The session-guard flags for THIS request. They live on the accessor —
254
+ * which the Authenticator builds and caches per request — and never on the
255
+ * strategy, which is built once from config and shared by every request.
256
+ */
257
+ readonly #state: SessionGuardState = createSessionGuardState();
188
258
 
189
259
  constructor(
190
260
  ctx: WardenContext,
@@ -209,19 +279,203 @@ export class GuardAccessor {
209
279
  return this.user !== undefined;
210
280
  }
211
281
 
282
+ /**
283
+ * Whether the user was revived from a remember-me cookie rather than
284
+ * signing in.
285
+ *
286
+ * This is the distinction that lets an app demand the password again before
287
+ * something sensitive — changing an email, spending money, deleting an
288
+ * account.
289
+ */
290
+ get viaRemember(): boolean {
291
+ return this.#state.viaRemember;
292
+ }
293
+
294
+ /** Whether a remember-me cookie was tried at all on this request. */
295
+ get attemptedViaRemember(): boolean {
296
+ return this.#state.attemptedViaRemember;
297
+ }
298
+
299
+ /**
300
+ * Whether `logout()` has run during this request.
301
+ *
302
+ * A handler that logs out and then keeps working — clearing a cart, writing
303
+ * an audit line — could not otherwise tell the session was already gone.
304
+ */
305
+ get isLoggedOut(): boolean {
306
+ return this.#state.isLoggedOut;
307
+ }
308
+
309
+ /**
310
+ * Revive the user from a remember-me cookie, recording on this request that
311
+ * one was tried and whether it worked.
312
+ *
313
+ * The returned `cookieValue` must replace the one the browser holds: the
314
+ * token is single-use and is recycled on every successful revival.
315
+ */
316
+ authenticateViaRememberMeToken(
317
+ cookieValue: unknown,
318
+ ): Promise<{ user: UserPayload; cookieValue: string } | null> {
319
+ return this.#auth.authenticateViaRememberMeToken(
320
+ cookieValue,
321
+ this.#name,
322
+ this.#state,
323
+ );
324
+ }
325
+
212
326
  /** Authenticate the request using only this guard (throws on failure). */
213
327
  authenticate(): Promise<void> {
214
328
  return this.#parent.authenticateUsing([this.#name]);
215
329
  }
216
330
 
217
- /** Log a user in through this guard (session guards). */
218
- login(user: UserPayload): Promise<void> {
219
- return this.#auth.login(user, this.#requireSession(), this.#name);
331
+ /**
332
+ * Revive this request from the remember-me cookie, if the browser holds one.
333
+ *
334
+ * The token is single-use: a success recycles the cookie and re-seats the
335
+ * session, so a stolen copy stops working the moment the real user comes
336
+ * back, and the rest of the request sees an ordinary signed-in user.
337
+ */
338
+ async tryRememberMeCookie(): Promise<UserPayload | undefined> {
339
+ const read = this.#ctx.request.encryptedCookie;
340
+ const write = this.#ctx.response.encryptedCookie;
341
+ const session = this.#ctx.session;
342
+ if (!read || !write || !session) return undefined;
343
+
344
+ const strategy = strategyOrUndefined(this.#auth, this.#name);
345
+ if (!strategy || !isRememberMeIssuer(strategy)) return undefined;
346
+
347
+ const cookie = read.call(this.#ctx.request, strategy.rememberMeCookieName);
348
+ if (!cookie) return undefined;
349
+
350
+ const revived = await strategy.authenticateViaRememberMeToken(
351
+ cookie,
352
+ this.#state,
353
+ );
354
+ if (!revived) return undefined;
355
+
356
+ write.call(
357
+ this.#ctx.response,
358
+ strategy.rememberMeCookieName,
359
+ revived.cookieValue,
360
+ { maxAge: strategy.rememberMeAgeSeconds, httpOnly: true },
361
+ );
362
+ // Seat the session WITHOUT `login()`: that method means a password was
363
+ // typed, and it clears `viaRemember` — the one thing this path exists to
364
+ // report, and what an app checks before letting someone change an email
365
+ // or spend money.
366
+ strategy.seatSession(revived.user, session);
367
+ return revived.user;
368
+ }
369
+
370
+ /**
371
+ * Log a user in through this guard (session guards).
372
+ *
373
+ * `remember` mints a remember-me token and writes it as an ENCRYPTED,
374
+ * httpOnly cookie — the cookie IS the credential, so anyone who can read it
375
+ * can present it. Without `remember`, any cookie the browser still holds is
376
+ * cleared: signing in without ticking the box has to REVOKE the standing
377
+ * permission, not leave it in place.
378
+ */
379
+ async login(user: UserPayload, remember = false): Promise<void> {
380
+ const session = this.#requireSession();
381
+ const issued = remember ? await this.#issueRememberMe(user) : undefined;
382
+ if (!remember) this.#clearRememberMe();
383
+ try {
384
+ await this.#auth.login(user, session, this.#name, this.#state);
385
+ } catch (err) {
386
+ // The token is minted and the cookie sent before the session is
387
+ // seated — upstream's order, and it has to be, because the cookie
388
+ // belongs on the same response.
389
+ //
390
+ // NAMED DEVIATION — upstream does not roll any of this back; it has
391
+ // no need to, because its session write is a map assignment that
392
+ // cannot fail. Here `login()` also fires listeners, any of which
393
+ // can throw, so the window is real.
394
+ //
395
+ // And clearing the cookie is not enough: the token was PERSISTED,
396
+ // and its value reached the wire, where it may have been captured
397
+ // — a proxy log, an already-flushed response. Revoking the row is
398
+ // what makes a failed sign-in leave nothing usable behind.
399
+ if (issued !== undefined) await this.#revokeRememberMe(issued);
400
+ throw err;
401
+ }
402
+ }
403
+
404
+ /** Undo an issued remember-me: the stored row first, then the cookie. */
405
+ async #revokeRememberMe(value: string): Promise<void> {
406
+ const strategy = strategyOrUndefined(this.#auth, this.#name);
407
+ if (strategy && isRememberMeIssuer(strategy)) {
408
+ // Best-effort: a store that is itself down must not replace the
409
+ // caller's error with its own.
410
+ await strategy.revokeRememberMeToken(value).catch(() => undefined);
411
+ }
412
+ this.#clearRememberMe();
413
+ }
414
+
415
+ /**
416
+ * Mint the token and put it in the browser, or say why it cannot.
417
+ *
418
+ * Returns the minted value so a failure further along can revoke it: a
419
+ * persisted token nobody can reach is still a credential.
420
+ */
421
+ async #issueRememberMe(user: UserPayload): Promise<string> {
422
+ const strategy = strategyOrUndefined(this.#auth, this.#name);
423
+ if (!strategy || !isRememberMeIssuer(strategy)) {
424
+ throw new WardenError(
425
+ "REMEMBER_ME_UNAVAILABLE",
426
+ `Guard '${this.#name}' cannot keep a user signed in: no remember-me tokens are configured.`,
427
+ {
428
+ hint: "Set `rememberMeTokens` on the session guard, or call login(user) without the remember flag.",
429
+ },
430
+ );
431
+ }
432
+ const value = await strategy.issueRememberMeToken(user);
433
+ if (value === null) {
434
+ throw new WardenError(
435
+ "REMEMBER_ME_UNAVAILABLE",
436
+ `Guard '${this.#name}' cannot keep a user signed in: no remember-me tokens are configured.`,
437
+ {
438
+ hint: "Set `rememberMeTokens` on the session guard, or call login(user) without the remember flag.",
439
+ },
440
+ );
441
+ }
442
+ const write = this.#ctx.response.encryptedCookie;
443
+ if (!write) {
444
+ throw new WardenError(
445
+ "REMEMBER_ME_UNAVAILABLE",
446
+ "This host cannot write an encrypted cookie, which is where the remember-me token lives.",
447
+ {
448
+ hint: "Use a host whose response exposes encryptedCookie(), or call login(user) without the remember flag.",
449
+ },
450
+ );
451
+ }
452
+ try {
453
+ write.call(this.#ctx.response, strategy.rememberMeCookieName, value, {
454
+ maxAge: strategy.rememberMeAgeSeconds,
455
+ httpOnly: true,
456
+ });
457
+ } catch (err) {
458
+ // The row exists and the browser will never hold it: a credential
459
+ // nobody can reach is still one, so it does not survive the failure.
460
+ await strategy.revokeRememberMeToken(value).catch(() => undefined);
461
+ throw err;
462
+ }
463
+ return value;
464
+ }
465
+
466
+ /** Drop whatever remember-me cookie the browser is still holding. */
467
+ #clearRememberMe(): void {
468
+ const strategy = strategyOrUndefined(this.#auth, this.#name);
469
+ if (!strategy || !isRememberMeIssuer(strategy)) return;
470
+ this.#ctx.response.clearCookie?.call(
471
+ this.#ctx.response,
472
+ strategy.rememberMeCookieName,
473
+ );
220
474
  }
221
475
 
222
476
  /** Log the current user out of this guard (session guards). */
223
477
  logout(): Promise<void> {
224
- return this.#auth.logout(this.#requireSession(), this.#name);
478
+ return this.#auth.logout(this.#requireSession(), this.#name, this.#state);
225
479
  }
226
480
 
227
481
  #requireSession(): SessionStore {
@@ -337,7 +591,7 @@ export class Authenticator {
337
591
  * Authenticate by trying the given guards in order (default: the default
338
592
  * guard). Sets the user on the first success; throws `E_UNAUTHORIZED_ACCESS`
339
593
  * (401, carrying `redirectTo` for session guards) when all reject, or a
340
- * `WARDEN_AUTH_STRATEGY_ERROR` (500) when every attempted guard crashed.
594
+ * `E_WARDEN_AUTH_STRATEGY_ERROR` (500) when every attempted guard crashed.
341
595
  */
342
596
  async authenticateUsing(
343
597
  guards?: string[],
@@ -355,12 +609,29 @@ export class Authenticator {
355
609
  { guardName },
356
610
  );
357
611
  const creds = extractCredentials(this.#ctx, this.#auth);
358
- const hasSessionStrategy = names.includes("session");
359
- const { result, viaGuard, attemptCount, crashCount } =
360
- await tryAuthenticate(this.#auth, names, {
361
- ...creds,
362
- hasSessionStrategy,
363
- });
612
+ // Same rule as the loop above: a session guard is one that verifies from
613
+ // the request context. Matching the literal name meant a guard called
614
+ // `web` never got the login redirect a browser needs.
615
+ const hasSessionStrategy = names.some((name) =>
616
+ isSessionGuard(this.#auth, name),
617
+ );
618
+ const attempt = await tryAuthenticate(this.#auth, names, creds);
619
+ const { attemptCount, crashCount } = attempt;
620
+ let result = attempt.result;
621
+ let viaGuard = attempt.viaGuard;
622
+
623
+ // No credential answered, but the browser may still hold a remember-me
624
+ // cookie — that is what "keep me signed in" means, and nothing read it.
625
+ if (!result?.authenticated && hasSessionStrategy) {
626
+ for (const name of names) {
627
+ const user = await this.use(name).tryRememberMeCookie();
628
+ if (user) {
629
+ result = { authenticated: true, user };
630
+ viaGuard = name;
631
+ break;
632
+ }
633
+ }
634
+ }
364
635
 
365
636
  if (result?.authenticated && result.user) {
366
637
  this.#user = result.user;
@@ -42,7 +42,7 @@ export default class WardenProvider {
42
42
  const hasGuards = config?.guards && Object.keys(config.guards).length > 0;
43
43
  if (!hasGuards && !config?.jwt && !config?.session && !config?.apiKey) {
44
44
  throw new WardenError(
45
- "WARDEN_NO_AUTH_CONFIG",
45
+ "E_WARDEN_NO_AUTH_CONFIG",
46
46
  `@c9up/warden: no authentication guards configured. Set config.warden.auth.guards (AdonisJS form) or at least one of .jwt / .session / .apiKey in your reamrc.ts before registering WardenProvider.`,
47
47
  );
48
48
  }
@@ -5,7 +5,7 @@
5
5
  * 2026-06-01): standalone abilities via `Bouncer.ability`, class-based policies
6
6
  * via `with(Policy)`, the four verbs `allows`/`denies`/`authorize`/`execute`,
7
7
  * and guest-denied-by-default. The user is `UserPayload | null` (guest = null,
8
- * D3); `authorize` throws `WARDEN_AUTHORIZATION_FAILURE` carrying `status: 403`
8
+ * D3); `authorize` throws `AUTHORIZATION_FAILURE` carrying `status: 403`
9
9
  * (D2). 56.2 ships PURE mechanics — it does NOT consult the Layer-1
10
10
  * `RightsResolver` (D4); abilities/policy methods receive `(user, ...args)` and
11
11
  * the developer writes the predicate, exactly as Adonis does.
@@ -320,7 +320,7 @@ export class Bouncer {
320
320
  return !(await this.#evaluateAbility(ability, args)).authorized;
321
321
  }
322
322
 
323
- /** Resolves on allow; throws `WARDEN_AUTHORIZATION_FAILURE` on deny (D2). */
323
+ /** Resolves on allow; throws `AUTHORIZATION_FAILURE` on deny (D2). */
324
324
  authorize<Args extends unknown[]>(
325
325
  ability: Ability<Args>,
326
326
  ...args: Args
@@ -144,7 +144,7 @@ export class PolicyAuthorizer {
144
144
  return !(await this.execute(action, ...args)).authorized;
145
145
  }
146
146
 
147
- /** Resolves on allow; throws `WARDEN_AUTHORIZATION_FAILURE` on deny (D2). */
147
+ /** Resolves on allow; throws `AUTHORIZATION_FAILURE` on deny (D2). */
148
148
  async authorize(action: string, ...args: unknown[]): Promise<void> {
149
149
  const response = await this.execute(action, ...args);
150
150
  if (!response.authorized) {
package/src/config.ts CHANGED
@@ -61,7 +61,14 @@ export interface JwtConfig {
61
61
  * A guard entry in the AdonisJS-style config — an {@link AuthStrategy} instance,
62
62
  * built via {@link jwtGuard}/{@link sessionGuard}/{@link apiKeyGuard}. Named a
63
63
  * "factory" for AdonisJS symmetry (`sessionGuard({...})`), though Warden guards
64
- * are shared per-app instances (the per-request state lives on the Authenticator).
64
+ * are shared per-app instances rather than one built per request.
65
+ *
66
+ * Because the instance is shared, a guard must hold NO per-request state: the
67
+ * flags a request asks about — `viaRemember`, `attemptedViaRemember`,
68
+ * `isLoggedOut` — live on the per-request guard the Authenticator hands out
69
+ * (`auth.use(name)`), and a strategy method records into the state it is
70
+ * given. A flag stored on the strategy would answer the next request with the
71
+ * previous one's truth.
65
72
  */
66
73
  export type GuardFactory = AuthStrategy;
67
74
 
package/src/errors.ts CHANGED
@@ -18,13 +18,17 @@ export class WardenError extends Error {
18
18
  ) {
19
19
  super(message);
20
20
  this.name = "WardenError";
21
- // Warden's own codes carry the `WARDEN_` namespace. The AdonisJS auth
22
- // identifiers (`E_UNAUTHORIZED_ACCESS`, `E_INVALID_CREDENTIALS`) are
23
- // PRESERVED verbatim so the exposed `.code` matches Adonis exactly — a
24
- // consumer branching on `error.code === 'E_UNAUTHORIZED_ACCESS'` (or a
25
- // framework mapping the Adonis id) sees the same string it would under
26
- // `@adonisjs/auth`. Documented deviation from the blanket prefix.
27
- this.code = code.startsWith("E_") ? code : `WARDEN_${code}`;
21
+ // Warden's own codes are namespaced `E_WARDEN_`: `E_` because every
22
+ // framework code carries it, the package name because `E_FORBIDDEN`
23
+ // alone would mean three different things across the ecosystem and an
24
+ // application could not tell them apart.
25
+ //
26
+ // The AdonisJS auth identifiers (`E_UNAUTHORIZED_ACCESS`,
27
+ // `E_INVALID_CREDENTIALS`) are PRESERVED verbatim — they already start
28
+ // with `E_` and fall through untouched — so a consumer branching on
29
+ // `error.code === 'E_UNAUTHORIZED_ACCESS'` sees the same string it
30
+ // would under `@adonisjs/auth`.
31
+ this.code = code.startsWith("E_") ? code : `E_WARDEN_${code}`;
28
32
  this.hint = options?.hint;
29
33
  this.status = options?.status;
30
34
  }
package/src/index.ts CHANGED
@@ -44,7 +44,10 @@ export type {
44
44
  BouncerEmitter,
45
45
  PolicyContainerResolver,
46
46
  } from "./bouncer/types.js";
47
- export type { GuardFactory, WardenConfig } from "./config.js";
47
+ export type {
48
+ GuardFactory,
49
+ WardenConfig,
50
+ } from "./config.js";
48
51
  export {
49
52
  apiKeyGuard,
50
53
  basicAuthGuard,
@@ -58,15 +61,6 @@ export {
58
61
  E_UNAUTHORIZED_ACCESS,
59
62
  WardenError,
60
63
  } from "./errors.js";
61
- export { GitHubDriver } from "./firstcontact/drivers/GitHubDriver.js";
62
- export { GoogleDriver } from "./firstcontact/drivers/GoogleDriver.js";
63
- export { FirstContactManager } from "./firstcontact/FirstContactManager.js";
64
- export type {
65
- FirstContactDriver,
66
- OAuthConfig,
67
- OAuthToken,
68
- OAuthUser,
69
- } from "./firstcontact/types.js";
70
64
  export {
71
65
  Guard,
72
66
  getGuardMetadata,
@@ -178,9 +172,13 @@ export {
178
172
  export type { JwtClaims, JwtStrategyConfig } from "./strategies/JwtStrategy.js";
179
173
  export { generateJwtSecret, JwtStrategy } from "./strategies/JwtStrategy.js";
180
174
  export type {
175
+ SessionGuardState,
181
176
  SessionStore,
182
177
  SessionStrategyConfig,
183
178
  } from "./strategies/SessionStrategy.js";
184
- export { SessionStrategy } from "./strategies/SessionStrategy.js";
179
+ export {
180
+ createSessionGuardState,
181
+ SessionStrategy,
182
+ } from "./strategies/SessionStrategy.js";
185
183
  export type { BlacklistDriver } from "./TokenBlacklist.js";
186
184
  export { MemoryBlacklistDriver, TokenBlacklist } from "./TokenBlacklist.js";
package/src/middleware.ts CHANGED
@@ -101,6 +101,8 @@ export interface WardenContext {
101
101
  request: {
102
102
  /** Ream's `HttpContext` exposes headers as a METHOD, not a property. */
103
103
  headers(): Record<string, string>;
104
+ /** Read the encrypted remember-me cookie back. Optional, like its writer. */
105
+ encryptedCookie?: (name: string) => string | null;
104
106
  };
105
107
  /**
106
108
  * Per-request IoC resolver (Ream's `ctx.containerResolver`). Warden resolves
@@ -111,6 +113,21 @@ export interface WardenContext {
111
113
  response: {
112
114
  status: (code: number) => unknown;
113
115
  json: (data: unknown) => void;
116
+ /**
117
+ * Write an ENCRYPTED cookie, for the remember-me token. Optional: a
118
+ * host without it simply cannot offer "keep me signed in", and
119
+ * `login(user, true)` says so rather than pretending.
120
+ *
121
+ * Encrypted and not merely signed, because the value IS the credential
122
+ * — anyone who reads it can present it.
123
+ */
124
+ encryptedCookie?: (
125
+ name: string,
126
+ value: string,
127
+ options?: Record<string, unknown>,
128
+ ) => unknown;
129
+ /** Drop a cookie (used to clear the remember-me one). */
130
+ clearCookie?: (name: string, options?: Record<string, unknown>) => unknown;
114
131
  /**
115
132
  * Redirect the response (Ream's `ctx.response.redirect`). Optional so a
116
133
  * minimal host without it still gets the 401 JSON fallback — Warden does
@@ -239,7 +256,7 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
239
256
  // inline handlers use via `ctx.auth.authenticate()`), so the decorator path
240
257
  // and the functional path share one code path. It sets `ctx.auth` and throws
241
258
  // on failure — E_UNAUTHORIZED_ACCESS (401, credential rejection) or a
242
- // WARDEN_AUTH_STRATEGY_ERROR (500, every attempted guard crashed).
259
+ // E_WARDEN_AUTH_STRATEGY_ERROR (500, every attempted guard crashed).
243
260
  const authenticator = ensureAuthenticator(ctx, auth);
244
261
  const loginRoute = await resolveLoginRoute(ctx);
245
262
  try {
@@ -254,7 +271,7 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
254
271
  if (err instanceof WardenError && err.status === 500) {
255
272
  ctx.response.status(500);
256
273
  ctx.response.json({
257
- error: { code: "AUTH_STRATEGY_ERROR", message: err.message },
274
+ error: { code: "E_WARDEN_AUTH_STRATEGY_ERROR", message: err.message },
258
275
  });
259
276
  return;
260
277
  }
@@ -278,7 +295,9 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
278
295
  );
279
296
  if (denied) {
280
297
  ctx.response.status(403);
281
- ctx.response.json({ error: { code: "FORBIDDEN", message: denied } });
298
+ ctx.response.json({
299
+ error: { code: "E_WARDEN_FORBIDDEN", message: denied },
300
+ });
282
301
  return;
283
302
  }
284
303
 
@@ -288,7 +307,7 @@ export async function wardenMiddleware(ctx: WardenContext, next: WardenNext) {
288
307
  ctx.response.status(403);
289
308
  ctx.response.json({
290
309
  error: {
291
- code: "MFA_REQUIRED",
310
+ code: "E_WARDEN_MFA_REQUIRED",
292
311
  message: "Multi-factor authentication is required for this action.",
293
312
  },
294
313
  });
@@ -428,7 +447,7 @@ export interface BouncerRegistry {
428
447
  * from the authenticated user (`ctx.auth?.user`, or `null` for a guest), the
429
448
  * shared `RightsResolver`, and the registered abilities/policies, then attaches
430
449
  * it as `ctx.bouncer`. Handlers authorize via `await ctx.bouncer.authorize(...)`
431
- * (throws `WARDEN_AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
450
+ * (throws `AUTHORIZATION_FAILURE` carrying `status: 403`, which the host's
432
451
  * ExceptionHandler maps to a 403 response) or branch on `ctx.bouncer.allows(...)`.
433
452
  *
434
453
  * Unlike `wardenMiddleware` (a per-route GUARD that short-circuits public
package/src/native.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Warden NAPI loader — loads the `warden-engine-napi` binary for Rust-native
3
3
  * JWT/HMAC/random operations. There is no TS fallback: when the binary is
4
4
  * absent, `nativeWarden()` returns `undefined` and `JwtStrategy` (and any
5
- * other consumer) throws `WARDEN_NAPI_REQUIRED` at use time. Password
5
+ * other consumer) throws `E_WARDEN_NAPI_REQUIRED` at use time. Password
6
6
  * hashing is the sole responsibility of `@c9up/sigil` (story 40.1).
7
7
  */
8
8
  import { createRequire } from "node:module";
@@ -38,7 +38,7 @@ try {
38
38
  native = nodeRequire(join(currentDir, `../index.${suffix}.node`));
39
39
  }
40
40
  } catch {
41
- // Binary not available — JwtStrategy will throw WARDEN_NAPI_REQUIRED at use time.
41
+ // Binary not available — JwtStrategy will throw E_WARDEN_NAPI_REQUIRED at use time.
42
42
  }
43
43
 
44
44
  /** Whether the Rust NAPI engine loaded. */
package/src/standalone.ts CHANGED
@@ -107,7 +107,7 @@ export function createWarden(config: WardenConfig): Warden {
107
107
  .status(401)
108
108
  .json({
109
109
  error: {
110
- code: "UNAUTHORIZED",
110
+ code: "E_WARDEN_UNAUTHORIZED",
111
111
  message: "Missing authentication token",
112
112
  },
113
113
  });
@@ -122,7 +122,7 @@ export function createWarden(config: WardenConfig): Warden {
122
122
  .status(401)
123
123
  .json({
124
124
  error: {
125
- code: "UNAUTHORIZED",
125
+ code: "E_WARDEN_UNAUTHORIZED",
126
126
  message: result.error ?? "Authentication failed",
127
127
  },
128
128
  });
@@ -138,7 +138,7 @@ export function createWarden(config: WardenConfig): Warden {
138
138
  .status(500)
139
139
  .json({
140
140
  error: {
141
- code: "AUTH_ERROR",
141
+ code: "E_WARDEN_AUTH_ERROR",
142
142
  message: "Internal authentication error",
143
143
  },
144
144
  });
@@ -34,7 +34,7 @@ function sign(payload: JwtClaims, secret: string): string {
34
34
  const rust = nativeWarden();
35
35
  if (!rust) {
36
36
  throw new Error(
37
- "[WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
37
+ "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
38
38
  );
39
39
  }
40
40
  return rust.jwtSign(JSON.stringify(payload), secret);
@@ -44,7 +44,7 @@ function verify(token: string, secret: string): JwtClaims | null {
44
44
  const rust = nativeWarden();
45
45
  if (!rust) {
46
46
  throw new Error(
47
- "[WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
47
+ "[E_WARDEN_NAPI_REQUIRED] The Rust warden-engine binary is required. Build it with `cd packages/warden && pnpm build:napi`.",
48
48
  );
49
49
  }
50
50
  try {