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37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
 * Authentication middleware for API security
 *
 * Supports two authentication methods:
 * 1. Header-based (X-API-Key) - Used by Electron mode
 * 2. Cookie-based (HTTP-only session cookie) - Used by web mode
 *
 * Auto-generates an API key on first run if none is configured.
 */

import type { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
import path from 'path';
import * as secureFs from './secure-fs.js';
import { createLogger } from '@automaker/utils';

const logger = createLogger('Auth');

const DATA_DIR = process.env.DATA_DIR || './data';
const API_KEY_FILE = path.join(DATA_DIR, '.api-key');
const SESSIONS_FILE = path.join(DATA_DIR, '.sessions');
const SESSION_COOKIE_NAME = 'automaker_session';
const SESSION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
const WS_TOKEN_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes for WebSocket connection tokens

/**
 * Check if an environment variable is set to 'true'
 */
function isEnvTrue(envVar: string | undefined): boolean {
  return envVar === 'true';
}

// Session store - persisted to file for survival across server restarts
const validSessions = new Map<string, { createdAt: number; expiresAt: number }>();

// Short-lived WebSocket connection tokens (in-memory only, not persisted)
const wsConnectionTokens = new Map<string, { createdAt: number; expiresAt: number }>();

// Clean up expired WebSocket tokens periodically
setInterval(() => {
  const now = Date.now();
  wsConnectionTokens.forEach((data, token) => {
    if (data.expiresAt <= now) {
      wsConnectionTokens.delete(token);
    }
  });
}, 60 * 1000); // Clean up every minute

/**
 * Load sessions from file on startup
 */
function loadSessions(): void {
  try {
    if (secureFs.existsSync(SESSIONS_FILE)) {
      const data = secureFs.readFileSync(SESSIONS_FILE, 'utf-8') as string;
      const sessions = JSON.parse(data) as Array<
        [string, { createdAt: number; expiresAt: number }]
      >;
      const now = Date.now();
      let loadedCount = 0;
      let expiredCount = 0;

      for (const [token, session] of sessions) {
        // Only load non-expired sessions
        if (session.expiresAt > now) {
          validSessions.set(token, session);
          loadedCount++;
        } else {
          expiredCount++;
        }
      }

      if (loadedCount > 0 || expiredCount > 0) {
        logger.info(`Loaded ${loadedCount} sessions (${expiredCount} expired)`);
      }
    }
  } catch (error) {
    logger.warn('Error loading sessions:', error);
  }
}

/**
 * Save sessions to file (async)
 */
async function saveSessions(): Promise<void> {
  try {
    await secureFs.mkdir(path.dirname(SESSIONS_FILE), { recursive: true });
    const sessions = Array.from(validSessions.entries());
    await secureFs.writeFile(SESSIONS_FILE, JSON.stringify(sessions), {
      encoding: 'utf-8',
      mode: 0o600,
    });
  } catch (error) {
    logger.error('Failed to save sessions:', error);
  }
}

// Load existing sessions on startup
loadSessions();

/**
 * Ensure an API key exists - either from env var, file, or generate new one.
 * This provides CSRF protection by requiring a secret key for all API requests.
 */
function ensureApiKey(): string {
  // First check environment variable (Electron passes it this way)
  if (process.env.AUTOMAKER_API_KEY) {
    logger.info('Using API key from environment variable');
    return process.env.AUTOMAKER_API_KEY;
  }

  // Try to read from file
  try {
    if (secureFs.existsSync(API_KEY_FILE)) {
      const key = (secureFs.readFileSync(API_KEY_FILE, 'utf-8') as string).trim();
      if (key) {
        logger.info('Loaded API key from file');
        return key;
      }
    }
  } catch (error) {
    logger.warn('Error reading API key file:', error);
  }

  // Generate new key
  const newKey = crypto.randomUUID();
  try {
    secureFs.mkdirSync(path.dirname(API_KEY_FILE), { recursive: true });
    secureFs.writeFileSync(API_KEY_FILE, newKey, { encoding: 'utf-8', mode: 0o600 });
    logger.info('Generated new API key');
  } catch (error) {
    logger.error('Failed to save API key:', error);
  }
  return newKey;
}

// API key - always generated/loaded on startup for CSRF protection
const API_KEY = ensureApiKey();

// Width for log box content (excluding borders)
const BOX_CONTENT_WIDTH = 67;

// Print API key to console for web mode users (unless suppressed for production logging)
if (!isEnvTrue(process.env.AUTOMAKER_HIDE_API_KEY)) {
  const autoLoginEnabled = isEnvTrue(process.env.AUTOMAKER_AUTO_LOGIN);
  const autoLoginStatus = autoLoginEnabled ? 'enabled (auto-login active)' : 'disabled';

  // Build box lines with exact padding
  const header = 'πŸ” API Key for Web Mode Authentication'.padEnd(BOX_CONTENT_WIDTH);
  const line1 = "When accessing via browser, you'll be prompted to enter this key:".padEnd(
    BOX_CONTENT_WIDTH
  );
  const line2 = API_KEY.padEnd(BOX_CONTENT_WIDTH);
  const line3 = 'In Electron mode, authentication is handled automatically.'.padEnd(
    BOX_CONTENT_WIDTH
  );
  const line4 = `Auto-login (AUTOMAKER_AUTO_LOGIN): ${autoLoginStatus}`.padEnd(BOX_CONTENT_WIDTH);
  const tipHeader = 'πŸ’‘ Tips'.padEnd(BOX_CONTENT_WIDTH);
  const line5 = 'Set AUTOMAKER_API_KEY env var to use a fixed key'.padEnd(BOX_CONTENT_WIDTH);
  const line6 = 'Set AUTOMAKER_AUTO_LOGIN=true to skip the login prompt'.padEnd(BOX_CONTENT_WIDTH);

  logger.info(`
╔═════════════════════════════════════════════════════════════════════╗
β•‘  ${header}β•‘
╠═════════════════════════════════════════════════════════════════════╣
β•‘                                                                     β•‘
β•‘  ${line1}β•‘
β•‘                                                                     β•‘
β•‘  ${line2}β•‘
β•‘                                                                     β•‘
β•‘  ${line3}β•‘
β•‘                                                                     β•‘
β•‘  ${line4}β•‘
β•‘                                                                     β•‘
╠═════════════════════════════════════════════════════════════════════╣
β•‘  ${tipHeader}β•‘
╠═════════════════════════════════════════════════════════════════════╣
β•‘  ${line5}β•‘
β•‘  ${line6}β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
`);
} else {
  logger.info('API key banner hidden (AUTOMAKER_HIDE_API_KEY=true)');
}

/**
 * Generate a cryptographically secure session token
 */
function generateSessionToken(): string {
  return crypto.randomBytes(32).toString('hex');
}

/**
 * Create a new session and return the token
 */
export async function createSession(): Promise<string> {
  const token = generateSessionToken();
  const now = Date.now();
  validSessions.set(token, {
    createdAt: now,
    expiresAt: now + SESSION_MAX_AGE_MS,
  });
  await saveSessions(); // Persist to file
  return token;
}

/**
 * Validate a session token
 * Note: This returns synchronously but triggers async persistence if session expired
 */
export function validateSession(token: string): boolean {
  const session = validSessions.get(token);
  if (!session) return false;

  if (Date.now() > session.expiresAt) {
    validSessions.delete(token);
    // Fire-and-forget: persist removal asynchronously
    saveSessions().catch((err) => logger.error('Error saving sessions:', err));
    return false;
  }

  return true;
}

/**
 * Invalidate a session token
 */
export async function invalidateSession(token: string): Promise<void> {
  validSessions.delete(token);
  await saveSessions(); // Persist removal
}

/**
 * Create a short-lived WebSocket connection token
 * Used for initial WebSocket handshake authentication
 */
export function createWsConnectionToken(): string {
  const token = generateSessionToken();
  const now = Date.now();
  wsConnectionTokens.set(token, {
    createdAt: now,
    expiresAt: now + WS_TOKEN_MAX_AGE_MS,
  });
  return token;
}

/**
 * Validate a WebSocket connection token
 * These tokens are single-use and short-lived (5 minutes)
 * Token is invalidated immediately after first successful use
 */
export function validateWsConnectionToken(token: string): boolean {
  const tokenData = wsConnectionTokens.get(token);
  if (!tokenData) return false;

  // Always delete the token (single-use)
  wsConnectionTokens.delete(token);

  // Check if expired
  if (Date.now() > tokenData.expiresAt) {
    return false;
  }

  return true;
}

/**
 * Validate the API key using timing-safe comparison
 * Prevents timing attacks that could leak information about the key
 */
export function validateApiKey(key: string): boolean {
  if (!key || typeof key !== 'string') return false;

  // Both buffers must be the same length for timingSafeEqual
  const keyBuffer = Buffer.from(key);
  const apiKeyBuffer = Buffer.from(API_KEY);

  // If lengths differ, compare against a dummy to maintain constant time
  if (keyBuffer.length !== apiKeyBuffer.length) {
    crypto.timingSafeEqual(apiKeyBuffer, apiKeyBuffer);
    return false;
  }

  return crypto.timingSafeEqual(keyBuffer, apiKeyBuffer);
}

/**
 * Get session cookie options
 */
export function getSessionCookieOptions(): {
  httpOnly: boolean;
  secure: boolean;
  sameSite: 'strict' | 'lax' | 'none';
  maxAge: number;
  path: string;
} {
  return {
    httpOnly: true, // JavaScript cannot access this cookie
    secure: process.env.NODE_ENV === 'production', // HTTPS only in production
    sameSite: 'lax', // Sent for same-site requests and top-level navigations, but not cross-origin fetch/XHR
    maxAge: SESSION_MAX_AGE_MS,
    path: '/',
  };
}

/**
 * Get the session cookie name
 */
export function getSessionCookieName(): string {
  return SESSION_COOKIE_NAME;
}

/**
 * Authentication result type
 */
type AuthResult =
  | { authenticated: true }
  | { authenticated: false; errorType: 'invalid_api_key' | 'invalid_session' | 'no_auth' };

/**
 * Core authentication check - shared between middleware and status check
 * Extracts auth credentials from various sources and validates them
 */
function checkAuthentication(
  headers: Record<string, string | string[] | undefined>,
  query: Record<string, string | undefined>,
  cookies: Record<string, string | undefined>
): AuthResult {
  // Check for API key in header (Electron mode)
  const headerKey = headers['x-api-key'] as string | undefined;
  if (headerKey) {
    if (validateApiKey(headerKey)) {
      return { authenticated: true };
    }
    return { authenticated: false, errorType: 'invalid_api_key' };
  }

  // Check for session token in header (web mode with explicit token)
  const sessionTokenHeader = headers['x-session-token'] as string | undefined;
  if (sessionTokenHeader) {
    if (validateSession(sessionTokenHeader)) {
      return { authenticated: true };
    }
    return { authenticated: false, errorType: 'invalid_session' };
  }

  // Check for API key in query parameter (fallback)
  const queryKey = query.apiKey;
  if (queryKey) {
    if (validateApiKey(queryKey)) {
      return { authenticated: true };
    }
    return { authenticated: false, errorType: 'invalid_api_key' };
  }

  // Check for session token in query parameter (web mode - needed for image loads)
  const queryToken = query.token;
  if (queryToken) {
    if (validateSession(queryToken)) {
      return { authenticated: true };
    }
    return { authenticated: false, errorType: 'invalid_session' };
  }

  // Check for session cookie (web mode)
  const sessionToken = cookies[SESSION_COOKIE_NAME];
  if (sessionToken && validateSession(sessionToken)) {
    return { authenticated: true };
  }

  return { authenticated: false, errorType: 'no_auth' };
}

/**
 * Authentication middleware
 *
 * Accepts either:
 * 1. X-API-Key header (for Electron mode)
 * 2. X-Session-Token header (for web mode with explicit token)
 * 3. apiKey query parameter (fallback for Electron, cases where headers can't be set)
 * 4. token query parameter (fallback for web mode, needed for image loads via CSS/img tags)
 * 5. Session cookie (for web mode)
 */
export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
  // Allow disabling auth for local/trusted networks
  if (isEnvTrue(process.env.AUTOMAKER_DISABLE_AUTH)) {
    next();
    return;
  }

  const result = checkAuthentication(
    req.headers as Record<string, string | string[] | undefined>,
    req.query as Record<string, string | undefined>,
    (req.cookies || {}) as Record<string, string | undefined>
  );

  if (result.authenticated) {
    next();
    return;
  }

  // Return appropriate error based on what failed
  switch (result.errorType) {
    case 'invalid_api_key':
      res.status(403).json({
        success: false,
        error: 'Invalid API key.',
      });
      break;
    case 'invalid_session':
      res.status(403).json({
        success: false,
        error: 'Invalid or expired session token.',
      });
      break;
    case 'no_auth':
    default:
      res.status(401).json({
        success: false,
        error: 'Authentication required.',
      });
  }
}

/**
 * Check if authentication is enabled (always true now)
 */
export function isAuthEnabled(): boolean {
  return true;
}

/**
 * Get authentication status for health endpoint
 */
export function getAuthStatus(): { enabled: boolean; method: string } {
  const disabled = isEnvTrue(process.env.AUTOMAKER_DISABLE_AUTH);
  return {
    enabled: !disabled,
    method: disabled ? 'disabled' : 'api_key_or_session',
  };
}

/**
 * Check if a request is authenticated (for status endpoint)
 */
export function isRequestAuthenticated(req: Request): boolean {
  if (isEnvTrue(process.env.AUTOMAKER_DISABLE_AUTH)) return true;
  const result = checkAuthentication(
    req.headers as Record<string, string | string[] | undefined>,
    req.query as Record<string, string | undefined>,
    (req.cookies || {}) as Record<string, string | undefined>
  );
  return result.authenticated;
}

/**
 * Check if raw credentials are authenticated
 * Used for WebSocket authentication where we don't have Express request objects
 */
export function checkRawAuthentication(
  headers: Record<string, string | string[] | undefined>,
  query: Record<string, string | undefined>,
  cookies: Record<string, string | undefined>
): boolean {
  if (isEnvTrue(process.env.AUTOMAKER_DISABLE_AUTH)) return true;
  return checkAuthentication(headers, query, cookies).authenticated;
}