302 lines
13 KiB
JavaScript
302 lines
13 KiB
JavaScript
"use strict";
|
|
|
|
// Tests pinning the editor data-loss contract between index.js's socket
|
|
// readFile handler and bot.js's editor error handling.
|
|
//
|
|
// History: node daemons used to answer a failed read by returning the literal
|
|
// placeholder strings "/* ERROR: server not found on node */" or
|
|
// "/* ERROR: failed to load file */" as if they were file content. Opening
|
|
// such a "file" in the editor and hitting save overwrote the real file
|
|
// (server.properties etc.) with the placeholder. The fix has two halves that
|
|
// must never drift apart:
|
|
// 1. index.js reports read failures as { error } on the same "fileData"
|
|
// event (mirroring the /files/read HTTP endpoint) and never as content.
|
|
// 2. bot.js refuses to open or save marker content (blocklist + guards at
|
|
// every layer: fileData handler, openEditorModal, performSave).
|
|
// This file pins both halves by source assertion (same technique as
|
|
// file-action-token-mint-gates) plus real execution of the blocklist matcher,
|
|
// so re-introducing a marker emission, dropping a guard, or letting the two
|
|
// lists drift fails loudly here.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const vm = require("node:vm");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const botSource = fs.readFileSync(BOT_JS, "utf8");
|
|
|
|
const LEGACY_MARKERS = [
|
|
"/* ERROR: server not found on node */",
|
|
"/* ERROR: failed to load file */",
|
|
];
|
|
|
|
function extractRegion(source, startMarker, endMarker, label) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
|
|
const end = source.indexOf(endMarker, start);
|
|
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
// --- 1. index.js: read failures are { error } payloads, never content ---
|
|
|
|
const readFileHandler = extractRegion(
|
|
indexSource,
|
|
'socket.on("readFile"',
|
|
'socket.on("writeFile"',
|
|
"index.js socket readFile handler"
|
|
);
|
|
|
|
test("index.js readFile handler emits fileData failures as { error } with no content field", () => {
|
|
const emits = readFileHandler.match(/socket\.emit\("fileData",[^;]*\);/g) || [];
|
|
assert.equal(
|
|
emits.length, 4,
|
|
"expected exactly four fileData emissions in the readFile handler (two failures, one binary, one success)"
|
|
);
|
|
|
|
const failureEmits = emits.filter((e) => /\berror:/.test(e));
|
|
const binaryEmits = emits.filter((e) => /\bbinary: true/.test(e));
|
|
const successEmits = emits.filter((e) => /\bcontent:/.test(e));
|
|
assert.equal(failureEmits.length, 2, "both failure branches must emit an error payload");
|
|
assert.equal(binaryEmits.length, 1, "the binary branch must emit a binary marker payload");
|
|
assert.equal(successEmits.length, 1, "only the success branch may emit content");
|
|
for (const e of failureEmits) {
|
|
assert.doesNotMatch(
|
|
e, /\bcontent:/,
|
|
`a failure emission must never carry a content field: ${e}`
|
|
);
|
|
}
|
|
// The binary marker must never carry content: the editor would otherwise
|
|
// round-trip mangled text over the original binary file.
|
|
for (const e of binaryEmits) {
|
|
assert.doesNotMatch(
|
|
e, /\bcontent:/,
|
|
`the binary emission must never carry a content field: ${e}`
|
|
);
|
|
}
|
|
|
|
// The two concrete failure branches keep their { path, error } shape.
|
|
assert.match(readFileHandler, /if \(!ctx\.remote\) return socket\.emit\("fileData", \{ path: rel, error: "server not found on node" \}\);/);
|
|
assert.match(readFileHandler, /socket\.emit\("fileData", \{ path: rel, error: "node read failed" \}\);/);
|
|
});
|
|
|
|
test("index.js readFile handler never fabricates a legacy marker as file content", () => {
|
|
for (const marker of LEGACY_MARKERS) {
|
|
const offending = indexSource
|
|
.split("\n")
|
|
.map((line, i) => ({ line: line.trim(), no: i + 1 }))
|
|
.filter(({ line }) => line.includes(marker));
|
|
for (const { line, no } of offending) {
|
|
// Allowed only inside comments (index.js currently has none at all).
|
|
assert.ok(
|
|
line.startsWith("//") || line.startsWith("*") || line.startsWith("/*"),
|
|
`index.js:${no} contains a legacy marker outside a comment: ${line}`
|
|
);
|
|
}
|
|
assert.equal(
|
|
offending.length, 0,
|
|
"index.js should not reference the legacy markers at all (failures are { error } payloads)"
|
|
);
|
|
}
|
|
});
|
|
|
|
// --- 2. bot.js: the blocklist is the single home of the legacy markers ---
|
|
|
|
const blocklistRegion = extractRegion(
|
|
botSource,
|
|
"const EDITOR_ERROR_CONTENT_MARKERS = [",
|
|
'socket.on("fileData"',
|
|
"bot.js EDITOR_ERROR_CONTENT_MARKERS blocklist"
|
|
);
|
|
|
|
test("bot.js blocklist contains exactly the two legacy markers (lists cannot drift apart)", () => {
|
|
// Slice just the array literal so the matcher's own string literals below
|
|
// are not mistaken for markers.
|
|
const arrayStart = blocklistRegion.indexOf("[");
|
|
const arrayEnd = blocklistRegion.indexOf("];", arrayStart);
|
|
assert.ok(arrayEnd > arrayStart, "blocklist array literal not found");
|
|
const listed = [...blocklistRegion.slice(arrayStart, arrayEnd).matchAll(/"([^"]+)"/g)].map((m) => m[1]);
|
|
assert.deepEqual(
|
|
listed.sort(), [...LEGACY_MARKERS].sort(),
|
|
"EDITOR_ERROR_CONTENT_MARKERS must list exactly the legacy markers index.js no longer emits"
|
|
);
|
|
});
|
|
|
|
test("legacy marker strings appear nowhere in bot.js outside the blocklist definition", () => {
|
|
const withoutBlocklist = botSource.replace(blocklistRegion, "");
|
|
for (const marker of LEGACY_MARKERS) {
|
|
assert.ok(
|
|
!withoutBlocklist.includes(marker),
|
|
`marker "${marker}" must only exist inside the EDITOR_ERROR_CONTENT_MARKERS array`
|
|
);
|
|
}
|
|
});
|
|
|
|
test("isEditorErrorContent matches only exact (trimmed) marker content", () => {
|
|
// Execute the real blocklist + matcher, not a copy of it.
|
|
const sandbox = {};
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(blocklistRegion, sandbox);
|
|
const isEditorErrorContent = sandbox.isEditorErrorContent;
|
|
assert.equal(typeof isEditorErrorContent, "function", "matcher must be defined next to the blocklist");
|
|
|
|
assert.equal(isEditorErrorContent("/* ERROR: server not found on node */"), true);
|
|
assert.equal(isEditorErrorContent("/* ERROR: failed to load file */"), true);
|
|
assert.equal(isEditorErrorContent(" /* ERROR: failed to load file */ "), true, "whitespace-padded marker is still a marker");
|
|
assert.equal(isEditorErrorContent("prefix /* ERROR: failed to load file */ suffix"), false, "a real file that merely contains the marker line must stay openable");
|
|
assert.equal(isEditorErrorContent("server.properties content"), false);
|
|
assert.equal(isEditorErrorContent(""), false);
|
|
assert.equal(isEditorErrorContent(null), false);
|
|
assert.equal(isEditorErrorContent(undefined), false);
|
|
});
|
|
|
|
// --- 3. bot.js: the fileData handler fails closed before opening the editor ---
|
|
|
|
const fileDataHandler = extractRegion(
|
|
botSource,
|
|
'socket.on("fileData"',
|
|
"async function loadServerInfo",
|
|
"bot.js fileData handler"
|
|
);
|
|
|
|
test("bot.js fileData handler returns early on d.error or marker content before openEditorModal", () => {
|
|
const guardAt = fileDataHandler.indexOf("if (d.error || isEditorErrorContent(d.content)) {");
|
|
assert.ok(guardAt >= 0, "fileData handler must guard on d.error || isEditorErrorContent(d.content)");
|
|
const openAt = fileDataHandler.indexOf("openEditorModal(d.path, d.content, request);");
|
|
assert.ok(openAt > guardAt, "the guard must run before any openEditorModal call");
|
|
assert.equal(
|
|
(fileDataHandler.match(/openEditorModal\(/g) || []).length, 1,
|
|
"openEditorModal must be reachable only after the guard in the fileData handler"
|
|
);
|
|
const guardBlock = fileDataHandler.slice(guardAt, openAt);
|
|
assert.match(guardBlock, /showStoreToast\(/, "a refused load must surface a user-visible toast");
|
|
assert.match(guardBlock, /return;\s*\}/, "a refused load must return before openEditorModal");
|
|
});
|
|
|
|
test("openEditorModal itself refuses marker content (belt-and-braces entry point)", () => {
|
|
const region = extractRegion(
|
|
botSource,
|
|
"async function openEditorModal(path, content, request) {",
|
|
"currentEditorPath = path || \"\";",
|
|
"bot.js openEditorModal entry"
|
|
);
|
|
assert.match(
|
|
region, /if \(isEditorErrorContent\(content\)\) \{[\s\S]*?return;/,
|
|
"openEditorModal must bounce marker content before touching editor state"
|
|
);
|
|
});
|
|
|
|
test("the editor switches buffer, filename and hash together and ignores stale opens", async () => {
|
|
const functions = extractRegion(botSource, "async function openEditorModal(", "function closeEditorModal(", "editor open");
|
|
let signalLoader;
|
|
const waitForLoader = () => new Promise((resolve) => { signalLoader = resolve; });
|
|
const notifications = [];
|
|
const noop = () => {};
|
|
const { open, state, setText, documentGeneration } = vm.runInNewContext(`
|
|
let editorOpenGeneration = 0;
|
|
let editorDocumentGeneration = 0;
|
|
let currentEditorPath = "first.txt";
|
|
let editorBaseSha256 = "hash:first";
|
|
let editorOriginalContent = "first";
|
|
let value = "first";
|
|
const editorPath = { textContent: currentEditorPath };
|
|
const editorHistoryPushed = true;
|
|
const editorSaving = false;
|
|
const getCurrentEditorValue = () => value;
|
|
const openAceEditor = (text) => { value = text; };
|
|
${functions}
|
|
({
|
|
open: (file, content) => openEditorModal(file, content, { generation: ++editorOpenGeneration, sourceValue: value }),
|
|
state: () => [editorPath.textContent, value, editorBaseSha256].join("|"),
|
|
setText: (text) => { value = text; },
|
|
documentGeneration: () => editorDocumentGeneration,
|
|
});`, {
|
|
isEditorErrorContent: () => false,
|
|
computeEditorBaseSha256: async (content) => `hash:${content}`,
|
|
shouldUseAceFallback: () => new Promise((resolve) => signalLoader(resolve)),
|
|
editorModal: { classList: { contains: () => false } },
|
|
normalizeInput: (content) => content.replace(/\r\n/g, "\n"),
|
|
showModalElement: noop,
|
|
setEditorSaveButtonState: noop,
|
|
updateEditorSaveDirtyState: noop,
|
|
renderMiniFm: noop,
|
|
showStoreToast: (message) => notifications.push(message),
|
|
});
|
|
|
|
const earlierLoader = waitForLoader();
|
|
const earlierOpen = open("second.txt", "second");
|
|
const finishEarlier = await earlierLoader;
|
|
assert.strictEqual(state(), "first.txt|first|hash:first");
|
|
assert.strictEqual(documentGeneration(), 0);
|
|
const newestLoader = waitForLoader();
|
|
const newestOpen = open("third.txt", "third\r\nline");
|
|
const finishNewest = await newestLoader;
|
|
finishNewest(true);
|
|
await newestOpen;
|
|
assert.strictEqual(state(), "third.txt|third\nline|hash:third\r\nline");
|
|
finishEarlier(true);
|
|
await earlierOpen;
|
|
assert.strictEqual(state(), "third.txt|third\nline|hash:third\r\nline");
|
|
assert.strictEqual(documentGeneration(), 1);
|
|
|
|
const editLoader = waitForLoader();
|
|
const openWhileEditing = open("fourth.txt", "fourth");
|
|
const finishWhileEditing = await editLoader;
|
|
setText("new draft");
|
|
finishWhileEditing(true);
|
|
await openWhileEditing;
|
|
assert.strictEqual(state(), "third.txt|new draft|hash:third\r\nline");
|
|
assert.strictEqual(notifications.length, 1);
|
|
assert.strictEqual(documentGeneration(), 1);
|
|
});
|
|
|
|
test("ordinary close preserves a draft unless confirmed, while explicit discard closes directly", () => {
|
|
const closeSource = extractRegion(botSource, "function closeEditorModal(", "function setEditorSaveButtonState(", "editor close");
|
|
let confirmations = 0;
|
|
let closes = 0;
|
|
const { close, documentGeneration } = vm.runInNewContext(`
|
|
let editorOpenGeneration = 0;
|
|
let editorDocumentGeneration = 0;
|
|
let pendingEditorRead = null;
|
|
${closeSource}
|
|
({ close: closeEditorModal, documentGeneration: () => editorDocumentGeneration });`, {
|
|
editorModal: {},
|
|
editorHistoryPushed: false,
|
|
isEditorDirty: () => true,
|
|
confirm: () => { confirmations++; return false; },
|
|
animateClose: () => { closes++; },
|
|
});
|
|
close();
|
|
assert.strictEqual(closes, 0);
|
|
assert.strictEqual(confirmations, 1);
|
|
assert.strictEqual(documentGeneration(), 0);
|
|
close({ discard: true });
|
|
assert.strictEqual(closes, 1);
|
|
assert.strictEqual(confirmations, 1);
|
|
assert.strictEqual(documentGeneration(), 1);
|
|
});
|
|
|
|
// --- 4. bot.js: performSave refuses to persist either half of a bad load ---
|
|
|
|
const performSaveHead = extractRegion(
|
|
botSource,
|
|
"async function performSave(opts = {}) {",
|
|
"editorSaving = true;",
|
|
"bot.js performSave guard region"
|
|
);
|
|
|
|
test("performSave blocks saving when contentToSave OR editorOriginalContent is a marker", () => {
|
|
assert.match(
|
|
performSaveHead,
|
|
/if \(isEditorErrorContent\(contentToSave\) \|\| isEditorErrorContent\(editorOriginalContent\)\) \{/,
|
|
"the save guard must test BOTH the pending content and the loaded original"
|
|
);
|
|
assert.match(performSaveHead, /return false;/, "a blocked save must report failure to its caller");
|
|
});
|