Files
wekan/models/lib/sanitizeSvg.js
T
Lauri Ojansivu c71a97cba2 **Fixed OpenAPI REST API documentation generation**, which had been broken
since after WeKan v7.93 and only generated docs for the `login`/`register`
endpoints (2 operations) instead of the full API. The Meteor 3 migration moved
the REST routes from `models/*.js` (`JsonRoutes.add(...)`) into
`server/models/*.js` (`WebApp.handlers.get/post/put/delete(...)`) and
introduced optional chaining (`?.`) that the `esprima` Python parser cannot
read, so `openapi/generate_openapi.py` silently skipped every route file.
The generator now understands both routing styles, scans both `models/` and
`server/models/`, downlevels modern JS syntax so files parse, handles the
`type: Array` SimpleSchema idiom, and `releases/rebuild-docs.sh` works directly
with Python 3.12.x (PEP 668). The generated `public/api/wekan.yml` /
`wekan.html` now cover the full API again (89 operations / 61 paths).
Thanks to Claude.

**Documented the attachment / file REST API in the OpenAPI docs** — file
upload, download, info, listing a board's files, copy, move and delete (the
`/api/attachment/*` endpoints registered via `WebApp.handlers.use()`, which the
generator cannot auto-discover) are now documented in `openapi/extra_paths.yml`
and injected into the generated docs, including their authentication and
permission requirements. Thanks to Claude.

**Security: attachment write operations in the REST/DDP API now require board
write access, not just membership (CWE-862, CWE-639).** Both attachment API
implementations (`server/routes/attachmentApi.js` HTTP routes and
`server/attachmentApi.js` Meteor methods) gated upload / copy / move / delete
on `board.hasMember()`, which is true for any active member regardless of role.
This let read-only, comment-only, no-comments, worker and assigned-only board
members add, copy, move and delete attachments through the API — actions the UI
forbids for those roles. They now require board write access (global site
admins still allowed); read operations (download / list / info) keep
membership-level access. Added security tests in
`server/lib/tests/attachmentApi.tests.js`. Thanks to Claude.

**The attachment copy API now honours the admin "Admin Panel / Attachments"
API transfer limits.** Copying an attachment creates a new attachment but
skipped the `apiUploadBlocked` / `apiUploadMaxBytes` checks that upload
enforces; copy now respects them in both API implementations. Thanks to Claude.

**SVG image uploads are now sanitized instead of rejected.** Uploaded SVGs
(attachments and avatars) are cleaned in place in `onAfterUpload` via the new
`models/lib/sanitizeSvg.js`, which removes JavaScript (`<script>`, inline
`on*=` event handlers, `javascript:`/`vbscript:` URIs, `<foreignObject>` /
`<iframe>` / `<object>` / `<embed>` and similar active content) and XML loops
(`<!DOCTYPE>` / `<!ENTITY>` entity-expansion / XXE constructs and
`<?xml-stylesheet?>`), so SVG images can be uploaded safely.

Thanks to Claude.
2026-06-05 23:44:04 +03:00

100 lines
3.6 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import fs from 'fs';
// SVG sanitization for uploaded files.
//
// SVG is XML and can carry active content: <script> elements, inline event
// handlers (onload=, onclick=, ...), javascript:/vbscript: URIs, HTML embedded
// via <foreignObject>/<iframe>/<object>/<embed>, and XML DOCTYPE/ENTITY
// declarations that enable entity-expansion ("billion laughs" / XML loop) and
// external-entity (XXE) attacks.
//
// Rather than rejecting such files we strip the dangerous constructs so the
// image still uploads but cannot execute script or expand entities. The set of
// constructs removed here is kept in sync with the detection patterns in
// models/fileValidation.js (containsJsOrXmlBombs), so a sanitized file passes
// validation afterwards.
//
// This is a string/regex sanitizer (the server has no DOM, so DOMPurify is not
// available without jsdom). It is intentionally aggressive — when in doubt it
// removes content.
// Active-content elements that can run JavaScript or load remote/HTML content.
const DANGEROUS_ELEMENTS = [
'script',
'foreignObject',
'iframe',
'object',
'embed',
'handler',
'set',
'animate',
'animateTransform',
'animateMotion',
];
export function sanitizeSvgContent(svg) {
if (typeof svg !== 'string' || svg.length === 0) {
return { content: svg, changed: false };
}
let out = svg;
// XML loops / XXE: remove DOCTYPE (including any internal DTD subset with
// <!ENTITY ...> definitions) and any stray ENTITY declarations.
out = out.replace(/<!DOCTYPE[\s\S]*?>/gi, '');
out = out.replace(/<!ENTITY[\s\S]*?>/gi, '');
// Remove <?xml-stylesheet ...?> processing instructions (keep the leading
// <?xml ...?> declaration, which is harmless).
out = out.replace(/<\?xml-stylesheet[\s\S]*?\?>/gi, '');
// Remove dangerous elements, both paired (<tag>...</tag>) and self-closing.
for (const tag of DANGEROUS_ELEMENTS) {
out = out.replace(new RegExp(`<${tag}\\b[\\s\\S]*?<\\/${tag}\\s*>`, 'gi'), '');
out = out.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, 'gi'), '');
}
// Remove <meta http-equiv="refresh" ...> redirects.
out = out.replace(/<meta\b[^>]*http-equiv\s*=\s*['"]?\s*refresh[^>]*>/gi, '');
// Strip inline event-handler attributes (onload=, onclick=, onmouseover=, ...).
out = out.replace(/\son[a-z][a-z0-9_-]*\s*=\s*"[^"]*"/gi, '');
out = out.replace(/\son[a-z][a-z0-9_-]*\s*=\s*'[^']*'/gi, '');
out = out.replace(/\son[a-z][a-z0-9_-]*\s*=\s*[^\s>]+/gi, '');
// Neutralize javascript:/vbscript: URIs (in href, xlink:href, style url(), ...).
out = out.replace(/(javascript|vbscript)\s*:/gi, 'removed:');
return { content: out, changed: out !== svg };
}
// Returns true when a file looks like an SVG (by MIME type or .svg extension).
export function isSvgFile(mimeType, fileName) {
const mime = (mimeType || '').toLowerCase();
if (mime === 'image/svg+xml' || mime === 'image/svg') {
return true;
}
return /\.svg$/i.test(fileName || '');
}
// Sanitize an SVG file in place. Returns the new byte size when the file was
// rewritten, or null when nothing changed / the file could not be processed.
export function sanitizeSvgFileSync(filePath) {
if (!Meteor.isServer || !filePath) {
return null;
}
try {
const original = fs.readFileSync(filePath, 'utf8');
const { content, changed } = sanitizeSvgContent(original);
if (!changed) {
return null;
}
fs.writeFileSync(filePath, content, 'utf8');
return Buffer.byteLength(content, 'utf8');
} catch (error) {
console.error('[sanitizeSvgFileSync] failed to sanitize', filePath, error);
return null;
}
}