Add WordCraft and DeckCraft office editors with protected server saves

This commit is contained in:
SantaSpeen committed 2026-10-22 19:25:22 +03:00
1 parent bc9709e500
commit 6e36b6c4b7
20 files changed
+582 -40

No files matched your search

+11 -1
View File
@@ -6,7 +6,17 @@
<div class="addon-grid">
<article v-for="addon in store.items" :key="addon.id" class="addon-card">
<div class="addon-details">
<AppIcon :name="addon.id === 'gridcraft' ? 'table' : 'description'" />
<AppIcon
:name="
addon.id === 'gridcraft'
? 'table'
: addon.id === 'deckcraft'
? 'slideshow'
: addon.id === 'wordcraft'
? 'editDocument'
: 'description'
"
/>
<div>
<strong>{{ addon.name }}</strong
><small
+2
View File
@@ -404,6 +404,8 @@
"error": "Something went wrong"
},
"createTypes": {
"docx": "Word document",
"pptx": "Presentation",
"text": "Text file",
"markdown": "Markdown document",
"csv": "CSV spreadsheet",
+2
View File
@@ -401,6 +401,8 @@
"error": "Не удалось выполнить"
},
"createTypes": {
"docx": "Текстовый документ",
"pptx": "Презентация",
"text": "Текстовый файл",
"markdown": "Документ Markdown",
"csv": "Таблица CSV",
+1 -1
View File
@@ -33,7 +33,7 @@ const titles = {
const routes = [
{
path: "/editor/:addon(gridcraft|pdfcraft)",
path: "/editor/:addon(wordcraft|gridcraft|deckcraft|pdfcraft)",
name: "CraftEditor",
component: () => import("@/views/files/CraftEditor.vue"),
meta: { requiresAuth: true },
@@ -18,9 +18,6 @@ it("provides valid starter content and a safe fallback for unknown template IDs"
expect(new Set(fileTemplates.map((template) => template.id)).size).toBe(
fileTemplates.length
);
expect(
fileTemplates.some((template) =>
[".docx", ".pptx"].includes(template.extension)
)
).toBe(false);
expect(fileTemplate("docx").craft).toBe("wordcraft");
expect(fileTemplate("pptx").craft).toBe("deckcraft");
});
@@ -0,0 +1,147 @@
import { readFileSync } from "node:fs";
import vm from "node:vm";
import { expect, it, vi } from "vitest";
const source = readFileSync(
new URL("../../../../http/craft_bridge.js", import.meta.url),
"utf8"
);
function bridge(id = "wordcraft") {
const messages: any[] = [],
events = new Map<string, (event: any) => void>();
const parent = { postMessage: (message: any) => messages.push(message) };
const canvas = { dispatchEvent: vi.fn(), focus: vi.fn() };
class Anchor {
href = "";
download = "";
click = undefined;
}
// Prototype interception must behave like a real DOM anchor.
const nativeClick = vi.fn();
Object.defineProperty(Anchor.prototype, "click", {
value: nativeClick,
writable: true,
});
class LocalURL extends URL {}
let counter = 0;
LocalURL.createObjectURL = () => "blob:test/" + ++counter;
LocalURL.revokeObjectURL = vi.fn();
const context: any = {
parent,
location: {
pathname: `/addons/${id}/build/index.html`,
search: "?host=parent",
origin: "https://files.test",
},
document: {
documentElement: {},
getElementById: (name: string) =>
name === id + "_canvas" ? canvas : null,
},
addEventListener: (name: string, callback: any) =>
events.set(name, callback),
MutationObserver: class {
observe() {}
disconnect() {}
},
DataTransfer: class {
items = { add: vi.fn() };
},
DragEvent: class {
constructor(
public type: string,
public options: unknown
) {}
},
HTMLAnchorElement: Anchor,
URL: LocalURL,
URLSearchParams,
Blob,
File,
ArrayBuffer,
DOMException,
Map,
Promise,
};
context.window = context;
vm.runInNewContext(source, context);
const receive = (data: unknown, overrides = {}) =>
events.get("message")!({
source: parent,
origin: "https://files.test",
data,
...overrides,
});
return { context, messages, canvas, receive, nativeClick, Anchor, events };
}
it("opens the server document once and rejects messages from other origins or frames", () => {
const { receive, canvas, messages } = bridge();
expect(messages[0].type).toBe("wordcraft:ready");
const open = {
type: "wordcraft:open",
name: "report.docx",
bytes: new ArrayBuffer(8),
};
receive(open, { origin: "https://evil.test" });
receive(open, { source: {} });
expect(canvas.dispatchEvent).not.toHaveBeenCalled();
receive(open);
receive(open);
expect(canvas.dispatchEvent).toHaveBeenCalledTimes(1);
});
it("keeps Save pending until the server acknowledges the actual write", async () => {
const { context, messages, receive } = bridge();
const file = await context.showSaveFilePicker({
suggestedName: "report.docx",
});
const writer = await file.createWritable();
await writer.write(new Uint8Array([1, 2, 3]));
let completed = false;
const saved = writer.close().then(() => {
completed = true;
});
await vi.waitFor(() =>
expect(messages.some((m) => m.type === "wordcraft:save")).toBe(true)
);
const message = messages.find((m) => m.type === "wordcraft:save");
expect(new Uint8Array(message.bytes)).toEqual(new Uint8Array([1, 2, 3]));
expect(completed).toBe(false);
receive({ type: "wordcraft:saved", requestId: message.requestId });
await saved;
expect(completed).toBe(true);
});
it("rejects failed writes and bounds memory before accepting document data", async () => {
const { context, messages, receive } = bridge();
const writer = await (
await context.showSaveFilePicker({ suggestedName: "report.docx" })
).createWritable();
await expect(
writer.write(new Uint8Array(64 * 1024 * 1024 + 1))
).rejects.toThrow("64 MiB");
await writer.write(new Uint8Array([1]));
const saved = writer.close();
const rejected = expect(saved).rejects.toThrow("Server could not save");
await vi.waitFor(() =>
expect(messages.some((m) => m.type === "wordcraft:save")).toBe(true)
);
receive({
type: "wordcraft:save-error",
requestId: messages.find((m) => m.type === "wordcraft:save").requestId,
});
await rejected;
});
it("captures presentation saves but preserves native downloads for unrelated exports", async () => {
const { context, messages, nativeClick } = bridge("deckcraft");
// DOM instances don't have an own click member.
const link = Object.create(context.HTMLAnchorElement.prototype);
link.href = context.URL.createObjectURL(new Blob(["presentation"]));
link.download = "slides.pptx";
link.click();
await vi.waitFor(() =>
expect(messages.some((m) => m.type === "deckcraft:save")).toBe(true)
);
expect(nativeClick).not.toHaveBeenCalled();
link.download = "slide.png";
link.click();
expect(nativeClick).toHaveBeenCalledTimes(1);
});
+1
View File
@@ -46,6 +46,7 @@ export function craftMessage(
return null;
return event.data as {
type: string;
requestId?: string;
name?: string;
bytes?: ArrayBuffer;
dirty?: boolean;
+14
View File
@@ -6,6 +6,20 @@ interface FileTemplate {
craft?: string;
}
export const fileTemplates: readonly FileTemplate[] = [
{
id: "docx",
extension: ".docx",
icon: "editDocument",
content: "",
craft: "wordcraft",
},
{
id: "pptx",
extension: ".pptx",
icon: "slideshow",
content: "",
craft: "deckcraft",
},
{
id: "xlsx",
extension: ".xlsx",
+5 -1
View File
@@ -76,7 +76,11 @@ const currentView = computed(() => {
if (fileStore.req.isDir) {
return FileListing;
}
if (["gridcraft", "pdfcraft"].includes(String(route.query.craft)))
if (
["wordcraft", "gridcraft", "deckcraft", "pdfcraft"].includes(
String(route.query.craft)
)
)
return CraftEditor;
if (
route.query.edit === "true" &&
+22 -10
View File
@@ -99,6 +99,9 @@ const file = files.req,
: file?.path || "";
const currentPath = ref(sourcePath),
currentName = ref(sourcePath.split("/").pop() || "");
const nativeExtension = computed(
() => store.items.find((item) => item.id === id)?.extension || ""
);
const title = computed(
() => store.items.find((item) => item.id === id)?.name || id
);
@@ -116,6 +119,7 @@ interface Save {
path: string;
create: boolean;
revision: number;
requestId?: string;
}
const pending = ref<Save>();
const authExpired = ref(false);
@@ -204,10 +208,13 @@ async function persist() {
);
if (disposed) return;
success = true;
if (payload.requestId)
frame.value?.contentWindow?.postMessage(
{ type: id + ":saved", requestId: payload.requestId },
window.location.origin
);
authExpired.value = false;
if (
payload.path.toLowerCase().endsWith(id === "gridcraft" ? ".xlsx" : ".pdf")
) {
if (payload.path.toLowerCase().endsWith(nativeExtension.value)) {
tag = response.headers.get("ETag") || "";
currentPath.value = payload.path;
currentName.value = payload.name;
@@ -219,6 +226,11 @@ async function persist() {
}
} catch (failure) {
if (!disposed) {
if (payload.requestId)
frame.value?.contentWindow?.postMessage(
{ type: id + ":save-error", requestId: payload.requestId },
window.location.origin
);
if (failure instanceof StatusError && failure.status === 401)
authExpired.value = true;
error.value =
@@ -237,9 +249,7 @@ function confirmSaveAs() {
if (!pending.value) return;
const ext = pending.value.name.toLowerCase().endsWith(".pdf")
? ".pdf"
: id === "gridcraft"
? ".xlsx"
: ".pdf";
: nativeExtension.value;
const name = safeCraftName(newName.value, ext);
if (!name) {
error.value = t("addons.invalidName");
@@ -299,9 +309,7 @@ function receive(event: MessageEvent) {
}
const extension = message.name?.toLowerCase().endsWith(".pdf")
? ".pdf"
: id === "gridcraft"
? ".xlsx"
: ".pdf";
: nativeExtension.value;
const name = safeCraftName(message.name, extension);
if (!name) {
error.value = t("addons.invalidName");
@@ -311,9 +319,13 @@ function receive(event: MessageEvent) {
pending.value = {
bytes: message.bytes,
name,
path: currentPath.value,
path: create
? currentPath.value.slice(0, currentPath.value.lastIndexOf("/") + 1) +
name
: currentPath.value,
create,
revision,
requestId: message.requestId,
};
if (create) {
newName.value = name;