All files / backend/src/api server.ts

21.6% Statements 27/125
24.07% Branches 13/54
10.52% Functions 2/19
21.6% Lines 27/125

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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                                                                                                                              8x 8x 8x     8x 4x       8x 5x           8x     8x 8x                   8x                       8x                         8x                                                       8x                                                                                                                                   8x           8x                                                         8x                                                               8x                                                             8x                                                             8x 5x 2x 1x 1x   1x         8x   8x                                            
/**
 * Express Server Factory
 *
 * Creates an Express app with all API routes and middleware.
 * Uses dependency injection via AppContainer.
 */
 
import express, { type Express, type Request, type Response } from 'express';
import path from 'path';
import cors from 'cors';
import type { AppContainer } from '../config/container.js';
import { createApiHandlers, getHandler } from './router.js';
import { errorHandler, asyncHandler } from './middleware/error-handler.js';
import { createAuthMiddleware } from './middleware/auth-middleware.js';
import { createAuthRoutes } from './routes/auth-routes.js';
import { TokenService } from '../auth/token-service.js';
 
/**
 * Server configuration options
 */
/**
 * Auth configuration for the server
 */
export interface ServerAuthOptions {
  enabled: boolean;
  secret: string;
  accessTokenExpiry: string;
  refreshTokenExpiry: string;
}
 
export interface ServerOptions {
  /**
   * Port to listen on (default: 5150)
   */
  port?: number;
 
  /**
   * Enable CORS. Defaults to true when frontendPath is not set,
   * false when frontendPath is set (same-origin, CORS not needed).
   */
  cors?: boolean;
 
  /**
   * Path to the frontend build directory. When set, the server
   * serves static files and provides SPA catch-all routing.
   */
  frontendPath?: string;
 
  /**
   * Authentication configuration. When set with enabled: true,
   * JWT auth middleware protects all API routes.
   * Electron mode should never set this.
   */
  auth?: ServerAuthOptions;
}
 
/**
 * Create an Express server with all API routes
 */
export function createServer(
  container: AppContainer,
  options: ServerOptions = {}
): Express {
  const app = express();
  const { frontendPath } = options;
  const enableCors = options.cors ?? !frontendPath;
 
  // Middleware
  if (enableCors) {
    app.use(cors());
  }
 
  // Serve frontend SPA static files (public — login page must load without auth)
  if (frontendPath) {
    app.use(express.static(frontendPath));
  }
 
  // We need to raise this limit because we import theme screenshots and bundle files.
  // The files are base64 encoded and can get quite large (base64 adds ~33% overhead).
  // For a local Electron app, 100mb is a reasonable limit.
  app.use(express.json({ limit: '100mb' }));
 
  // Auth routes and middleware (when auth is enabled)
  const { auth } = options;
  Iif (auth?.enabled && container.authProvider) {
    const tokenService = new TokenService(auth.secret, auth.accessTokenExpiry, auth.refreshTokenExpiry);
 
    // Auth API routes are public (login, refresh, check)
    app.use(createAuthRoutes(container.authProvider, tokenService));
 
    // Auth middleware protects all routes registered after this point
    app.use(createAuthMiddleware(tokenService));
  } else {
    // When auth is disabled, provide a check endpoint that says so
    app.get('/api/auth/check', (_req: Request, res: Response) => {
      res.json({ authEnabled: false });
    });
  }
 
  /**
   * Create handler registry
   * The handlers are platform specific and implemented in adapters
   *
   * For example: the electron adapter defines handlers to open a file in an editor
   * The standalone adapter does not, and just console.log a no-op.
   */
  const apiHandlers = createApiHandlers(container);
 
  /** Set standard SSE headers, including CORS when enabled */
  function setSseHeaders(res: Response) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    if (enableCors) {
      res.setHeader('Access-Control-Allow-Origin', '*');
    }
  }
 
  // API route - handles all POST /api/:method requests
  app.post(
    '/api/:method',
    asyncHandler(async (req: Request, res: Response) => {
      const { method } = req.params;
      const { data } = req.body;
 
      if (typeof method !== 'string') {
        res.status(400).json({ error: 'Invalid parameters' });
        return;
      }
 
      // Get the handler for this method
      const handler = getHandler(apiHandlers, method);
 
      if (!handler) {
        res.status(404).json({
          error: `API method '${method}' not found`,
        });
        return;
      }
 
      // Execute handler
      const result = await handler(data);
      res.json(result);
    })
  );
 
  // SSE route for SSG binary download progress streaming
  app.get(
    '/api/ssg/download/:ssgType/:version',
    async (req: Request, res: Response) => {
      const { ssgType, version } = req.params;
 
      if (typeof ssgType !== 'string' || typeof version !== 'string') {
        res.status(400).json({ error: 'Invalid parameters' });
        return;
      }
 
      setSseHeaders(res);
 
      // Track if connection was closed by client
      let connectionClosed = false;
 
      try {
        // Get the provider's binary manager
        const provider = await container.providerFactory.getProvider(ssgType);
        const binaryManager = provider.getBinaryManager();
 
        if (!binaryManager) {
          res.write(`data: ${JSON.stringify({ percent: 0, message: `${ssgType} does not require binary downloads`, complete: false, error: 'No binary manager available' })}\n\n`);
          res.end();
          return;
        }
 
        // Handle client disconnect - cancel the download and clean up
        req.on('close', () => {
          connectionClosed = true;
          // Cancel the download if client disconnects (e.g., user closes dialog)
          binaryManager.cancel();
        });
 
        // Stream progress updates from the async generator
        // the for..of syntax is basically a nice way to do something like
        // const generator = container.hugoDownloader.download(version);
        // generator.next(); (repeat untill the SSE stream closes)
        for await (const progress of binaryManager.download(version)) {
          // Stop if client disconnected
          if (connectionClosed) {
            break;
          }
 
          // the data: prefix is required
          // the \n\n is the way the browser knows it's the end of the message
          res.write(`data: ${JSON.stringify(progress)}\n\n`);
 
          // End stream on completion or error
          if (progress.complete || progress.error) {
            break;
          }
        }
      } catch (error) {
        if (!connectionClosed) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          res.write(`data: ${JSON.stringify({ percent: 0, message: errorMessage, complete: false, error: errorMessage })}\n\n`);
        }
      }
 
      if (!connectionClosed) {
        res.end();
      }
    }
  );
 
  // Backward compatibility: redirect old Hugo endpoint to new SSG endpoint
  app.get('/api/hugo/download/:version', (req: Request, res: Response) => {
    const { version } = req.params;
    res.redirect(307, `/api/ssg/download/hugo/${version}`);
  });
 
  // SSE route for model change events (workspace config invalidation)
  app.get(
    '/api/workspace/:siteKey/:workspaceKey/model-events',
    (req: Request, res: Response) => {
      const { siteKey, workspaceKey } = req.params;
 
      setSseHeaders(res);
 
      let connectionClosed = false;
 
      // Subscribe to model change events for this workspace
      const unsubscribe = container.modelChangeEventBroadcaster.subscribe((event) => {
        if (!connectionClosed && event.siteKey === siteKey && event.workspaceKey === workspaceKey) {
          res.write(`data: ${JSON.stringify(event)}\n\n`);
        }
      });
 
      // Handle client disconnect
      req.on('close', () => {
        connectionClosed = true;
        unsubscribe();
      });
 
      // Send initial connection confirmation
      res.write(`data: ${JSON.stringify({ type: 'connected', siteKey, workspaceKey })}\n\n`);
    }
  );
 
 
  // SSE route for sync publish progress streaming
  app.post(
    '/api/sync/publish/stream',
    async (req: Request, res: Response) => {
      const { siteKey, publishConf } = req.body;
 
      setSseHeaders(res);
 
      try {
        // Create progress callback that writes to SSE stream
        const progressCallback = (message: string, progress: number) => {
          res.write(`data: ${JSON.stringify({ message, progress, complete: false })}\n\n`);
        };
 
        // Get publisher with progress callback
        const action = publishConf.type === 'folder' ? 'pushToRemote' : 'pushWithSoftMerge';
        const publisher = container.syncFactory.getPublisher(publishConf, siteKey, "main", progressCallback);
 
        // Execute sync operation
        const result = await publisher.actionDispatcher(action);
 
        // Send completion
        res.write(`data: ${JSON.stringify({ message: 'Sync complete', progress: 100, complete: true, result })}\n\n`);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        res.write(`data: ${JSON.stringify({ message: errorMessage, progress: 0, complete: false, error: errorMessage })}\n\n`);
      }
 
      res.end();
    }
  );
 
  // SSE route for sync merge/pull progress streaming
  app.post(
    '/api/sync/merge/stream',
    async (req: Request, res: Response) => {
      const { siteKey, publishConf } = req.body;
 
      setSseHeaders(res);
 
      try {
        // Create progress callback that writes to SSE stream
        const progressCallback = (message: string, progress: number) => {
          res.write(`data: ${JSON.stringify({ message, progress, complete: false })}\n\n`);
        };
 
        // Get publisher with progress callback
        const publisher = container.syncFactory.getPublisher(publishConf, siteKey, "main", progressCallback);
 
        // Execute sync operation
        const result = await publisher.actionDispatcher('pullFromRemote');
 
        // Send completion
        res.write(`data: ${JSON.stringify({ message: 'Merge complete', progress: 100, complete: true, result })}\n\n`);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        res.write(`data: ${JSON.stringify({ message: errorMessage, progress: 0, complete: false, error: errorMessage })}\n\n`);
      }
 
      res.end();
    }
  );
 
  // SSE route for generic sync action progress streaming
  app.post(
    '/api/sync/action/stream',
    async (req: Request, res: Response) => {
      const { siteKey, publishConf, action, actionParameters } = req.body;
 
      setSseHeaders(res);
 
      try {
        // Create progress callback that writes to SSE stream
        const progressCallback = (message: string, progress: number) => {
          res.write(`data: ${JSON.stringify({ message, progress, complete: false })}\n\n`);
        };
 
        // Get publisher with progress callback
        const publisher = container.syncFactory.getPublisher(publishConf, siteKey, "main", progressCallback);
 
        // Execute sync operation
        const result = await publisher.actionDispatcher(action, actionParameters);
 
        // Send completion
        res.write(`data: ${JSON.stringify({ message: 'Action complete', progress: 100, complete: true, result })}\n\n`);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        res.write(`data: ${JSON.stringify({ message: errorMessage, progress: 0, complete: false, error: errorMessage })}\n\n`);
      }
 
      res.end();
    }
  );
 
  // SPA catch-all: serve index.html for any non-API route (public)
  if (frontendPath) {
    app.get('/{*path}', (req, res) => {
      if (req.path.startsWith('/api')) {
        res.status(404).json({ error: 'API endpoint not found' });
        return;
      }
      res.sendFile(path.join(frontendPath, 'index.html'));
    });
  }
 
  // Error handling middleware (must be last)
  app.use(errorHandler);
 
  return app;
}
 
/**
 * Start the server on the specified port
 */
export function startServer(
  container: AppContainer,
  options: ServerOptions = {}
): void {
  const { port = 5150 } = options;
 
  const app = createServer(container, options);
 
  app.listen(port, () => {
    container.logger.info('backend-server', 'API Server started', {
      port,
      url: `http://localhost:${port}`
    });
    console.log(`Server running on http://localhost:${port}`);
  });
}