etherpad-lite/src/node/hooks/express/admin.ts
John McLear 7ea9970648
Hardening: API request handling, random IDs, and plugin loading (#7906)
* Hardening: API request handling, token generation, and plugin loading

- pad_utils.randomString: generate the random IDs via crypto.getRandomValues
  (CSPRNG) instead of Math.random.
- OAuth2Provider: constant-time password comparison and a uniform failure delay
  on the OIDC interaction login; own-property user lookup.
- API.appendChatMessage: require the pad to already exist (getPadSafe),
  consistent with the other content API methods.
- RestAPI /api/2: forward only the authorization header rather than merging all
  request headers into the API field set.
- LinkInstaller: validate plugin dependency names before building filesystem
  paths from them.
- admin file server: return a generic error message and log details server-side.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address review: timingSafeEqual on raw bytes; align /api/2 auth fallback

- OAuth2Provider.constantTimeEquals: compare raw UTF-8 bytes with
  crypto.timingSafeEqual instead of hashing them first. Resolves the CodeQL
  "password hash with insufficient computational effort" alert while keeping a
  content-independent comparison (length difference is covered by the uniform
  failure delay).
- RestAPI /api/2: fall back to the authorization header whenever the field is
  falsy (not only null), matching the openapi.ts handler so the two routers
  authenticate identically (Qodo).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* appendChatMessage: throw explicit error instead of getPadSafe (review)

Per review: replace the getPadSafe(padID, true) existence check with an
explicit `throw new CustomError('padID does not exist', 'apierror')` so chat
messages can't create pads, without fetching the pad.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 19:17:39 +02:00

102 lines
3.7 KiB
TypeScript

'use strict';
import {ArgsExpressType} from "../../types/ArgsExpressType";
import path from "path";
import fs from "fs";
import {MapArrayType} from "../../types/MapType";
import settings from 'ep_etherpad-lite/node/utils/Settings';
import {sanitizeProxyPath} from '../../utils/sanitizeProxyPath';
const ADMIN_PATH = path.join(settings.root, 'src', 'templates');
const PROXY_HEADER = "x-proxy-path"
/**
* Add the admin navigation link
* @param hookName {String} the name of the hook
* @param args {Object} the object containing the arguments
* @param {Function} cb the callback function
* @return {*}
*/
exports.expressCreateServer = (hookName: string, args: ArgsExpressType, cb: Function): any => {
if (!fs.existsSync(ADMIN_PATH)) {
console.error('admin template not found, skipping admin interface. You need to rebuild it in /admin with pnpm run build-copy')
return cb();
}
args.app.get('/admin/{*filename}', (req: any, res: any) => {
// extract URL path
let pathname = path.join(ADMIN_PATH, req.url);
pathname = path.normalize(pathname)
if (!pathname.startsWith(ADMIN_PATH)) {
res.statusCode = 403;
return res.end("Forbidden");
}
// based on the URL path, extract the file extension. e.g. .js, .doc, ...
let ext = path.parse(pathname).ext;
// maps file extension to MIME typere
const map: MapArrayType<string> = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
fs.exists(pathname, function (exist) {
if (!exist) {
// if the file is not found, return 404
res.statusCode = 200;
pathname = ADMIN_PATH + "/admin/index.html"
ext = path.parse(pathname).ext;
}
// if is a directory search for index file matching the extension
if (exist && fs.statSync(pathname).isDirectory()) {
pathname = pathname + '/index.html';
ext = path.parse(pathname).ext;
}
// read file from file system
fs.readFile(pathname, function (err, data) {
if (err) {
// Log the detailed error server-side; return a generic message to the
// client rather than echoing the filesystem error.
console.error(`admin: error reading ${pathname}: ${err}`);
res.statusCode = 500;
res.end('Error getting the file.');
} else {
let dataToSend:Buffer|string = data
// if the file is found, set Content-type and send data
res.setHeader('Content-type', map[ext] || 'text/plain');
if (ext === ".html" || ext === ".js" || ext === ".css") {
// The proxy-path header is woven into the response body, so
// it must be sanitised before substitution and downstream
// caches must not collapse responses across different
// header values.
const proxyPath = sanitizeProxyPath(req);
if (proxyPath) {
let string = data.toString()
dataToSend = string.replaceAll("/admin", proxyPath + "/admin")
dataToSend = dataToSend.replaceAll(
"/socket.io", proxyPath + "/socket.io")
}
res.setHeader('Vary', 'x-proxy-path');
res.setHeader('Cache-Control', 'private, no-store');
}
res.end(dataToSend);
}
});
})
});
args.app.get('/admin', (req: any, res: any, next: Function) => {
if ('/' !== req.path[req.path.length - 1]) return res.redirect('./admin/');
})
return cb();
};