265 lines
14 KiB
JavaScript
265 lines
14 KiB
JavaScript
/* Trusted local document renderer. No application token or remote attachment URL enters this page. */
|
|
(function () {
|
|
'use strict';
|
|
var params = new URLSearchParams(window.location.search);
|
|
var requestId = params.get('requestId') || '';
|
|
var kind = params.get('type') || '';
|
|
var content = document.getElementById('document');
|
|
var status = document.getElementById('status');
|
|
var finished = false;
|
|
var limits = { source: 30 * 1024 * 1024, text: 5 * 1024 * 1024, entries: 1000, item: 20 * 1024 * 1024, total: 100 * 1024 * 1024 };
|
|
|
|
/** Send only request-scoped, explicitly understood messages to the native host. */
|
|
function post(type, fields) {
|
|
var message = { type: type, requestId: requestId };
|
|
Object.keys(fields || {}).forEach(function (key) { message[key] = fields[key]; });
|
|
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.trainingDocument) {
|
|
window.webkit.messageHandlers.trainingDocument.postMessage(message);
|
|
} else if (window.TrainingDocument && typeof window.TrainingDocument.postMessage === 'function') {
|
|
window.TrainingDocument.postMessage(JSON.stringify(message));
|
|
}
|
|
}
|
|
|
|
function previewError(code, message) {
|
|
var error = new Error(message);
|
|
error.previewCode = code;
|
|
return error;
|
|
}
|
|
|
|
function fail(error) {
|
|
if (finished) { return; }
|
|
finished = true;
|
|
content.hidden = true;
|
|
content.textContent = '';
|
|
status.hidden = false;
|
|
status.textContent = error && error.message ? error.message : '附件无法预览,请重试';
|
|
post('error', { code: error.previewCode || 'render_failed', message: status.textContent });
|
|
}
|
|
|
|
/** XHR also works for local WKURLSchemeHandler resources without exposing remote origins. */
|
|
function loadBytes() {
|
|
return new Promise(function (resolve, reject) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', './document/' + requestId + '/file', true);
|
|
xhr.responseType = 'arraybuffer';
|
|
xhr.timeout = 30000;
|
|
xhr.withCredentials = false;
|
|
xhr.onprogress = function (event) {
|
|
if (event.loaded > limits.source) {
|
|
xhr.abort();
|
|
reject(previewError('file_too_large', '附件超过 30 MB,暂时无法预览'));
|
|
}
|
|
};
|
|
xhr.onload = function () {
|
|
if (xhr.status !== 0 && (xhr.status < 200 || xhr.status >= 300)) {
|
|
reject(previewError('document_unavailable', '附件加载失败,请重试')); return;
|
|
}
|
|
if (!(xhr.response instanceof ArrayBuffer) || !xhr.response.byteLength) {
|
|
reject(previewError('empty_document', '附件内容为空')); return;
|
|
}
|
|
if (xhr.response.byteLength > limits.source) {
|
|
reject(previewError('file_too_large', '附件超过 30 MB,暂时无法预览')); return;
|
|
}
|
|
resolve(xhr.response);
|
|
};
|
|
xhr.onerror = function () { reject(previewError('document_unavailable', '附件加载失败,请重试')); };
|
|
xhr.ontimeout = function () { reject(previewError('document_timeout', '附件加载超时,请重试')); };
|
|
xhr.onabort = function () { reject(previewError('document_cancelled', '附件加载已取消')); };
|
|
xhr.send();
|
|
});
|
|
}
|
|
|
|
/** Decode common Chinese text encodings, refusing binary input rather than showing corrupt markup. */
|
|
function decodeText(buffer) {
|
|
if (buffer.byteLength > limits.text) { throw previewError('text_too_large', '文本附件超过 5 MB,暂时无法预览'); }
|
|
var bytes = new Uint8Array(buffer);
|
|
var encoding = 'utf-8';
|
|
if (bytes[0] === 0xff && bytes[1] === 0xfe) { encoding = 'utf-16le'; }
|
|
else if (bytes[0] === 0xfe && bytes[1] === 0xff) { encoding = 'utf-16be'; }
|
|
else {
|
|
// Some TXT exporters omit the UTF-16 byte-order mark.
|
|
var evenNul = 0; var oddNul = 0; var count = Math.min(bytes.length, 256);
|
|
for (var i = 0; i < count; i += 1) { if (!bytes[i]) { if (i % 2) { oddNul += 1; } else { evenNul += 1; } } }
|
|
if (count > 4 && oddNul > count / 5 && evenNul === 0) { encoding = 'utf-16le'; }
|
|
else if (count > 4 && evenNul > count / 5 && oddNul === 0) { encoding = 'utf-16be'; }
|
|
}
|
|
var text;
|
|
try { text = new TextDecoder(encoding, { fatal: true }).decode(bytes); }
|
|
catch (error) {
|
|
if (encoding !== 'utf-8') { throw previewError('unsupported_encoding', '附件文本编码无法识别'); }
|
|
try { text = new TextDecoder('gb18030', { fatal: true }).decode(bytes); }
|
|
catch (fallbackError) { throw previewError('unsupported_encoding', '附件文本编码无法识别'); }
|
|
}
|
|
if (/[\u0000-\u0008\u000e-\u001f]/.test(text)) { throw previewError('invalid_text', '附件不是可预览的文本文件'); }
|
|
if (!text.trim()) { throw previewError('empty_document', '附件内容为空'); }
|
|
return text.replace(/^\uFEFF/, '');
|
|
}
|
|
|
|
/** Check advertised ZIP sizes before any decompression; ZIP64, encryption, split archives are unsupported. */
|
|
function checkZipDirectory(buffer) {
|
|
var view = new DataView(buffer);
|
|
var end = -1;
|
|
for (var i = buffer.byteLength - 22; i >= Math.max(0, buffer.byteLength - 65557); i -= 1) {
|
|
if (view.getUint32(i, true) === 0x06054b50 && i + 22 + view.getUint16(i + 20, true) === buffer.byteLength) { end = i; break; }
|
|
}
|
|
if (end < 0 || view.getUint16(end + 4, true) || view.getUint16(end + 6, true)) { throw previewError('invalid_docx', 'DOCX 文件损坏或格式不受支持'); }
|
|
var count = view.getUint16(end + 10, true);
|
|
var cursor = view.getUint32(end + 16, true);
|
|
var directorySize = view.getUint32(end + 12, true);
|
|
if (count > limits.entries || count === 0xffff || cursor + directorySize > end) { throw previewError('docx_too_large', 'DOCX 结构过大,暂时无法预览'); }
|
|
var total = 0;
|
|
for (var item = 0; item < count; item += 1) {
|
|
if (cursor + 46 > end || view.getUint32(cursor, true) !== 0x02014b50) { throw previewError('invalid_docx', 'DOCX 文件结构不完整'); }
|
|
var size = view.getUint32(cursor + 24, true);
|
|
var flags = view.getUint16(cursor + 8, true);
|
|
var compression = view.getUint16(cursor + 10, true);
|
|
if ((flags & 1) || (compression !== 0 && compression !== 8)) { throw previewError('encrypted_docx', '暂不支持加密的 DOCX 附件'); }
|
|
total += size;
|
|
if (size > limits.item || total > limits.total) { throw previewError('docx_too_large', 'DOCX 解压后内容过大,暂时无法预览'); }
|
|
cursor += 46 + view.getUint16(cursor + 28, true) + view.getUint16(cursor + 30, true) + view.getUint16(cursor + 32, true);
|
|
}
|
|
if (cursor !== view.getUint32(end + 16, true) + directorySize) { throw previewError('invalid_docx', 'DOCX 文件结构不完整'); }
|
|
}
|
|
|
|
/** Bound actual inflated bytes as well as directory declarations before docx-preview reads entries. */
|
|
async function validateDocx(buffer) {
|
|
checkZipDirectory(buffer);
|
|
var zip = await JSZip.loadAsync(buffer);
|
|
var names = Object.keys(zip.files);
|
|
if (!zip.file('word/document.xml') || !zip.file('[Content_Types].xml') || names.length > limits.entries) {
|
|
throw previewError('invalid_docx', '附件不是有效的 DOCX 文件');
|
|
}
|
|
var total = 0;
|
|
for (var i = 0; i < names.length; i += 1) {
|
|
var entry = zip.files[names[i]];
|
|
if (entry.dir) { continue; }
|
|
await new Promise(function (resolve, reject) {
|
|
var size = 0;
|
|
var stream = entry.internalStream('uint8array');
|
|
stream.on('data', function (chunk) {
|
|
size += chunk.length; total += chunk.length;
|
|
if (size > limits.item || total > limits.total) {
|
|
stream.pause(); reject(previewError('docx_too_large', 'DOCX 解压后内容过大,暂时无法预览'));
|
|
}
|
|
});
|
|
stream.on('error', function () { reject(previewError('invalid_docx', 'DOCX 文件损坏,无法预览')); });
|
|
stream.on('end', resolve);
|
|
stream.resume();
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Remove network-bearing attributes before connecting sanitized document nodes to the visible tree. */
|
|
function cleanDocument(root) {
|
|
root.querySelectorAll('img').forEach(function (image) {
|
|
var src = image.getAttribute('src') || '';
|
|
if (!/^(?:blob:|data:image\/(?:png|jpeg|gif|webp|bmp);base64,)/i.test(src)) {
|
|
var fallback = document.createElement('span');
|
|
fallback.textContent = image.getAttribute('alt') || '';
|
|
image.parentNode.replaceChild(fallback, image);
|
|
return;
|
|
}
|
|
image.removeAttribute('srcset');
|
|
image.removeAttribute('onload');
|
|
image.removeAttribute('onerror');
|
|
});
|
|
root.querySelectorAll('[href]').forEach(function (link) {
|
|
var href = link.getAttribute('href') || '';
|
|
if (!/^(https?:\/\/|#)/i.test(href)) { link.removeAttribute('href'); }
|
|
link.removeAttribute('target');
|
|
link.removeAttribute('download');
|
|
link.setAttribute('rel', 'noopener noreferrer');
|
|
});
|
|
root.querySelectorAll('[style]').forEach(function (element) {
|
|
var style = element.getAttribute('style');
|
|
if (/(?:url\s*\(|@import|expression\s*\()/i.test(style || '')) { element.removeAttribute('style'); }
|
|
});
|
|
root.querySelectorAll('style').forEach(function (sheet) {
|
|
if (/(?:@import|url\s*\((?!\s*["']?(?:blob:|data:)))/i.test(sheet.textContent || '')) { sheet.remove(); }
|
|
});
|
|
}
|
|
|
|
async function render(buffer) {
|
|
if (kind === 'txt') {
|
|
var pre = document.createElement('pre');
|
|
pre.textContent = decodeText(buffer);
|
|
content.appendChild(pre);
|
|
} else if (kind === 'md') {
|
|
var parser = window.markdownit({ html: false, linkify: false, typographer: false, breaks: true });
|
|
var html = parser.render(decodeText(buffer));
|
|
var fragment = DOMPurify.sanitize(html, { RETURN_DOM_FRAGMENT: true, USE_PROFILES: { html: true }, FORBID_TAGS: ['style', 'form', 'input', 'button', 'iframe', 'object', 'embed', 'video', 'audio'] });
|
|
cleanDocument(fragment);
|
|
content.appendChild(fragment);
|
|
} else {
|
|
await validateDocx(buffer);
|
|
var body = document.createElement('div');
|
|
var styles = document.createElement('div');
|
|
await window.docx.renderAsync(buffer, body, styles, {
|
|
className: 'docx', inWrapper: true, ignoreWidth: true, ignoreHeight: true,
|
|
ignoreFonts: true, breakPages: false, experimental: false, renderChanges: false,
|
|
renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
|
|
renderComments: false, renderAltChunks: false, useBase64URL: false
|
|
});
|
|
var combined = document.createElement('div');
|
|
combined.appendChild(styles); combined.appendChild(body);
|
|
var safe = DOMPurify.sanitize(combined, {
|
|
RETURN_DOM_FRAGMENT: true, ADD_TAGS: ['style'], ADD_ATTR: ['style'],
|
|
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'video', 'audio', 'svg', 'math'],
|
|
ALLOWED_URI_REGEXP: /^(?:(?:https?|blob):|data:image\/|#)/i,
|
|
ALLOW_DATA_ATTR: false
|
|
});
|
|
cleanDocument(safe);
|
|
var pages = safe.querySelectorAll('section.docx');
|
|
var hasText = Array.prototype.some.call(pages, function (page) { return page.textContent.trim().length > 0; });
|
|
if (!hasText && !safe.querySelector('img[src]')) { throw previewError('empty_document', 'DOCX 文件没有可预览的内容'); }
|
|
content.appendChild(safe);
|
|
}
|
|
}
|
|
|
|
/** Wait for visible content and images to settle, then two paint opportunities before allowing reading time. */
|
|
async function visibleReady() {
|
|
status.hidden = true;
|
|
content.hidden = false;
|
|
var images = Array.prototype.slice.call(content.querySelectorAll('img[src]'));
|
|
await Promise.all(images.map(function (image) {
|
|
if (image.complete) { return Promise.resolve(); }
|
|
return new Promise(function (resolve) {
|
|
var timeout = setTimeout(function () { image.removeAttribute('src'); resolve(); }, 8000);
|
|
var complete = function () { clearTimeout(timeout); resolve(); };
|
|
image.addEventListener('load', complete, { once: true });
|
|
image.addEventListener('error', complete, { once: true });
|
|
});
|
|
}));
|
|
if (document.fonts && document.fonts.ready) { await document.fonts.ready; }
|
|
await new Promise(function (resolve) { requestAnimationFrame(function () { requestAnimationFrame(resolve); }); });
|
|
if (finished) { return; }
|
|
if (content.getBoundingClientRect().height <= 0) { throw previewError('render_failed', '附件内容尚未显示,请重试'); }
|
|
finished = true;
|
|
post('ready', { height: Math.ceil(Math.max(content.scrollHeight, content.getBoundingClientRect().height)) });
|
|
}
|
|
|
|
// Block every generated link from navigating this trusted local shell.
|
|
document.addEventListener('click', function (event) {
|
|
var element = event.target instanceof Element ? event.target.closest('a') : null;
|
|
if (!element) { return; }
|
|
event.preventDefault();
|
|
var href = element.getAttribute('href') || '';
|
|
if (/^https?:\/\//i.test(href)) {
|
|
try {
|
|
var url = new URL(href);
|
|
if ((url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password) { post('link', { url: url.href }); }
|
|
} catch (error) { /* Malformed or unsupported destinations do not leave the document. */ }
|
|
} else if (href.charAt(0) === '#') {
|
|
var anchor = document.getElementById(href.slice(1));
|
|
if (anchor) { anchor.scrollIntoView(); }
|
|
}
|
|
}, true);
|
|
|
|
if (!/^[A-Za-z0-9_-]{1,80}$/.test(requestId) || ['docx', 'txt', 'md'].indexOf(kind) === -1) {
|
|
fail(previewError('unsupported_type', '暂不支持此附件格式')); return;
|
|
}
|
|
loadBytes().then(render).then(visibleReady).catch(function (error) {
|
|
fail(error.previewCode ? error : previewError('render_failed', '附件无法预览,文件可能已损坏'));
|
|
});
|
|
}());
|