Audit the project and secure toolbox data
This commit is contained in:
parent
96af62edf0
commit
e87edda5c7
40 changed files with 2324 additions and 125 deletions
|
|
@ -4,6 +4,8 @@ import assert from "node:assert/strict";
|
|||
import { createPersistenceQueue } from "../website/src/features/toolboxes/storage/persistenceQueue.js";
|
||||
import { useToolboxActions } from "../website/src/features/toolboxes/useToolboxActions.js";
|
||||
import { applyModuleDataValue, removeModuleDataKeys } from "../website/src/features/toolboxes/storage/optimisticModuleData.js";
|
||||
import { DEFERRED_MODULE_DATA } from "../website/src/features/toolboxes/storage/deferredModuleData.js";
|
||||
import { createStorageMutation } from "../website/src/features/toolboxes/storage/storageMutation.js";
|
||||
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
|
|
@ -81,7 +83,15 @@ test("imports merge after file reading and preserve edits queued during the tran
|
|||
});
|
||||
const imported = actions.importToolbox({ text: () => fileRead.promise }, "game");
|
||||
await queue.enqueue((s) => ({ ...s, moduleData: { note: "B" } }), async (next) => { disk = next; });
|
||||
fileRead.resolve(JSON.stringify({ toolbox: { id: "source", name: "Import", modules: [] }, modules: {} }));
|
||||
fileRead.resolve(JSON.stringify({
|
||||
version: 2,
|
||||
toolbox: {
|
||||
id: "source", name: "Import", modules: [],
|
||||
spaces: [{ id: "default", name: "Défaut", moduleOrder: { one: [], two: [[], []] } }],
|
||||
defaultSpaceId: "default", activeSpaceId: "default"
|
||||
},
|
||||
modules: {}
|
||||
}));
|
||||
await Promise.resolve();
|
||||
assert.equal(notices.length, 0);
|
||||
const edit = queue.enqueue((s) => ({ ...s, moduleData: { ...s.moduleData, note: "C" } }), async (next) => { disk = next; });
|
||||
|
|
@ -124,9 +134,15 @@ test("global imports started from the same render both survive", async () => {
|
|||
setConfirmModal: (value) => assert.fail(value.message)
|
||||
});
|
||||
const file = (id) => ({ text: async () => JSON.stringify({
|
||||
toolboxes: [{ id, name: id, modules: [{ id: "note", type: "notepad" }] }],
|
||||
version: 2,
|
||||
exportedAt: "2026-10-14T12:00:00.000Z",
|
||||
toolboxes: [{
|
||||
id, name: id, modules: [{ id: "note", type: "notepad" }],
|
||||
spaces: [{ id: "default", name: "Défaut", moduleOrder: { one: ["note"], two: [["note"], []] } }],
|
||||
defaultSpaceId: "default", activeSpaceId: "default"
|
||||
}],
|
||||
links: { [id]: id },
|
||||
modules: { [`${id}:note`]: { text: id } }
|
||||
modules: { [`${id}:note`]: { pages: [{ id: "page", title: "Page 1", html: `<p>${id}</p>`, text: id }] } }
|
||||
}) });
|
||||
assert.deepEqual(await Promise.all([
|
||||
actions.importAllToolboxes(file("one")), actions.importAllToolboxes(file("two"))
|
||||
|
|
@ -160,7 +176,7 @@ test("v2 imports reject more than five spaces before writing", async () => {
|
|||
}) });
|
||||
assert.equal(result, null);
|
||||
assert.equal(writes, 0);
|
||||
assert.match(errorMessage, /plus de 5 espaces/);
|
||||
assert.match(errorMessage, /entre 1 et 5 espaces/);
|
||||
});
|
||||
|
||||
test("failed toolbox deletion preserves registry links and modules together", async () => {
|
||||
|
|
@ -182,3 +198,60 @@ test("failed toolbox deletion preserves registry links and modules together", as
|
|||
assert.equal(await deleted, false);
|
||||
assert.deepEqual(queue.getCurrent(), initial);
|
||||
});
|
||||
|
||||
test("storage mutations target independent records and preserve deferred media deletions", () => {
|
||||
const expected = {
|
||||
toolboxes: [{ id: "a", modules: [{ id: "media", type: "images" }] }],
|
||||
links: { game: "a" },
|
||||
moduleData: { "a:media": DEFERRED_MODULE_DATA, "a:note": { text: "A" } }
|
||||
};
|
||||
const next = {
|
||||
toolboxes: [
|
||||
{ id: "b", modules: [{ id: "note", type: "notepad" }] },
|
||||
{ id: "a", modules: [] }
|
||||
],
|
||||
links: { game: "a", other: "b" },
|
||||
moduleData: { "a:note": { text: "A" }, "b:note": { text: "B" } }
|
||||
};
|
||||
const mutation = createStorageMutation(expected, next);
|
||||
assert.deepEqual(mutation.toolboxes.changes.map((change) => change.key).sort(), ["a", "b"]);
|
||||
assert.deepEqual(mutation.links.map((change) => change.key), ["other"]);
|
||||
assert.deepEqual(mutation.modules.map((change) => [change.key, change.expected, change.nextExists]), [
|
||||
["a:media", "any", false],
|
||||
["b:note", "missing", true]
|
||||
]);
|
||||
});
|
||||
|
||||
test("the persistence queue adopts the canonical stored state returned by a write", async () => {
|
||||
const initial = { toolboxes: ["local"], moduleData: {} };
|
||||
const canonical = { toolboxes: ["remote", "local"], moduleData: {} };
|
||||
const published = [];
|
||||
const queue = createPersistenceQueue(initial, (state) => published.push(state));
|
||||
const success = await queue.enqueue(
|
||||
(current) => ({ ...current, toolboxes: ["new", ...current.toolboxes] }),
|
||||
async () => canonical
|
||||
);
|
||||
assert.equal(success, true);
|
||||
assert.deepEqual(queue.getCurrent(), canonical);
|
||||
assert.deepEqual(published.at(-1), canonical);
|
||||
});
|
||||
|
||||
test("a storage conflict rebases pending operations on the confirmed remote state", async () => {
|
||||
const initial = { value: "initial", independent: 0 };
|
||||
const remote = { value: "remote", independent: 0 };
|
||||
const queue = createPersistenceQueue(initial, () => {});
|
||||
const conflict = queue.enqueue(
|
||||
(current) => ({ ...current, value: "local" }),
|
||||
async () => {
|
||||
const error = new Error("conflict");
|
||||
error.confirmedState = remote;
|
||||
throw error;
|
||||
}
|
||||
);
|
||||
const independent = queue.enqueue(
|
||||
(current) => ({ ...current, independent: current.independent + 1 }),
|
||||
async (next) => next
|
||||
);
|
||||
assert.deepEqual(await Promise.all([conflict, independent]), [false, true]);
|
||||
assert.deepEqual(queue.getCurrent(), { value: "remote", independent: 1 });
|
||||
});
|
||||
|
|
|
|||
225
tests/toolbox-import-validation.test.mjs
Normal file
225
tests/toolbox-import-validation.test.mjs
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
// Rôle : vérifie le contrat v2 des imports avant remappage et écriture.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { TOOLBOX_MODULE_DEFINITIONS } from "../website/src/features/toolboxes/toolboxModuleRegistry.js";
|
||||
import { useToolboxActions } from "../website/src/features/toolboxes/useToolboxActions.js";
|
||||
import { createGlobalExportPayload, createToolboxExportPayload } from "../website/src/features/toolboxes/storage/toolboxStorage.js";
|
||||
import { validateToolboxImportPayload } from "../website/src/features/toolboxes/storage/toolboxImportValidation.js";
|
||||
|
||||
const MODULE_TYPES = Object.keys(TOOLBOX_MODULE_DEFINITIONS);
|
||||
|
||||
function sourceToolbox() {
|
||||
const modules = MODULE_TYPES.map((type) => ({ id: type === "taskPlanner" ? "planner" : type, type }));
|
||||
const chunks = Array.from({ length: 5 }, () => []);
|
||||
modules.forEach((module, index) => chunks[index % chunks.length].push(module.id));
|
||||
const spaces = chunks.map((ids, index) => ({
|
||||
id: `space-${index + 1}`,
|
||||
name: index ? `Espace ${index + 1}` : "Défaut",
|
||||
moduleOrder: { one: ids, two: [ids.filter((_, itemIndex) => itemIndex % 2 === 0), ids.filter((_, itemIndex) => itemIndex % 2 === 1)] }
|
||||
}));
|
||||
return {
|
||||
id: "source", name: "Tous les outils", modules, spaces,
|
||||
defaultSpaceId: spaces[0].id, activeSpaceId: spaces[4].id,
|
||||
updatedAt: "2026-10-14T12:00:00.000Z"
|
||||
};
|
||||
}
|
||||
|
||||
function sourceModuleData() {
|
||||
return {
|
||||
"source:notepad": { pages: [{ id: "page", title: "Page 1", html: "<p>Notes</p>", text: "Notes" }] },
|
||||
"source:memos": { plannerLink: "planner", items: [{ id: "memo", text: "Préparer", color: "#f6c453" }] },
|
||||
"source:checklist": { items: [{ id: "item", label: "Objet", qtyTarget: 2 }] },
|
||||
"source:images": { images: [{ id: "image", label: "Carte", dataUrl: "data:image/png;base64,AA==" }] },
|
||||
"source:imageAnnotation": {
|
||||
image: "data:image/png;base64,AA==",
|
||||
markers: [{ id: "marker", x: 25, y: 75, label: "Cible" }]
|
||||
},
|
||||
"source:links": { links: [{ id: "link", title: "Guide", url: "https://example.com/" }] },
|
||||
"source:counters": { counters: [{ id: "counter", label: "Score", value: 12 }] },
|
||||
"source:randomizer": { wheel: { entries: [{ id: "choice", label: "Choix", weight: 1 }] } },
|
||||
"source:rngSimulator": { rates: [{ id: "rate", label: "Rare", rate: "5" }] },
|
||||
"source:combos": { combos: [{ id: "combo", name: "Attaque", inputs: [[{ kind: "button", value: "cross" }]] }] },
|
||||
"source:planner": {
|
||||
tasks: [{ id: "parent", title: "Parent", type: "unique" }, { id: "child", title: "Enfant", type: "daily" }],
|
||||
relations: [{ id: "relation", fromTaskId: "child", toTaskId: "parent" }]
|
||||
},
|
||||
"source:calculator": {
|
||||
entries: [{ id: "root", label: "Total", value: 2 }, { id: "child", parentId: "root", label: "Part", value: 1 }]
|
||||
},
|
||||
"source:equipmentPlanner": {
|
||||
types: [{ id: "type", title: "Armure" }],
|
||||
equipments: [{
|
||||
id: "equipment", typeId: "type", name: "Casque",
|
||||
socketItems: [{ id: "socket-a", name: "A" }, { id: "socket-b", name: "B" }],
|
||||
socketLinks: [{ id: "socket-link", fromSocketItemId: "socket-a", toSocketItemId: "socket-b" }]
|
||||
}]
|
||||
},
|
||||
"source:calendar": { events: [{ id: "event", title: "Raid", dayIndex: 2, startMinutes: 120 }] },
|
||||
"source:table": { rows: 2, columns: 2, cells: { A1: "2", B1: "=A1*2" } },
|
||||
"source:timer": { countdowns: [{ id: "countdown", label: "Départ", type: "duration", durationMs: 60000, targetAt: 100000 }] },
|
||||
"source:goalTree": {
|
||||
nodes: [
|
||||
{ id: "goal", title: "Objectif" },
|
||||
{ id: "step", parentId: "goal", title: "Étape", kind: "text", items: [{ id: "goal-item", label: "Détail" }] }
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function validIndividualPayload() {
|
||||
return JSON.parse(JSON.stringify(createToolboxExportPayload(sourceToolbox(), sourceModuleData())));
|
||||
}
|
||||
|
||||
function clone(value) {
|
||||
return structuredClone(value);
|
||||
}
|
||||
|
||||
test("a v2 individual export round-trips all registered tool types and five spaces", async () => {
|
||||
const payload = validIndividualPayload();
|
||||
assert.equal(payload.toolbox.modules.length, 17);
|
||||
assert.equal(payload.toolbox.spaces.length, 5);
|
||||
assert.equal(validateToolboxImportPayload(payload, "single"), payload);
|
||||
|
||||
let state = { toolboxes: [], links: {}, moduleData: {} };
|
||||
const actions = useToolboxActions({
|
||||
store: {
|
||||
ready: true,
|
||||
persistToolboxSnapshot: async (updater) => {
|
||||
state = { ...state, ...updater(state) };
|
||||
return true;
|
||||
}
|
||||
},
|
||||
notify() {},
|
||||
setConfirmModal: (value) => assert.fail(value.message)
|
||||
});
|
||||
const imported = await actions.importToolbox({ text: async () => JSON.stringify(payload) });
|
||||
assert.ok(imported);
|
||||
assert.deepEqual(imported.modules.map((module) => module.type).sort(), MODULE_TYPES.toSorted());
|
||||
assert.equal(imported.spaces.length, 5);
|
||||
|
||||
const roundTrip = JSON.parse(JSON.stringify(createToolboxExportPayload(imported, state.moduleData)));
|
||||
validateToolboxImportPayload(roundTrip, "single");
|
||||
assert.deepEqual(roundTrip.toolbox.modules.map((module) => module.type).sort(), MODULE_TYPES.toSorted());
|
||||
assert.equal(Object.keys(roundTrip.modules).length, MODULE_TYPES.length);
|
||||
const memos = roundTrip.toolbox.modules.find((module) => module.type === "memos");
|
||||
const planner = roundTrip.toolbox.modules.find((module) => module.type === "taskPlanner");
|
||||
assert.equal(roundTrip.modules[memos.id].plannerLink, planner.id);
|
||||
});
|
||||
|
||||
test("compact empty individual and global v2 exports remain valid", () => {
|
||||
const toolbox = {
|
||||
id: "empty", name: "Vide", modules: [],
|
||||
spaces: [{ id: "default", name: "Défaut", moduleOrder: { one: [], two: [[], []] } }],
|
||||
defaultSpaceId: "default", activeSpaceId: "default", updatedAt: "2026-10-14T12:00:00.000Z"
|
||||
};
|
||||
const individual = createToolboxExportPayload(toolbox, {});
|
||||
validateToolboxImportPayload(individual, "single");
|
||||
const global = createGlobalExportPayload([], {}, {});
|
||||
validateToolboxImportPayload(global, "global");
|
||||
});
|
||||
|
||||
test("unknown versions, tool types and duplicate ids are rejected with their location", () => {
|
||||
const version = clone(validIndividualPayload());
|
||||
version.version = 999;
|
||||
assert.throws(() => validateToolboxImportPayload(version), /version 999 non prise en charge/);
|
||||
|
||||
const type = clone(validIndividualPayload());
|
||||
type.toolbox.modules[0].type = "unknown";
|
||||
assert.throws(() => validateToolboxImportPayload(type), /modules\[0\]\.type « unknown » est inconnu/);
|
||||
|
||||
const duplicate = clone(validIndividualPayload());
|
||||
duplicate.toolbox.modules[1].id = duplicate.toolbox.modules[0].id;
|
||||
assert.throws(() => validateToolboxImportPayload(duplicate), /identifiant dupliqué/);
|
||||
});
|
||||
|
||||
test("orphan storage, space and business references are rejected", () => {
|
||||
const moduleData = clone(validIndividualPayload());
|
||||
moduleData.modules.orphan = { pages: [{ id: "page", title: "Page 1", text: "Orpheline", html: "<p>Orpheline</p>" }] };
|
||||
assert.throws(() => validateToolboxImportPayload(moduleData), /ne correspond à aucun outil déclaré/);
|
||||
|
||||
const order = clone(validIndividualPayload());
|
||||
order.toolbox.spaces[0].moduleOrder.one[0] = "missing";
|
||||
assert.throws(() => validateToolboxImportPayload(order), /référence l'identifiant absent « missing »/);
|
||||
|
||||
const planner = clone(validIndividualPayload());
|
||||
const memosId = planner.toolbox.modules.find((module) => module.type === "memos").id;
|
||||
planner.modules[memosId].plannerLink = "missing";
|
||||
assert.throws(() => validateToolboxImportPayload(planner), /plannerLink référence un planificateur absent/);
|
||||
|
||||
const memos = clone(validIndividualPayload());
|
||||
const duplicateMemosId = memos.toolbox.modules.find((module) => module.type === "memos").id;
|
||||
memos.modules[duplicateMemosId].items.push(clone(memos.modules[duplicateMemosId].items[0]));
|
||||
assert.throws(() => validateToolboxImportPayload(memos), /identifiant dupliqué/);
|
||||
});
|
||||
|
||||
test("global imports reject duplicate toolboxes, orphan module keys and orphan game links", () => {
|
||||
const toolbox = sourceToolbox();
|
||||
const payload = createGlobalExportPayload([toolbox], { game: toolbox.id }, sourceModuleData());
|
||||
validateToolboxImportPayload(payload, "global");
|
||||
|
||||
const duplicate = clone(payload);
|
||||
duplicate.toolboxes.push(clone(duplicate.toolboxes[0]));
|
||||
assert.throws(() => validateToolboxImportPayload(duplicate, "global"), /identifiant dupliqué « source » dans toolboxes/);
|
||||
|
||||
const moduleData = clone(payload);
|
||||
moduleData.modules["source:missing"] = { pages: [{ id: "page", title: "Page 1", text: "X", html: "<p>X</p>" }] };
|
||||
assert.throws(() => validateToolboxImportPayload(moduleData, "global"), /ne correspond à aucun outil déclaré/);
|
||||
|
||||
const link = clone(payload);
|
||||
link.links.game = "missing";
|
||||
assert.throws(() => validateToolboxImportPayload(link, "global"), /links\.game référence l'identifiant absent/);
|
||||
});
|
||||
|
||||
test("a global import remaps toolbox, game and planner references together", async () => {
|
||||
const toolbox = sourceToolbox();
|
||||
const payload = JSON.parse(JSON.stringify(createGlobalExportPayload(
|
||||
[toolbox],
|
||||
{ game: toolbox.id },
|
||||
sourceModuleData()
|
||||
)));
|
||||
let state = { toolboxes: [], links: {}, moduleData: {} };
|
||||
const actions = useToolboxActions({
|
||||
store: {
|
||||
ready: true,
|
||||
persistToolboxSnapshot: async (updater) => {
|
||||
state = { ...state, ...updater(state) };
|
||||
return true;
|
||||
}
|
||||
},
|
||||
notify() {},
|
||||
setConfirmModal: (value) => assert.fail(value.message)
|
||||
});
|
||||
|
||||
assert.equal(await actions.importAllToolboxes({ text: async () => JSON.stringify(payload) }), true);
|
||||
const imported = state.toolboxes[0];
|
||||
const memos = imported.modules.find((module) => module.type === "memos");
|
||||
const planner = imported.modules.find((module) => module.type === "taskPlanner");
|
||||
assert.notEqual(imported.id, toolbox.id);
|
||||
assert.equal(state.links.game, imported.id);
|
||||
assert.equal(state.moduleData[`${imported.id}:${memos.id}`].plannerLink, planner.id);
|
||||
});
|
||||
|
||||
test("non-canonical values are rejected instead of being silently normalized", () => {
|
||||
const payload = validIndividualPayload();
|
||||
const counterId = payload.toolbox.modules.find((module) => module.type === "counters").id;
|
||||
payload.modules[counterId] = { counters: [{ id: "counter", label: "Score", value: "12" }] };
|
||||
assert.throws(
|
||||
() => validateToolboxImportPayload(payload),
|
||||
/ne respecte pas le format canonique du type « counters »/
|
||||
);
|
||||
});
|
||||
|
||||
test("invalid imports never reach the storage transaction", async () => {
|
||||
let writes = 0;
|
||||
let message = "";
|
||||
const actions = useToolboxActions({
|
||||
store: { ready: true, persistToolboxSnapshot: () => { writes += 1; return Promise.resolve(true); } },
|
||||
notify() {},
|
||||
setConfirmModal: (value) => { message = value.message; }
|
||||
});
|
||||
const payload = validIndividualPayload();
|
||||
payload.version = 999;
|
||||
assert.equal(await actions.importToolbox({ text: async () => JSON.stringify(payload) }), null);
|
||||
assert.equal(writes, 0);
|
||||
assert.match(message, /version 999/);
|
||||
});
|
||||
|
|
@ -1015,12 +1015,16 @@ test("toolbox modules preserve only active shell display options", () => {
|
|||
});
|
||||
|
||||
test("legacy toolbox order becomes a persistent default space", () => {
|
||||
const toolbox = normalizeToolbox({
|
||||
const legacy = {
|
||||
id: "legacy",
|
||||
modules: [{ id: "a", type: "notepad" }, { id: "b", type: "links" }],
|
||||
moduleOrder: { one: ["b", "a"], two: [["a"], ["b"]] }
|
||||
});
|
||||
};
|
||||
const toolbox = normalizeToolbox(legacy);
|
||||
assert.equal(toolbox.spaces.length, 1);
|
||||
assert.equal(toolbox.spaces[0].id, "default");
|
||||
assert.equal(normalizeToolbox(legacy).spaces[0].id, toolbox.spaces[0].id);
|
||||
assert.equal(normalizeToolbox(legacy).updatedAt, toolbox.updatedAt);
|
||||
assert.equal(toolbox.spaces[0].name, "Défaut");
|
||||
assert.equal(toolbox.defaultSpaceId, toolbox.spaces[0].id);
|
||||
assert.equal(toolbox.activeSpaceId, toolbox.spaces[0].id);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue