(() => { "use strict"; const MESSAGE = Object.freeze({ HOST_READY: "ctms.onlyoffice.host-ready", INIT: "ctms.onlyoffice.init", DOCUMENT_READY: "ctms.onlyoffice.document-ready", WARNING: "ctms.onlyoffice.warning", ERROR: "ctms.onlyoffice.error", DOCUMENT_STATE_CHANGE: "ctms.onlyoffice.document-state-change", SAVE_AS: "ctms.onlyoffice.save-as", SAVE_AS_ERROR: "ctms.onlyoffice.save-as-error", DOWNLOAD: "ctms.onlyoffice.download", DOWNLOAD_ERROR: "ctms.onlyoffice.download-error", REQUEST_EDIT_RIGHTS: "ctms.onlyoffice.request-edit-rights", }); const API_SCRIPT_PATH = "/onlyoffice/web-apps/apps/api/documents/api.js"; const MAX_SAVE_AS_BYTES = 64 * 1024 * 1024; const ALLOWED_TAURI_ORIGINS = new Set([ "tauri://localhost", "http://tauri.localhost", "https://tauri.localhost", ]); let initialized = false; let editor = null; let parentOrigin = null; let requestNonce = null; let apiScriptPromise = null; let readyTimer = null; let readyDeadlineTimer = null; let documentTitle = "download"; const isLoopbackOrigin = (origin) => { try { const url = new URL(origin); return url.protocol === "http:" && ["localhost", "127.0.0.1", "::1", "[::1]"].includes(url.hostname); } catch { return false; } }; const isAllowedParentOrigin = (origin) => origin === window.location.origin || ALLOWED_TAURI_ORIGINS.has(origin) || isLoopbackOrigin(origin); const postToParent = (type, detail, transfer = []) => { if (!parentOrigin || !requestNonce) return; window.parent.postMessage({ type, nonce: requestNonce, detail }, parentOrigin, transfer); }; const safeEventDetail = (event) => { const raw = event && typeof event === "object" && "data" in event ? event.data : event; if (!raw || typeof raw !== "object") return {}; const detail = {}; if (typeof raw.errorCode === "number" || typeof raw.errorCode === "string") detail.errorCode = raw.errorCode; if (typeof raw.errorDescription === "string") detail.errorDescription = raw.errorDescription.slice(0, 500); if (typeof raw.warningCode === "number" || typeof raw.warningCode === "string") detail.warningCode = raw.warningCode; if (typeof raw.warningDescription === "string") detail.warningDescription = raw.warningDescription.slice(0, 500); return detail; }; const loadOnlyOfficeApi = () => { if (window.DocsAPI?.DocEditor) return Promise.resolve(); if (apiScriptPromise) return apiScriptPromise; apiScriptPromise = new Promise((resolve, reject) => { const script = document.createElement("script"); script.src = API_SCRIPT_PATH; script.async = true; script.addEventListener("load", () => { if (window.DocsAPI?.DocEditor) resolve(); else reject(new Error("ONLYOFFICE API 未正确加载")); }, { once: true }); script.addEventListener("error", () => reject(new Error("ONLYOFFICE API 加载失败")), { once: true }); document.head.appendChild(script); }); return apiScriptPromise; }; const saveAsEventDetail = (event) => { const raw = event && typeof event === "object" && "data" in event ? event.data : null; if (!raw || typeof raw !== "object") throw new Error("另存为数据格式不正确"); const fileType = typeof raw.fileType === "string" ? raw.fileType.toLowerCase() : ""; const title = typeof raw.title === "string" ? raw.title.trim().slice(0, 240) : ""; if (!/^[a-z0-9]{1,16}$/.test(fileType) || !title || typeof raw.url !== "string") { throw new Error("另存为文件信息不完整"); } const url = new URL(raw.url, window.location.origin); if (url.origin !== window.location.origin || !url.pathname.startsWith("/onlyoffice/")) { throw new Error("另存为文件地址不可信"); } return { fileType, title, url }; }; const handleRequestSaveAs = async (event) => { try { const { fileType, title, url } = saveAsEventDetail(event); const response = await fetch(url, { cache: "no-store", credentials: "omit", redirect: "error", }); if (!response.ok) throw new Error("另存为文件生成失败"); const declaredSize = Number(response.headers.get("content-length") || "0"); if (declaredSize > MAX_SAVE_AS_BYTES) throw new Error("另存为文件超出大小限制"); const data = await response.arrayBuffer(); if (!data.byteLength || data.byteLength > MAX_SAVE_AS_BYTES) throw new Error("另存为文件内容无效"); const mimeType = (response.headers.get("content-type") || "application/octet-stream").slice(0, 120); postToParent(MESSAGE.SAVE_AS, { fileType, title, mimeType, data }, [data]); } catch (error) { postToParent(MESSAGE.SAVE_AS_ERROR, { message: error instanceof Error ? error.message.slice(0, 200) : "另存为失败", }); } }; const downloadEventDetail = (event) => { const raw = event && typeof event === "object" && "data" in event ? event.data : null; if (!raw || typeof raw !== "object") throw new Error("下载文件数据格式不正确"); const fileType = typeof raw.fileType === "string" ? raw.fileType.toLowerCase() : ""; if (!/^[a-z0-9]{1,16}$/.test(fileType) || typeof raw.url !== "string") { throw new Error("下载文件信息不完整"); } const url = new URL(raw.url, window.location.origin); if (url.origin !== window.location.origin || !url.pathname.startsWith("/onlyoffice/")) { throw new Error("下载文件地址不可信"); } const suffix = `.${fileType}`; const stem = documentTitle.toLowerCase().endsWith(suffix) ? documentTitle.slice(0, -suffix.length) : documentTitle.replace(/\.[^.]+$/, ""); return { fileType, title: `${stem}${suffix}`, url }; }; const handleDownloadAs = async (event) => { try { const { fileType, title, url } = downloadEventDetail(event); const response = await fetch(url, { cache: "no-store", credentials: "omit", redirect: "error", }); if (!response.ok) throw new Error("下载文件生成失败"); const declaredSize = Number(response.headers.get("content-length") || "0"); if (declaredSize > MAX_SAVE_AS_BYTES) throw new Error("下载文件超出大小限制"); const data = await response.arrayBuffer(); if (!data.byteLength || data.byteLength > MAX_SAVE_AS_BYTES) throw new Error("下载文件内容无效"); const mimeType = (response.headers.get("content-type") || "application/octet-stream").slice(0, 120); postToParent(MESSAGE.DOWNLOAD, { fileType, title, mimeType, data }, [data]); } catch (error) { postToParent(MESSAGE.DOWNLOAD_ERROR, { message: error instanceof Error ? error.message.slice(0, 200) : "下载失败", }); } }; const destroyEditor = () => { if (editor && typeof editor.destroyEditor === "function") { try { editor.destroyEditor(); } catch { /* The remote editor may already have been torn down. */ } } editor = null; }; const stopReadyAnnouncements = () => { if (readyTimer !== null) window.clearInterval(readyTimer); if (readyDeadlineTimer !== null) window.clearTimeout(readyDeadlineTimer); readyTimer = null; readyDeadlineTimer = null; }; const announceReady = () => { if (!initialized) window.parent.postMessage({ type: MESSAGE.HOST_READY }, "*"); }; const initializeEditor = async (message) => { const config = message?.config; if (!config || typeof config !== "object" || typeof message?.nonce !== "string" || !message.nonce) { throw new Error("预览配置格式不正确"); } requestNonce = message.nonce; documentTitle = typeof config.document?.title === "string" && config.document.title.trim() ? config.document.title.trim().slice(0, 240) : "download"; await loadOnlyOfficeApi(); const events = { onDocumentReady: () => postToParent(MESSAGE.DOCUMENT_READY), onWarning: (event) => postToParent(MESSAGE.WARNING, safeEventDetail(event)), onError: (event) => postToParent(MESSAGE.ERROR, safeEventDetail(event)), onDocumentStateChange: (event) => postToParent(MESSAGE.DOCUMENT_STATE_CHANGE, { changed: Boolean(event && typeof event === "object" && "data" in event ? event.data : event), }), onRequestEditRights: () => postToParent(MESSAGE.REQUEST_EDIT_RIGHTS), }; if (message?.allowSaveAs === true) events.onRequestSaveAs = handleRequestSaveAs; if (message?.allowDownload === true) events.onDownloadAs = handleDownloadAs; const editorConfig = { ...config, events, }; editor = new window.DocsAPI.DocEditor("onlyoffice-editor", editorConfig); }; window.addEventListener("message", async (event) => { if (event.source !== window.parent || initialized || !isAllowedParentOrigin(event.origin)) return; if (event.data?.type !== MESSAGE.INIT) return; initialized = true; stopReadyAnnouncements(); parentOrigin = event.origin; requestNonce = typeof event.data?.nonce === "string" ? event.data.nonce : null; try { await initializeEditor(event.data); } catch (error) { postToParent(MESSAGE.ERROR, { errorDescription: error instanceof Error ? error.message.slice(0, 500) : "Office 预览初始化失败", }); } }); window.addEventListener("pagehide", () => { stopReadyAnnouncements(); destroyEditor(); }, { once: true }); announceReady(); readyTimer = window.setInterval(announceReady, 250); readyDeadlineTimer = window.setTimeout(stopReadyAnnouncements, 15_000); })();