Fix serving of favicons

This commit is contained in:
Mats Jun Larsen
2025-06-18 22:52:29 +09:00
parent a346112ccc
commit 9202469d51
17 changed files with 24 additions and 125 deletions
+1 -1
View File
@@ -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,
};
+14 -14
View File
@@ -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');
+1 -1
View File
@@ -37,7 +37,7 @@ export interface ServerOptions {
staticRoot: string;
httpRoot: string;
sentrySlowRequestMs: number;
distPath: string;
manifestPath: string;
extraBodyClass: string;
maxUploadSize: string;
}
+3 -6
View File
@@ -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,
);
+2 -21
View File
@@ -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<PugRequireHandler> {
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';
}
-34
View File
@@ -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",
-2
View File
@@ -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",

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

+1 -1
View File
@@ -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', () => {
-6
View File
@@ -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 {
+1 -1
View File
@@ -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',
};
-37
View File
@@ -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');
});
});
});
+1 -1
View File
@@ -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);