Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion __tests__/server-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
getContentType,
generateX2TConfig,
extractFilePathFromUrl,
isXLSXSignature
isXLSXSignature,
classifySendFileError
} from '../server-utils.js';

describe('getX2TFormatCode', () => {
Expand Down Expand Up @@ -293,3 +294,57 @@ describe('isXLSXSignature', () => {
expect(isXLSXSignature(undefined)).toBe(false);
});
});

describe('classifySendFileError', () => {
test('ignores aborted requests', () => {
expect(classifySendFileError({
code: 'ECONNABORTED'
}, {
notFoundBody: 'File not found',
internalErrorBody: 'File error'
})).toEqual({
action: 'ignore'
});
});

test('maps sendFile not-found errors to HTTP 404 responses', () => {
expect(classifySendFileError({
statusCode: 404,
code: 'ENOENT'
}, {
notFoundBody: 'File not found',
internalErrorBody: 'File error'
})).toEqual({
action: 'respond',
statusCode: 404,
body: 'File not found',
logLevel: 'warn'
});
});

test('maps directory sendFile errors to HTTP 404 responses', () => {
expect(classifySendFileError({
code: 'EISDIR'
}, {
notFoundBody: 'File not found',
internalErrorBody: 'File error'
})).toEqual({
action: 'respond',
statusCode: 404,
body: 'File not found',
logLevel: 'warn'
});
});

test('maps unexpected sendFile failures to HTTP 500 responses', () => {
expect(classifySendFileError(new Error('permission denied'), {
notFoundBody: 'File not found',
internalErrorBody: 'File error'
})).toEqual({
action: 'respond',
statusCode: 500,
body: 'File error',
logLevel: 'error'
});
});
});
45 changes: 44 additions & 1 deletion server-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,48 @@ function isXLSXSignature(data) {
return data[0] === 0x50 && data[1] === 0x4B;
}

/**
* Classify an Express sendFile callback error into an HTTP response.
* @param {Error & {statusCode?: number, status?: number, code?: string}} err
* @param {object} options
* @param {string} options.notFoundBody
* @param {string} options.internalErrorBody
* @returns {
* {action: 'ignore'} |
* {action: 'respond', statusCode: number, body: string, logLevel: 'warn' | 'error'}
* }
*/
function classifySendFileError(err, options) {
const { notFoundBody, internalErrorBody } = options;
const statusCode = Number.isInteger(err?.statusCode)
? err.statusCode
: Number.isInteger(err?.status)
? err.status
: null;

if (err?.code === 'ECONNABORTED') {
return {
action: 'ignore'
};
}

if (statusCode === 404 || err?.code === 'ENOENT' || err?.code === 'EISDIR') {
return {
action: 'respond',
statusCode: 404,
body: notFoundBody,
logLevel: 'warn'
};
}

return {
action: 'respond',
statusCode: 500,
body: internalErrorBody,
logLevel: 'error'
};
}

module.exports = {
getX2TFormatCode,
getOutputFormatInfo,
Expand All @@ -207,5 +249,6 @@ module.exports = {
getContentType,
generateX2TConfig,
extractFilePathFromUrl,
isXLSXSignature
isXLSXSignature,
classifySendFileError
};
112 changes: 88 additions & 24 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const {
getDocTypeFromFilename,
isAbsolutePath,
getContentType,
isXLSXSignature
isXLSXSignature,
classifySendFileError
} = require('./server-utils');

if (!process.env.FONT_DATA_DIR) {
Expand Down Expand Up @@ -49,6 +50,43 @@ app.use((req, res, next) => {
next();
});

function sendFileWithHttpErrors(res, filePath, options) {
const {
logPrefix,
notFoundBody,
internalErrorBody,
successMessage
} = options;

res.sendFile(filePath, (err) => {
if (!err) {
if (successMessage) {
console.log(successMessage);
}
return;
}

const failure = classifySendFileError(err, {
notFoundBody,
internalErrorBody
});

if (failure.action === 'ignore') {
return;
}

if (failure.logLevel === 'warn') {
console.warn(`${logPrefix} sendFile returned 404: ${filePath}`);
} else {
console.error(`${logPrefix} Error serving ${filePath}:`, err);
}

if (!res.headersSent) {
res.status(failure.statusCode).send(failure.body);
}
});
}

// API Endpoint: Health check
app.get('/healthcheck', (req, res) => {
res.setHeader('Content-Type', 'text/plain');
Expand Down Expand Up @@ -86,8 +124,12 @@ app.get('/fonts/*', (req, res) => {

res.setHeader('Content-Type', fontContentType);
res.setHeader('Access-Control-Allow-Origin', '*');
res.sendFile(fontPath);
console.log(`[FONTS] Served font: ${fontPath}`);
sendFileWithHttpErrors(res, fontPath, {
logPrefix: '[FONTS]',
notFoundBody: 'Font not found',
internalErrorBody: 'Font error',
successMessage: `[FONTS] Served font: ${fontPath}`
});
} catch (err) {
console.error(`[FONTS] Error serving absolute font ${fontPath}:`, err);
res.status(500).send('Font error');
Expand All @@ -113,7 +155,11 @@ app.get('/document_editor_service_worker.js', (req, res) => {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache');
console.log('[SW] Serving document_editor_service_worker.js');
res.sendFile(workerPath);
sendFileWithHttpErrors(res, workerPath, {
logPrefix: '[SW]',
notFoundBody: 'Service worker not found',
internalErrorBody: 'Service worker error'
});
});

// Serve the desktop AllFonts.js verbatim for metadata parity
Expand All @@ -122,13 +168,10 @@ app.get('/fonts-info.js', (req, res) => {
console.log('[API] GET /fonts-info.js - serving', allFontsPath);
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(allFontsPath, (err) => {
if (err) {
console.error('[API] Error serving AllFonts.js:', err);
if (!res.headersSent) {
res.status(err.statusCode || 500).send('// Failed to load font metadata');
}
}
sendFileWithHttpErrors(res, allFontsPath, {
logPrefix: '[API] Error serving AllFonts.js:',
notFoundBody: '// Failed to load font metadata',
internalErrorBody: '// Failed to load font metadata'
});
});

Expand All @@ -138,13 +181,10 @@ app.get('/sdkjs/common/AllFonts.js', (req, res) => {
console.log('[API] GET /sdkjs/common/AllFonts.js - overriding with desktop AllFonts.js');
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(desktopAllFontsPath, (err) => {
if (err) {
console.error('[API] Error overriding /sdkjs/common/AllFonts.js:', err);
if (!res.headersSent) {
res.status(err.statusCode || 500).send('// Failed to load AllFonts override');
}
}
sendFileWithHttpErrors(res, desktopAllFontsPath, {
logPrefix: '[API] Error overriding /sdkjs/common/AllFonts.js:',
notFoundBody: '// Failed to load AllFonts override',
internalErrorBody: '// Failed to load AllFonts override'
});
});

Expand Down Expand Up @@ -220,7 +260,11 @@ app.get('/api/media/:filehash/:imagefile', (req, res) => {
res.setHeader('Cache-Control', 'public, max-age=31536000'); // Cache for 1 year

console.log(`[MEDIA] Serving image: ${imagePath} (${contentType})`);
res.sendFile(imagePath);
sendFileWithHttpErrors(res, imagePath, {
logPrefix: '[MEDIA]',
notFoundBody: 'Image not found',
internalErrorBody: 'Image error'
});
});

// API Endpoint: Serve arbitrary files within the converted document directory (used for relative resource lookups)
Expand Down Expand Up @@ -249,7 +293,11 @@ app.get('/api/doc-base/:filehash/*', (req, res) => {
return res.status(404).send('File not found');
}

res.sendFile(requestedPath);
sendFileWithHttpErrors(res, requestedPath, {
logPrefix: '[DOC-BASE]',
notFoundBody: 'File not found',
internalErrorBody: 'File error'
});
});

// API Endpoint: List images in media directory for a file
Expand Down Expand Up @@ -660,7 +708,11 @@ app.get('/converted/:filename', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');

console.log(`[CONVERTED] Serving file: ${filePath} (${contentType})`);
res.sendFile(filePath);
sendFileWithHttpErrors(res, filePath, {
logPrefix: '[CONVERTED]',
notFoundBody: 'File not found',
internalErrorBody: 'File error'
});
});

// API Endpoint: Save binary back to XLSX
Expand Down Expand Up @@ -1111,14 +1163,22 @@ app.get('/api/document/:filename', (req, res) => {
app.get('/desktop-stub-utils.js', (req, res) => {
const utilsPath = path.join(__dirname, 'editors', 'desktop-stub-utils.js');
res.setHeader('Content-Type', 'application/javascript');
res.sendFile(utilsPath);
sendFileWithHttpErrors(res, utilsPath, {
logPrefix: '[DESKTOP-STUB-UTILS]',
notFoundBody: 'Asset not found',
internalErrorBody: 'Asset error'
});
});

// Serve desktop-stub.js from the editors directory
app.get('/desktop-stub.js', (req, res) => {
const stubPath = path.join(__dirname, 'editors', 'desktop-stub.js');
res.setHeader('Content-Type', 'application/javascript');
res.sendFile(stubPath);
sendFileWithHttpErrors(res, stubPath, {
logPrefix: '[DESKTOP-STUB]',
notFoundBody: 'Asset not found',
internalErrorBody: 'Asset error'
});
});

// Middleware to inject desktop-stub.js into HTML files
Expand Down Expand Up @@ -1188,7 +1248,11 @@ app.get('*/*.wasm', (req, res, next) => {
if (wasmFiles[filename]) {
const wasmPath = path.join(__dirname, wasmFiles[filename]);
console.log(`[WASM] Redirecting ${req.path} to ${wasmPath}`);
res.sendFile(wasmPath);
sendFileWithHttpErrors(res, wasmPath, {
logPrefix: '[WASM]',
notFoundBody: 'WASM not found',
internalErrorBody: 'WASM error'
});
} else {
next();
}
Expand Down
Loading