From 9202469d514b75b867ff32112638c623cb569fdf Mon Sep 17 00:00:00 2001 From: Mats Jun Larsen Date: Sun, 15 Jun 2025 17:29:43 +0900 Subject: [PATCH] Fix serving of favicons --- lib/app/main.ts | 2 +- lib/app/server-config.ts | 28 ++++++------- lib/app/server.interfaces.ts | 2 +- lib/app/server.ts | 9 ++--- lib/app/static-assets.ts | 23 +---------- package-lock.json | 34 ---------------- package.json | 2 - {static/favicons => public}/favicon-beta.ico | Bin {static/favicons => public}/favicon-dev.ico | Bin .../favicons => public}/favicon-staging.ico | Bin .../favicons => public}/favicon-suspend.ico | Bin {static/favicons => public}/favicon.ico | Bin test/app/config-tests.ts | 2 +- test/app/server-config-tests.ts | 6 --- test/app/server-tests.ts | 2 +- test/app/static-assets-tests.ts | 37 ------------------ test/check-img.ts | 2 +- 17 files changed, 24 insertions(+), 125 deletions(-) rename {static/favicons => public}/favicon-beta.ico (100%) rename {static/favicons => public}/favicon-dev.ico (100%) rename {static/favicons => public}/favicon-staging.ico (100%) rename {static/favicons => public}/favicon-suspend.ico (100%) rename {static/favicons => public}/favicon.ico (100%) diff --git a/lib/app/main.ts b/lib/app/main.ts index ea9710668..7dd9f01b6 100644 --- a/lib/app/main.ts +++ b/lib/app/main.ts @@ -104,7 +104,7 @@ export async function initialiseApplication(options: ApplicationOptions): Promis staticRoot: config.staticRoot, httpRoot: config.httpRoot, sentrySlowRequestMs: ceProps('sentrySlowRequestMs', 0), - distPath: distPath, + manifestPath: distPath, extraBodyClass: config.extraBodyClass, maxUploadSize: config.maxUploadSize, }; diff --git a/lib/app/server-config.ts b/lib/app/server-config.ts index 18758e914..530916926 100644 --- a/lib/app/server-config.ts +++ b/lib/app/server-config.ts @@ -28,7 +28,6 @@ import express from 'express'; import type {NextFunction, Request, Response, Router} from 'express'; import morgan from 'morgan'; import sanitize from 'sanitize-filename'; -import sFavicon from 'serve-favicon'; import {cached, csp} from '../handlers/middleware.js'; import {logger, makeLogStream} from '../logger.js'; @@ -119,25 +118,36 @@ export function setupLoggingMiddleware(isDevMode: boolean, router: Router): void morgan(morganFormat, { stream: makeLogStream('info'), // Skip for non errors (2xx, 3xx) - skip: (req: Request, res: Response) => res.statusCode >= 400, + skip: (req: Request, res: Response) => res.statusCode >= 400 || isFaviconRequest(req), }), ); router.use( morgan(morganFormat, { stream: makeLogStream('warn'), // Skip for non user errors (4xx) - skip: (req: Request, res: Response) => res.statusCode < 400 || res.statusCode >= 500, + skip: (req: Request, res: Response) => + res.statusCode < 400 || res.statusCode >= 500 || isFaviconRequest(req), }), ); router.use( morgan(morganFormat, { stream: makeLogStream('error'), // Skip for non server errors (5xx) - skip: (req: Request, res: Response) => res.statusCode < 500, + skip: (req: Request, res: Response) => res.statusCode < 500 || isFaviconRequest(req), }), ); } +function isFaviconRequest(req: Request): boolean { + return [ + 'favicon.ico', + 'favicon-beta.ico', + 'favicon-dev.ico', + 'favicon-staging.ico', + 'favicon-suspend.ico', + ].includes(req.path); +} + /** * Setup basic routes for the web server * @param router - Express router @@ -145,7 +155,6 @@ export function setupLoggingMiddleware(isDevMode: boolean, router: Router): void * @param embeddedHandler - Handler for embedded mode * @param ceProps - Compiler Explorer properties * @param awsProps - AWS properties - * @param faviconFilename - Favicon filename * @param options - Server options * @param clientOptionsHandler - Client options handler */ @@ -155,7 +164,6 @@ export function setupBasicRoutes( embeddedHandler: express.Handler, ceProps: PropertyGetter, awsProps: PropertyGetter, - faviconFilename: string, options: ServerOptions, clientOptionsHandler: ClientOptionsSource, ): void { @@ -199,14 +207,6 @@ export function setupBasicRoutes( res.render('sitemap'); }); - // Try to add favicon support, but don't fail if it's not available (useful for tests) - try { - router.use(sFavicon(utils.resolvePathFromAppRoot('static/favicons', faviconFilename))); - } catch (err: unknown) { - const error = err as Error; - logger.warn(`Could not set up favicon: ${error.message}`); - } - router .get('/client-options.js', cached, (req, res) => { res.set('Content-Type', 'application/javascript'); diff --git a/lib/app/server.interfaces.ts b/lib/app/server.interfaces.ts index ce81a0dff..e2f55cccd 100644 --- a/lib/app/server.interfaces.ts +++ b/lib/app/server.interfaces.ts @@ -37,7 +37,7 @@ export interface ServerOptions { staticRoot: string; httpRoot: string; sentrySlowRequestMs: number; - distPath: string; + manifestPath: string; extraBodyClass: string; maxUploadSize: string; } diff --git a/lib/app/server.ts b/lib/app/server.ts index ce7db197e..01fc02f12 100644 --- a/lib/app/server.ts +++ b/lib/app/server.ts @@ -28,13 +28,11 @@ import type {AppArguments} from '../app.interfaces.js'; import {logger} from '../logger.js'; import {createRenderHandlers} from './rendering.js'; import {setupBaseServerConfig, setupBasicRoutes, setupLoggingMiddleware} from './server-config.js'; -import {startListening} from './server-listening.js'; import {ServerDependencies, ServerOptions, WebServerResult} from './server.interfaces.js'; -import {getFaviconFilename, setupStaticMiddleware, setupWebPackDevMiddleware} from './static-assets.js'; -import {isMobileViewer} from './url-handlers.js'; +import {setupStaticMiddleware, setupWebPackDevMiddleware} from './static-assets.js'; -// Re-exporting functions that are used by other modules -export {getFaviconFilename, isMobileViewer, startListening}; +export {startListening} from './server-listening.js'; +export {isMobileViewer} from './url-handlers.js'; /** * Configure a web server and its routes @@ -81,7 +79,6 @@ export async function setupWebServer( embeddedHandler, dependencies.ceProps, dependencies.awsProps, - getFaviconFilename(appArgs.devMode, appArgs.env), options, dependencies.clientOptionsHandler, ); diff --git a/lib/app/static-assets.ts b/lib/app/static-assets.ts index d64f3bb34..aadd00f0b 100644 --- a/lib/app/static-assets.ts +++ b/lib/app/static-assets.ts @@ -92,14 +92,14 @@ export async function setupWebPackDevMiddleware(options: ServerOptions, router: * @returns Function to handle Pug requires */ export async function setupStaticMiddleware(options: ServerOptions, router: Router): Promise { - const staticManifest = JSON.parse(await fs.readFile(path.join(options.distPath, 'manifest.json'), 'utf-8')); + const staticManifest = JSON.parse(await fs.readFile(path.join(options.manifestPath, 'manifest.json'), 'utf-8')); if (options.staticUrl) { logger.info(` using static files from '${options.staticUrl}'`); } else { logger.info(` serving static files from '${options.staticPath}'`); router.use( - '/static', + '/', express.static(options.staticPath, { maxAge: options.staticMaxAgeSecs * 1000, }), @@ -108,22 +108,3 @@ export async function setupStaticMiddleware(options: ServerOptions, router: Rout return createDefaultPugRequireHandler(options.staticRoot, staticManifest); } - -/** - * Gets the appropriate favicon filename based on the environment - * @param isDevMode - Whether the app is running in development mode - * @param env - The environment names array - * @returns The favicon filename to use - */ -export function getFaviconFilename(isDevMode: boolean, env?: string[]): string { - if (isDevMode) { - return 'favicon-dev.ico'; - } - if (env?.includes('beta')) { - return 'favicon-beta.ico'; - } - if (env?.includes('staging')) { - return 'favicon-staging.ico'; - } - return 'favicon.ico'; -} diff --git a/package-lock.json b/package-lock.json index faafe32e3..d3d1c2ccc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -56,7 +56,6 @@ "sanitize-filename": "^1.6.3", "scroll-into-view-if-needed": "^3.1.0", "semver": "^7.7.2", - "serve-favicon": "^2.5.1", "systemd-socket": "0.0.0", "tar-stream": "^3.1.7", "tom-select": "^2.4.3", @@ -89,7 +88,6 @@ "@types/node-targz": "^0.2.4", "@types/request": "^2.48.12", "@types/response-time": "^2.3.9", - "@types/serve-favicon": "^2.5.7", "@types/temp": "^0.9.4", "@types/underscore": "^1.13.0", "@types/webpack-env": "^1.18.8", @@ -4814,15 +4812,6 @@ "@types/node": "*" } }, - "node_modules/@types/serve-favicon": { - "version": "2.5.7", - "resolved": "https://registry.npmjs.org/@types/serve-favicon/-/serve-favicon-2.5.7.tgz", - "integrity": "sha512-z9TNUQXdQ+W/OJMP1e3KOYUZ99qJS4+ZfFOIrPGImcayqKoyifbJSEFkVq1MCKBbqjMZpjPj3B5ilrQAR2+TOw==", - "dev": true, - "dependencies": { - "@types/express": "*" - } - }, "node_modules/@types/serve-static": { "version": "1.15.8", "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.8.tgz", @@ -11401,29 +11390,6 @@ "randombytes": "^2.1.0" } }, - "node_modules/serve-favicon": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/serve-favicon/-/serve-favicon-2.5.1.tgz", - "integrity": "sha512-JndLBslCLA/ebr7rS3d+/EKkzTsTi1jI2T9l+vHfAaGJ7A7NhtDpSZ0lx81HCNWnnE0yHncG+SSnVf9IMxOwXQ==", - "dependencies": { - "etag": "~1.8.1", - "fresh": "~0.5.2", - "ms": "~2.1.3", - "parseurl": "~1.3.2", - "safe-buffer": "~5.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/serve-favicon/node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/serve-static": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", diff --git a/package.json b/package.json index 2a34a8ec8..881e66389 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,6 @@ "sanitize-filename": "^1.6.3", "scroll-into-view-if-needed": "^3.1.0", "semver": "^7.7.2", - "serve-favicon": "^2.5.1", "systemd-socket": "0.0.0", "tar-stream": "^3.1.7", "tom-select": "^2.4.3", @@ -98,7 +97,6 @@ "@types/node-targz": "^0.2.4", "@types/request": "^2.48.12", "@types/response-time": "^2.3.9", - "@types/serve-favicon": "^2.5.7", "@types/temp": "^0.9.4", "@types/underscore": "^1.13.0", "@types/webpack-env": "^1.18.8", diff --git a/static/favicons/favicon-beta.ico b/public/favicon-beta.ico similarity index 100% rename from static/favicons/favicon-beta.ico rename to public/favicon-beta.ico diff --git a/static/favicons/favicon-dev.ico b/public/favicon-dev.ico similarity index 100% rename from static/favicons/favicon-dev.ico rename to public/favicon-dev.ico diff --git a/static/favicons/favicon-staging.ico b/public/favicon-staging.ico similarity index 100% rename from static/favicons/favicon-staging.ico rename to public/favicon-staging.ico diff --git a/static/favicons/favicon-suspend.ico b/public/favicon-suspend.ico similarity index 100% rename from static/favicons/favicon-suspend.ico rename to public/favicon-suspend.ico diff --git a/static/favicons/favicon.ico b/public/favicon.ico similarity index 100% rename from static/favicons/favicon.ico rename to public/favicon.ico diff --git a/test/app/config-tests.ts b/test/app/config-tests.ts index 27a6290fc..aeee70225 100644 --- a/test/app/config-tests.ts +++ b/test/app/config-tests.ts @@ -358,7 +358,7 @@ describe('Config Module', () => { expect(result).toHaveProperty('extraBodyClass', 'test-class'); expect(result).toHaveProperty('storageSolution', 'local'); expect(result).toHaveProperty('httpRoot', '/ce/'); - expect(result).toHaveProperty('staticRoot', '/ce/static/'); + expect(result).toHaveProperty('staticRoot', '/ce/'); }); it('should enable property debugging when propDebug is true', () => { diff --git a/test/app/server-config-tests.ts b/test/app/server-config-tests.ts index a6d34279a..c164ccb45 100644 --- a/test/app/server-config-tests.ts +++ b/test/app/server-config-tests.ts @@ -52,12 +52,6 @@ vi.mock('../../lib/logger.js', async () => { }; }); -vi.mock('serve-favicon', () => { - return { - default: vi.fn(), - }; -}); - vi.mock('../../lib/utils.js', async () => { const actual = await vi.importActual('../../lib/utils.js'); return { diff --git a/test/app/server-tests.ts b/test/app/server-tests.ts index 27cd5d6fa..1b42e8e78 100644 --- a/test/app/server-tests.ts +++ b/test/app/server-tests.ts @@ -97,7 +97,7 @@ describe('Server Module', () => { staticRoot: '/static', httpRoot: '', sentrySlowRequestMs: 500, - distPath: '/mocked/dist', // Use absolute path for testing + manifestPath: '/mocked/dist', // Use absolute path for testing extraBodyClass: 'test-class', maxUploadSize: '1mb', }; diff --git a/test/app/static-assets-tests.ts b/test/app/static-assets-tests.ts index c1480c671..9904b8bc3 100644 --- a/test/app/static-assets-tests.ts +++ b/test/app/static-assets-tests.ts @@ -23,7 +23,6 @@ // POSSIBILITY OF SUCH DAMAGE. import {describe, expect, it, vi} from 'vitest'; -import {getFaviconFilename} from '../../lib/app/server.js'; import {createDefaultPugRequireHandler} from '../../lib/app/static-assets.js'; // Mock the logger @@ -109,40 +108,4 @@ describe('Static assets', () => { } }); }); - - describe('getFaviconFilename', () => { - it('should prioritize dev environment over other environments', () => { - // Dev mode favicon should be used regardless of environment flags - expect(getFaviconFilename(true, [])).toContain('dev'); - expect(getFaviconFilename(true, ['beta'])).toContain('dev'); - expect(getFaviconFilename(true, ['staging'])).toContain('dev'); - expect(getFaviconFilename(true, ['beta', 'staging'])).toContain('dev'); - }); - - it('should select appropriate favicon based on environment', () => { - // Test specific environments when not in dev mode - const environments = [ - {env: ['beta'], expected: 'beta'}, - {env: ['staging'], expected: 'staging'}, - {env: [], expected: 'favicon.ico'}, - ]; - - for (const {env, expected} of environments) { - const result = getFaviconFilename(false, env); - if (expected === 'favicon.ico') { - expect(result).toBe(expected); - } else { - expect(result).toContain(expected); - } - } - }); - - it('should handle environment arrays with mixed values', () => { - // When multiple environments are specified, there should be a consistent priority - expect(getFaviconFilename(false, ['beta', 'staging'])).toContain('beta'); - expect(getFaviconFilename(false, ['staging', 'beta'])).toContain('beta'); - expect(getFaviconFilename(false, ['other', 'beta'])).toContain('beta'); - expect(getFaviconFilename(false, ['other', 'staging'])).toContain('staging'); - }); - }); }); diff --git a/test/check-img.ts b/test/check-img.ts index a612b3e24..0e576465c 100644 --- a/test/check-img.ts +++ b/test/check-img.ts @@ -29,7 +29,7 @@ import {describe, expect, it} from 'vitest'; import {languages} from '../lib/languages.js'; -const img_dir = path.resolve('views/resources/logos'); +const img_dir = path.resolve('public/logos'); function checkImage(logo: string) { const logoPath = path.join(img_dir, logo);