@revealui/auth 0.2.1 → 0.3.0

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 (75) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/react/index.d.ts +4 -0
  3. package/dist/react/index.d.ts.map +1 -1
  4. package/dist/react/index.js +2 -0
  5. package/dist/react/useMFA.d.ts +83 -0
  6. package/dist/react/useMFA.d.ts.map +1 -0
  7. package/dist/react/useMFA.js +182 -0
  8. package/dist/react/usePasskey.d.ts +88 -0
  9. package/dist/react/usePasskey.d.ts.map +1 -0
  10. package/dist/react/usePasskey.js +203 -0
  11. package/dist/react/useSession.d.ts.map +1 -1
  12. package/dist/react/useSession.js +16 -5
  13. package/dist/react/useSignIn.d.ts +9 -3
  14. package/dist/react/useSignIn.d.ts.map +1 -1
  15. package/dist/react/useSignIn.js +32 -10
  16. package/dist/react/useSignOut.d.ts.map +1 -1
  17. package/dist/react/useSignUp.d.ts.map +1 -1
  18. package/dist/react/useSignUp.js +25 -9
  19. package/dist/server/auth.d.ts.map +1 -1
  20. package/dist/server/auth.js +75 -4
  21. package/dist/server/brute-force.d.ts +10 -1
  22. package/dist/server/brute-force.d.ts.map +1 -1
  23. package/dist/server/brute-force.js +17 -3
  24. package/dist/server/errors.d.ts.map +1 -1
  25. package/dist/server/index.d.ts +16 -6
  26. package/dist/server/index.d.ts.map +1 -1
  27. package/dist/server/index.js +11 -5
  28. package/dist/server/magic-link.d.ts +52 -0
  29. package/dist/server/magic-link.d.ts.map +1 -0
  30. package/dist/server/magic-link.js +111 -0
  31. package/dist/server/mfa.d.ts +87 -0
  32. package/dist/server/mfa.d.ts.map +1 -0
  33. package/dist/server/mfa.js +263 -0
  34. package/dist/server/oauth.d.ts +37 -0
  35. package/dist/server/oauth.d.ts.map +1 -1
  36. package/dist/server/oauth.js +135 -3
  37. package/dist/server/passkey.d.ts +132 -0
  38. package/dist/server/passkey.d.ts.map +1 -0
  39. package/dist/server/passkey.js +257 -0
  40. package/dist/server/password-reset.d.ts +15 -0
  41. package/dist/server/password-reset.d.ts.map +1 -1
  42. package/dist/server/password-reset.js +44 -1
  43. package/dist/server/password-validation.d.ts.map +1 -1
  44. package/dist/server/providers/github.d.ts.map +1 -1
  45. package/dist/server/providers/github.js +18 -2
  46. package/dist/server/providers/google.d.ts.map +1 -1
  47. package/dist/server/providers/google.js +18 -2
  48. package/dist/server/providers/vercel.d.ts.map +1 -1
  49. package/dist/server/providers/vercel.js +18 -2
  50. package/dist/server/rate-limit.d.ts +10 -1
  51. package/dist/server/rate-limit.d.ts.map +1 -1
  52. package/dist/server/rate-limit.js +61 -43
  53. package/dist/server/session.d.ts +48 -1
  54. package/dist/server/session.d.ts.map +1 -1
  55. package/dist/server/session.js +125 -6
  56. package/dist/server/signed-cookie.d.ts +32 -0
  57. package/dist/server/signed-cookie.d.ts.map +1 -0
  58. package/dist/server/signed-cookie.js +67 -0
  59. package/dist/server/storage/database.d.ts +1 -1
  60. package/dist/server/storage/database.d.ts.map +1 -1
  61. package/dist/server/storage/database.js +15 -7
  62. package/dist/server/storage/in-memory.d.ts.map +1 -1
  63. package/dist/server/storage/in-memory.js +7 -7
  64. package/dist/server/storage/index.d.ts +11 -3
  65. package/dist/server/storage/index.d.ts.map +1 -1
  66. package/dist/server/storage/index.js +18 -4
  67. package/dist/server/storage/interface.d.ts +1 -1
  68. package/dist/server/storage/interface.d.ts.map +1 -1
  69. package/dist/server/storage/interface.js +1 -1
  70. package/dist/types.d.ts +20 -8
  71. package/dist/types.d.ts.map +1 -1
  72. package/dist/types.js +2 -2
  73. package/dist/utils/database.d.ts.map +1 -1
  74. package/dist/utils/database.js +9 -2
  75. package/package.json +26 -8
@@ -2,7 +2,7 @@
2
2
  * Rate Limiting Utilities
3
3
  *
4
4
  * Rate limiting for authentication endpoints using storage abstraction.
5
- * Supports in-memory (dev), Redis (production), or database (fallback).
5
+ * Supports in-memory (dev) or database (production) backends.
6
6
  */
7
7
  import { getStorage } from './storage/index.js';
8
8
  const DEFAULT_CONFIG = {
@@ -10,6 +10,20 @@ const DEFAULT_CONFIG = {
10
10
  windowMs: 15 * 60 * 1000, // 15 minutes
11
11
  blockDurationMs: 30 * 60 * 1000, // 30 minutes block after max attempts
12
12
  };
13
+ let globalConfig = { ...DEFAULT_CONFIG };
14
+ /**
15
+ * Override default rate limit configuration globally.
16
+ * Per-call config parameters still take precedence.
17
+ */
18
+ export function configureRateLimit(overrides) {
19
+ globalConfig = { ...DEFAULT_CONFIG, ...overrides };
20
+ }
21
+ /**
22
+ * Reset rate limit configuration to defaults (for testing).
23
+ */
24
+ export function resetRateLimitConfig() {
25
+ globalConfig = { ...DEFAULT_CONFIG };
26
+ }
13
27
  /**
14
28
  * Serialize rate limit entry to string
15
29
  */
@@ -43,54 +57,58 @@ function getStorageKey(key) {
43
57
  * @param config - Rate limit configuration
44
58
  * @returns Rate limit result
45
59
  */
46
- export async function checkRateLimit(key, config = DEFAULT_CONFIG) {
60
+ export async function checkRateLimit(key, config = globalConfig) {
47
61
  const storage = getStorage();
48
62
  const storageKey = getStorageKey(key);
49
63
  const now = Date.now();
50
- // Get existing entry
51
- const entryData = await storage.get(storageKey);
52
- let entry = deserializeEntry(entryData);
53
- // Clean up expired entries
54
- if (entry && entry.resetAt < now) {
55
- await storage.del(storageKey);
56
- entry = null;
57
- }
58
- // Get or create entry
59
- const currentEntry = entry || {
60
- count: 0,
61
- resetAt: now + config.windowMs,
62
- };
63
- // Check if blocked
64
- if (config.blockDurationMs && currentEntry.count >= config.maxAttempts) {
65
- const blockUntil = now + config.blockDurationMs;
66
- // Extend the storage TTL so the entry outlives the block period.
67
- // Without this, the entry expires at resetAt (end of the rate-limit window)
68
- // before the block expires, letting the user back in prematurely.
69
- const blockTtlSeconds = Math.ceil(config.blockDurationMs / 1000);
70
- await storage.set(storageKey, serializeEntry(currentEntry), blockTtlSeconds);
71
- return {
72
- allowed: false,
73
- remaining: 0,
74
- resetAt: blockUntil,
64
+ // Use atomicUpdate to avoid the read-modify-write race condition.
65
+ // The result is captured via closure since atomicUpdate returns void.
66
+ let result;
67
+ const updater = (entryData) => {
68
+ let entry = deserializeEntry(entryData);
69
+ // Clean up expired entries
70
+ if (entry && entry.resetAt < now) {
71
+ entry = null;
72
+ }
73
+ // Get or create entry
74
+ const currentEntry = entry || {
75
+ count: 0,
76
+ resetAt: now + config.windowMs,
75
77
  };
76
- }
77
- // Check if within window
78
- if (currentEntry.count >= config.maxAttempts) {
79
- return {
80
- allowed: false,
81
- remaining: 0,
78
+ // Check if blocked
79
+ if (config.blockDurationMs && currentEntry.count >= config.maxAttempts) {
80
+ const blockUntil = now + config.blockDurationMs;
81
+ const blockTtlSeconds = Math.ceil(config.blockDurationMs / 1000);
82
+ result = { allowed: false, remaining: 0, resetAt: blockUntil };
83
+ return { value: serializeEntry(currentEntry), ttlSeconds: blockTtlSeconds };
84
+ }
85
+ // Check if within window
86
+ if (currentEntry.count >= config.maxAttempts) {
87
+ const ttlSeconds = Math.ceil((currentEntry.resetAt - now) / 1000);
88
+ result = { allowed: false, remaining: 0, resetAt: currentEntry.resetAt };
89
+ return { value: serializeEntry(currentEntry), ttlSeconds };
90
+ }
91
+ // Increment and update
92
+ currentEntry.count++;
93
+ const ttlSeconds = Math.ceil((currentEntry.resetAt - now) / 1000);
94
+ result = {
95
+ allowed: true,
96
+ remaining: config.maxAttempts - currentEntry.count,
82
97
  resetAt: currentEntry.resetAt,
83
98
  };
84
- }
85
- // Increment and update
86
- currentEntry.count++;
87
- const ttlSeconds = Math.ceil((currentEntry.resetAt - now) / 1000);
88
- await storage.set(storageKey, serializeEntry(currentEntry), ttlSeconds);
89
- return {
90
- allowed: true,
91
- remaining: config.maxAttempts - currentEntry.count,
92
- resetAt: currentEntry.resetAt,
99
+ return { value: serializeEntry(currentEntry), ttlSeconds };
93
100
  };
101
+ if (storage.atomicUpdate) {
102
+ await storage.atomicUpdate(storageKey, updater);
103
+ }
104
+ else {
105
+ // Fallback for storage backends without atomicUpdate
106
+ const existing = await storage.get(storageKey);
107
+ const { value, ttlSeconds } = updater(existing);
108
+ await storage.set(storageKey, value, ttlSeconds);
109
+ }
110
+ // biome-ignore lint/style/noNonNullAssertion: result is always assigned by updater before this point
111
+ return result;
94
112
  }
95
113
  /**
96
114
  * Resets rate limit for a key
@@ -109,7 +127,7 @@ export async function resetRateLimit(key) {
109
127
  * @param config - Rate limit configuration
110
128
  * @returns Rate limit status
111
129
  */
112
- export async function getRateLimitStatus(key, config = DEFAULT_CONFIG) {
130
+ export async function getRateLimitStatus(key, config = globalConfig) {
113
131
  const storage = getStorage();
114
132
  const storageKey = getStorageKey(key);
115
133
  const now = Date.now();
@@ -5,6 +5,30 @@
5
5
  * Sessions are stored in PostgreSQL and validated on each request.
6
6
  */
7
7
  import type { Session, User } from '../types.js';
8
+ export interface SessionBindingConfig {
9
+ /** Invalidate session when user-agent changes (default: true) */
10
+ enforceUserAgent: boolean;
11
+ /** Invalidate session when IP address changes (default: false — users roam) */
12
+ enforceIp: boolean;
13
+ /** Log a warning when IP changes but don't invalidate (default: true) */
14
+ warnOnIpChange: boolean;
15
+ }
16
+ /** Override session binding behaviour (useful for tests or strict deployments). */
17
+ export declare function configureSessionBinding(overrides: Partial<SessionBindingConfig>): void;
18
+ /** Reset to defaults (for tests). */
19
+ export declare function resetSessionBindingConfig(): void;
20
+ export interface RequestContext {
21
+ userAgent?: string;
22
+ ipAddress?: string;
23
+ }
24
+ /**
25
+ * Validate that the current request context matches the session's stored
26
+ * binding values (IP address, user-agent).
27
+ *
28
+ * @returns `null` when the session is valid, or a reason string when it should
29
+ * be invalidated.
30
+ */
31
+ export declare function validateSessionBinding(session: Session, ctx: RequestContext): string | null;
8
32
  export interface SessionData {
9
33
  session: Session;
10
34
  user: User;
@@ -13,9 +37,10 @@ export interface SessionData {
13
37
  * Get session from request headers (cookie)
14
38
  *
15
39
  * @param headers - Request headers containing cookies
40
+ * @param requestContext - Optional IP / user-agent for session binding validation
16
41
  * @returns Session data with user, or null if invalid/expired
17
42
  */
18
- export declare function getSession(headers: Headers): Promise<SessionData | null>;
43
+ export declare function getSession(headers: Headers, requestContext?: RequestContext): Promise<SessionData | null>;
19
44
  /**
20
45
  * Create a new session for a user
21
46
  *
@@ -27,6 +52,28 @@ export declare function createSession(userId: string, options?: {
27
52
  persistent?: boolean;
28
53
  userAgent?: string;
29
54
  ipAddress?: string;
55
+ expiresAt?: Date;
56
+ metadata?: Record<string, unknown>;
57
+ }): Promise<{
58
+ token: string;
59
+ session: Session;
60
+ }>;
61
+ /**
62
+ * Rotate a user's session to prevent session fixation attacks.
63
+ *
64
+ * Deletes the old session (by token hash) or all sessions for the user,
65
+ * then creates a fresh session with a new token.
66
+ *
67
+ * @param userId - User ID to rotate sessions for
68
+ * @param options - Rotation options
69
+ * @returns New session token and session data
70
+ */
71
+ export declare function rotateSession(userId: string, options?: {
72
+ /** Raw token of the old session to invalidate. When omitted, all user sessions are deleted. */
73
+ oldSessionToken?: string;
74
+ persistent?: boolean;
75
+ userAgent?: string;
76
+ ipAddress?: string;
30
77
  }): Promise<{
31
78
  token: string;
32
79
  session: Session;
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAIhD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,EAAE,IAAI,CAAA;CACX;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAsF9E;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;IACR,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,GACA,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,CAgE9C;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAmBtE;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyBzE"}
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/server/session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAQjD,MAAM,WAAW,oBAAoB;IACnC,iEAAiE;IACjE,gBAAgB,EAAE,OAAO,CAAC;IAC1B,+EAA+E;IAC/E,SAAS,EAAE,OAAO,CAAC;IACnB,yEAAyE;IACzE,cAAc,EAAE,OAAO,CAAC;CACzB;AAUD,mFAAmF;AACnF,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,OAAO,CAAC,oBAAoB,CAAC,GAAG,IAAI,CAEtF;AAED,qCAAqC;AACrC,wBAAgB,yBAAyB,IAAI,IAAI,CAEhD;AAMD,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,cAAc,GAAG,MAAM,GAAG,IAAI,CA0B3F;AAMD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,IAAI,CAAC;CACZ;AAED;;;;;;GAMG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,OAAO,EAChB,cAAc,CAAC,EAAE,cAAc,GAC9B,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CA4G7B;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;IACR,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,IAAI,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GACA,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,CAmE9C;AAED;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;IACR,+FAA+F;IAC/F,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GACA,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,CAoC9C;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAoBtE;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyBzE"}
@@ -7,16 +7,61 @@
7
7
  import { logger } from '@revealui/core/observability/logger';
8
8
  import { getClient } from '@revealui/db/client';
9
9
  import { sessions, users } from '@revealui/db/schema';
10
- import { and, eq, gt } from 'drizzle-orm';
10
+ import { and, eq, gt, isNull } from 'drizzle-orm';
11
11
  import { hashToken } from '../utils/token.js';
12
12
  import { DatabaseError, TokenError } from './errors.js';
13
+ const DEFAULT_SESSION_BINDING = {
14
+ enforceUserAgent: true,
15
+ enforceIp: false,
16
+ warnOnIpChange: true,
17
+ };
18
+ let sessionBindingConfig = { ...DEFAULT_SESSION_BINDING };
19
+ /** Override session binding behaviour (useful for tests or strict deployments). */
20
+ export function configureSessionBinding(overrides) {
21
+ sessionBindingConfig = { ...DEFAULT_SESSION_BINDING, ...overrides };
22
+ }
23
+ /** Reset to defaults (for tests). */
24
+ export function resetSessionBindingConfig() {
25
+ sessionBindingConfig = { ...DEFAULT_SESSION_BINDING };
26
+ }
27
+ /**
28
+ * Validate that the current request context matches the session's stored
29
+ * binding values (IP address, user-agent).
30
+ *
31
+ * @returns `null` when the session is valid, or a reason string when it should
32
+ * be invalidated.
33
+ */
34
+ export function validateSessionBinding(session, ctx) {
35
+ // User-agent enforcement
36
+ if (sessionBindingConfig.enforceUserAgent &&
37
+ ctx.userAgent &&
38
+ session.userAgent &&
39
+ ctx.userAgent !== session.userAgent) {
40
+ return 'user-agent mismatch';
41
+ }
42
+ // IP enforcement / warning
43
+ if (ctx.ipAddress && session.ipAddress && ctx.ipAddress !== session.ipAddress) {
44
+ if (sessionBindingConfig.enforceIp) {
45
+ return 'ip-address mismatch';
46
+ }
47
+ if (sessionBindingConfig.warnOnIpChange) {
48
+ logger.warn('Session IP changed', {
49
+ sessionId: session.id,
50
+ storedIp: session.ipAddress,
51
+ currentIp: ctx.ipAddress,
52
+ });
53
+ }
54
+ }
55
+ return null;
56
+ }
13
57
  /**
14
58
  * Get session from request headers (cookie)
15
59
  *
16
60
  * @param headers - Request headers containing cookies
61
+ * @param requestContext - Optional IP / user-agent for session binding validation
17
62
  * @returns Session data with user, or null if invalid/expired
18
63
  */
19
- export async function getSession(headers) {
64
+ export async function getSession(headers, requestContext) {
20
65
  try {
21
66
  const cookieHeader = headers.get('cookie');
22
67
  if (!cookieHeader) {
@@ -61,10 +106,32 @@ export async function getSession(headers) {
61
106
  if (!session) {
62
107
  return null;
63
108
  }
109
+ // Session binding validation (IP / user-agent)
110
+ if (requestContext) {
111
+ const bindingError = validateSessionBinding(session, requestContext);
112
+ if (bindingError) {
113
+ logger.warn('Session binding violation — invalidating session', {
114
+ sessionId: session.id,
115
+ reason: bindingError,
116
+ });
117
+ // Delete the compromised session
118
+ try {
119
+ await db.delete(sessions).where(eq(sessions.id, session.id));
120
+ }
121
+ catch {
122
+ logger.error('Failed to delete session after binding violation');
123
+ }
124
+ return null;
125
+ }
126
+ }
64
127
  // Get user data
65
128
  let user;
66
129
  try {
67
- const result = await db.select().from(users).where(eq(users.id, session.userId)).limit(1);
130
+ const result = await db
131
+ .select()
132
+ .from(users)
133
+ .where(and(eq(users.id, session.userId), isNull(users.deletedAt)))
134
+ .limit(1);
68
135
  user = result[0];
69
136
  }
70
137
  catch (error) {
@@ -128,9 +195,11 @@ export async function createSession(userId, options) {
128
195
  logger.error('Error generating session token');
129
196
  throw new TokenError('Failed to generate session token');
130
197
  }
131
- // Calculate expiration (7 days for persistent, 1 day for regular)
132
- const expiresAt = new Date();
133
- expiresAt.setDate(expiresAt.getDate() + (options?.persistent ? 7 : 1));
198
+ // Calculate expiration (custom override, 7 days for persistent, 1 day for regular)
199
+ const expiresAt = options?.expiresAt ?? new Date();
200
+ if (!options?.expiresAt) {
201
+ expiresAt.setDate(expiresAt.getDate() + (options?.persistent ? 7 : 1));
202
+ }
134
203
  // Create session in database
135
204
  let session;
136
205
  try {
@@ -145,6 +214,7 @@ export async function createSession(userId, options) {
145
214
  userAgent: options?.userAgent,
146
215
  ipAddress: options?.ipAddress,
147
216
  lastActivityAt: new Date(),
217
+ metadata: options?.metadata ?? null,
148
218
  })
149
219
  .returning();
150
220
  session = result[0];
@@ -171,6 +241,55 @@ export async function createSession(userId, options) {
171
241
  throw new DatabaseError('Unexpected error creating session', err);
172
242
  }
173
243
  }
244
+ /**
245
+ * Rotate a user's session to prevent session fixation attacks.
246
+ *
247
+ * Deletes the old session (by token hash) or all sessions for the user,
248
+ * then creates a fresh session with a new token.
249
+ *
250
+ * @param userId - User ID to rotate sessions for
251
+ * @param options - Rotation options
252
+ * @returns New session token and session data
253
+ */
254
+ export async function rotateSession(userId, options) {
255
+ try {
256
+ let db;
257
+ try {
258
+ db = getClient();
259
+ }
260
+ catch (error) {
261
+ logger.error('Error getting database client in rotateSession');
262
+ throw new DatabaseError('Database connection failed', error);
263
+ }
264
+ // Invalidate old session(s)
265
+ try {
266
+ if (options?.oldSessionToken) {
267
+ const oldTokenHash = hashToken(options.oldSessionToken);
268
+ await db.delete(sessions).where(eq(sessions.tokenHash, oldTokenHash));
269
+ }
270
+ else {
271
+ await db.delete(sessions).where(eq(sessions.userId, userId));
272
+ }
273
+ }
274
+ catch (error) {
275
+ logger.error('Error deleting old session(s) during rotation');
276
+ throw new DatabaseError('Failed to delete old session(s)', error);
277
+ }
278
+ // Create a fresh session
279
+ return await createSession(userId, {
280
+ persistent: options?.persistent,
281
+ userAgent: options?.userAgent,
282
+ ipAddress: options?.ipAddress,
283
+ });
284
+ }
285
+ catch (err) {
286
+ if (err instanceof DatabaseError || err instanceof TokenError) {
287
+ throw err;
288
+ }
289
+ logger.error('Unexpected error in rotateSession');
290
+ throw new DatabaseError('Unexpected error rotating session', err);
291
+ }
292
+ }
174
293
  /**
175
294
  * Delete a session (sign out)
176
295
  *
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Signed Cookie Utility
3
+ *
4
+ * Signs and verifies JSON payloads for stateless storage in httpOnly cookies.
5
+ * Used by MFA pre-auth flow and WebAuthn challenge flow.
6
+ *
7
+ * Format: base64url(JSON payload) + '.' + base64url(HMAC-SHA256 signature)
8
+ */
9
+ /**
10
+ * Sign a payload for storage in an httpOnly cookie.
11
+ * Format: base64url(JSON payload) + '.' + base64url(HMAC-SHA256 signature)
12
+ *
13
+ * @param payload - Must include `expiresAt` (Unix ms timestamp)
14
+ * @param secret - HMAC signing key (e.g., REVEALUI_SECRET)
15
+ * @returns Signed string safe for cookie value
16
+ */
17
+ export declare function signCookiePayload<T extends {
18
+ expiresAt: number;
19
+ }>(payload: T, secret: string): string;
20
+ /**
21
+ * Verify and decode a signed cookie payload.
22
+ * Returns null if: signature invalid, expired, or malformed.
23
+ * Uses timing-safe comparison to prevent timing attacks.
24
+ *
25
+ * @param signed - Signed cookie string from `signCookiePayload`
26
+ * @param secret - HMAC signing key (must match the one used to sign)
27
+ * @returns Decoded payload or null if invalid
28
+ */
29
+ export declare function verifyCookiePayload<T extends {
30
+ expiresAt: number;
31
+ }>(signed: string, secret: string): T | null;
32
+ //# sourceMappingURL=signed-cookie.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signed-cookie.d.ts","sourceRoot":"","sources":["../../src/server/signed-cookie.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,EAC/D,OAAO,EAAE,CAAC,EACV,MAAM,EAAE,MAAM,GACb,MAAM,CAQR;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,EACjE,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,CAAC,GAAG,IAAI,CAyCV"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Signed Cookie Utility
3
+ *
4
+ * Signs and verifies JSON payloads for stateless storage in httpOnly cookies.
5
+ * Used by MFA pre-auth flow and WebAuthn challenge flow.
6
+ *
7
+ * Format: base64url(JSON payload) + '.' + base64url(HMAC-SHA256 signature)
8
+ */
9
+ import crypto from 'node:crypto';
10
+ /**
11
+ * Sign a payload for storage in an httpOnly cookie.
12
+ * Format: base64url(JSON payload) + '.' + base64url(HMAC-SHA256 signature)
13
+ *
14
+ * @param payload - Must include `expiresAt` (Unix ms timestamp)
15
+ * @param secret - HMAC signing key (e.g., REVEALUI_SECRET)
16
+ * @returns Signed string safe for cookie value
17
+ */
18
+ export function signCookiePayload(payload, secret) {
19
+ const payloadJson = JSON.stringify(payload);
20
+ const payloadB64 = Buffer.from(payloadJson).toString('base64url');
21
+ const signature = crypto.createHmac('sha256', secret).update(payloadB64).digest();
22
+ const signatureB64 = signature.toString('base64url');
23
+ return `${payloadB64}.${signatureB64}`;
24
+ }
25
+ /**
26
+ * Verify and decode a signed cookie payload.
27
+ * Returns null if: signature invalid, expired, or malformed.
28
+ * Uses timing-safe comparison to prevent timing attacks.
29
+ *
30
+ * @param signed - Signed cookie string from `signCookiePayload`
31
+ * @param secret - HMAC signing key (must match the one used to sign)
32
+ * @returns Decoded payload or null if invalid
33
+ */
34
+ export function verifyCookiePayload(signed, secret) {
35
+ try {
36
+ if (!signed) {
37
+ return null;
38
+ }
39
+ const parts = signed.split('.');
40
+ if (parts.length !== 2) {
41
+ return null;
42
+ }
43
+ const [payloadB64, signatureB64] = parts;
44
+ // Recompute the expected signature
45
+ const expectedSignature = crypto.createHmac('sha256', secret).update(payloadB64).digest();
46
+ const actualSignature = Buffer.from(signatureB64, 'base64url');
47
+ // Timing-safe comparison — buffers must be same length
48
+ if (expectedSignature.length !== actualSignature.length) {
49
+ return null;
50
+ }
51
+ if (!crypto.timingSafeEqual(expectedSignature, actualSignature)) {
52
+ return null;
53
+ }
54
+ // Signature valid — decode and parse the payload
55
+ const payloadJson = Buffer.from(payloadB64, 'base64url').toString('utf8');
56
+ const payload = JSON.parse(payloadJson);
57
+ // Check expiry
58
+ if (typeof payload.expiresAt !== 'number' || payload.expiresAt <= Date.now()) {
59
+ return null;
60
+ }
61
+ return payload;
62
+ }
63
+ catch {
64
+ // Malformed input (bad base64, bad JSON, etc.) → null
65
+ return null;
66
+ }
67
+ }
@@ -2,7 +2,7 @@
2
2
  * Database Storage
3
3
  *
4
4
  * Database backend using Drizzle ORM
5
- * Slower than Redis but uses existing database infrastructure
5
+ * Uses existing database infrastructure with no external cache dependency
6
6
  */
7
7
  import type { Storage } from './interface.js';
8
8
  export declare class DatabaseStorage implements Storage {
@@ -1 +1 @@
1
- {"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../src/server/storage/database.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAE7C,qBAAa,eAAgB,YAAW,OAAO;IAC7C,OAAO,CAAC,EAAE,CAAU;gBAER,gBAAgB,CAAC,EAAE,MAAM;IAkB/B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAcxC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBnE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAOlC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAK3C;;;;OAIG;IACG,YAAY,CAChB,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAC1E,OAAO,CAAC,IAAI,CAAC;CAwBjB"}
1
+ {"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../src/server/storage/database.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAQH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAE9C,qBAAa,eAAgB,YAAW,OAAO;IAC7C,OAAO,CAAC,EAAE,CAAW;gBAET,gBAAgB,CAAC,EAAE,MAAM;IAkB/B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAcxC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBnE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IASlC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAK3C;;;;OAIG;IACG,YAAY,CAChB,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAC1E,OAAO,CAAC,IAAI,CAAC;CA6BjB"}
@@ -2,13 +2,14 @@
2
2
  * Database Storage
3
3
  *
4
4
  * Database backend using Drizzle ORM
5
- * Slower than Redis but uses existing database infrastructure
5
+ * Uses existing database infrastructure with no external cache dependency
6
6
  */
7
7
  // Import config module (ESM)
8
8
  // Config uses proxy for lazy loading, so import is safe - validation only happens on property access
9
9
  import configModule from '@revealui/config';
10
10
  import { createClient } from '@revealui/db/client';
11
- import { and, eq, gte, rateLimits } from '@revealui/db/schema';
11
+ import { rateLimits } from '@revealui/db/schema';
12
+ import { and, eq, gte } from 'drizzle-orm';
12
13
  export class DatabaseStorage {
13
14
  db;
14
15
  constructor(connectionString) {
@@ -60,9 +61,11 @@ export class DatabaseStorage {
60
61
  await this.db.delete(rateLimits).where(eq(rateLimits.key, key));
61
62
  }
62
63
  async incr(key) {
63
- const current = await this.get(key);
64
- const newValue = current ? parseInt(current, 10) + 1 : 1;
65
- await this.set(key, String(newValue));
64
+ let newValue = 1;
65
+ await this.atomicUpdate(key, (existing) => {
66
+ newValue = existing ? parseInt(existing, 10) + 1 : 1;
67
+ return { value: String(newValue), ttlSeconds: 24 * 60 * 60 };
68
+ });
66
69
  return newValue;
67
70
  }
68
71
  async exists(key) {
@@ -92,8 +95,13 @@ export class DatabaseStorage {
92
95
  });
93
96
  });
94
97
  }
95
- catch {
96
- // Transaction not supported (e.g., Neon HTTP serverless) — fall back to non-atomic
98
+ catch (error) {
99
+ // Only fall back for transaction-not-supported errors (e.g., Neon HTTP serverless).
100
+ // Re-throw real DB errors (connection failures, constraint violations, deadlocks).
101
+ const msg = error instanceof Error ? error.message : String(error);
102
+ if (!(msg.includes('transaction') || msg.includes('Transaction'))) {
103
+ throw error;
104
+ }
97
105
  const existing = await this.get(key);
98
106
  const { value, ttlSeconds } = updater(existing);
99
107
  await this.set(key, value, ttlSeconds);
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory.d.ts","sourceRoot":"","sources":["../../../src/server/storage/in-memory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAO7C,qBAAa,eAAgB,YAAW,OAAO;IAC7C,OAAO,CAAC,KAAK,CAAuC;IAG9C,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAiBxC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUnE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAQlC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAiBrC,YAAY,CAChB,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAC1E,OAAO,CAAC,IAAI,CAAC;IAUhB;;OAEG;IACH,OAAO,IAAI,IAAI;IASf;;OAEG;IACH,KAAK,IAAI,IAAI;CAGd"}
1
+ {"version":3,"file":"in-memory.d.ts","sourceRoot":"","sources":["../../../src/server/storage/in-memory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAO9C,qBAAa,eAAgB,YAAW,OAAO;IAC7C,OAAO,CAAC,KAAK,CAAwC;IAE/C,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAgBxC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASnE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAYlC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAgBrC,YAAY,CAChB,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAC1E,OAAO,CAAC,IAAI,CAAC;IAUhB;;OAEG;IACH,OAAO,IAAI,IAAI;IASf;;OAEG;IACH,KAAK,IAAI,IAAI;CAGd"}
@@ -6,7 +6,6 @@
6
6
  */
7
7
  export class InMemoryStorage {
8
8
  store = new Map();
9
- // eslint-disable-next-line @typescript-eslint/require-await
10
9
  async get(key) {
11
10
  const entry = this.store.get(key);
12
11
  if (!entry) {
@@ -19,7 +18,6 @@ export class InMemoryStorage {
19
18
  }
20
19
  return entry.value;
21
20
  }
22
- // eslint-disable-next-line @typescript-eslint/require-await
23
21
  async set(key, value, ttlSeconds) {
24
22
  const entry = {
25
23
  value,
@@ -27,17 +25,20 @@ export class InMemoryStorage {
27
25
  };
28
26
  this.store.set(key, entry);
29
27
  }
30
- // eslint-disable-next-line @typescript-eslint/require-await
31
28
  async del(key) {
32
29
  this.store.delete(key);
33
30
  }
34
31
  async incr(key) {
35
- const current = await this.get(key);
32
+ // Read and write synchronously on the Map to avoid yielding to the event loop
33
+ // between read and write (same approach as atomicUpdate).
34
+ const now = Date.now();
35
+ const entry = this.store.get(key);
36
+ const current = entry && (!entry.expiresAt || entry.expiresAt >= now) ? entry.value : null;
36
37
  const newValue = current ? parseInt(current, 10) + 1 : 1;
37
- await this.set(key, String(newValue));
38
+ // Preserve the original TTL if the entry exists
39
+ this.store.set(key, { value: String(newValue), expiresAt: entry?.expiresAt });
38
40
  return newValue;
39
41
  }
40
- // eslint-disable-next-line @typescript-eslint/require-await
41
42
  async exists(key) {
42
43
  const entry = this.store.get(key);
43
44
  if (!entry) {
@@ -50,7 +51,6 @@ export class InMemoryStorage {
50
51
  }
51
52
  return true;
52
53
  }
53
- // eslint-disable-next-line @typescript-eslint/require-await
54
54
  async atomicUpdate(key, updater) {
55
55
  // Read synchronously from the Map to avoid yielding to the event loop between
56
56
  // read and write (JavaScript is single-threaded; no I/O = no interleaving).
@@ -1,11 +1,19 @@
1
1
  /**
2
2
  * Storage Factory
3
3
  *
4
- * Selects storage backend based on configuration
4
+ * Selects storage backend based on configuration.
5
5
  * Priority: Database > In-Memory
6
6
  *
7
- * Note: Uses database storage for distributed rate limiting (works with ElectricSQL sync).
8
- * ElectricSQL handles client-side sync, database handles server-side storage.
7
+ * Architecture Decision (2026-03-11):
8
+ * Production deployments use DatabaseStorage backed by NeonDB (PostgreSQL).
9
+ * Neon's serverless driver uses HTTP (not persistent connections), so each
10
+ * rate limit check is a single HTTP round-trip (~30-50ms). State persists
11
+ * across Vercel cold starts because it lives in PostgreSQL, not process memory.
12
+ * This is acceptable for current scale. If sub-10ms latency becomes critical,
13
+ * add an ElectricSQL/PGlite adapter implementing the Storage interface.
14
+ *
15
+ * In-memory storage is ONLY used in development (throws in production if
16
+ * DATABASE_URL is missing).
9
17
  */
10
18
  import type { Storage } from './interface.js';
11
19
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/storage/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAI7C;;GAEG;AACH,wBAAgB,UAAU,IAAI,OAAO,CAkCpC;AAED;;GAEG;AACH,wBAAgB,aAAa,IAAI,OAAO,CAevC;AAED;;GAEG;AACH,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAED,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAE/C,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAChD,YAAY,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/storage/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAMH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAI9C;;GAEG;AACH,wBAAgB,UAAU,IAAI,OAAO,CA6CpC;AAED;;GAEG;AACH,wBAAgB,aAAa,IAAI,OAAO,CAevC;AAED;;GAEG;AACH,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAED,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,YAAY,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC"}