Audit the project and secure toolbox data

This commit is contained in:
Shinuwa 2026-10-14 16:59:09 +02:00
parent 96af62edf0
commit e87edda5c7
40 changed files with 2324 additions and 125 deletions

View file

@ -19,11 +19,12 @@ export function createPersistenceQueue(initialState, onChange) {
let failure;
try {
const next = operation.apply(confirmed);
await operation.persist(next);
confirmed = next;
const persisted = await operation.persist(next, confirmed);
confirmed = persisted ?? next;
success = true;
} catch (error) {
failure = error;
if (error?.confirmedState) confirmed = error.confirmedState;
}
pending.shift();
publish();

View file

@ -0,0 +1,67 @@
// Rôle : décrit les différences de stockage à appliquer atomiquement entre plusieurs onglets.
import { DEFERRED_MODULE_DATA } from "./deferredModuleData.js";
import { storageValuesEqual as valuesEqual } from "../../../utils/indexedDbStorage.js";
function keyedChanges(expected, next, { allowDeferredDelete = false } = {}) {
const changes = [];
const keys = new Set([...Object.keys(expected || {}), ...Object.keys(next || {})]);
for (const key of keys) {
const expectedExists = Object.hasOwn(expected || {}, key);
const nextExists = Object.hasOwn(next || {}, key);
const expectedValue = expected?.[key];
const nextValue = next?.[key];
if (expectedValue === DEFERRED_MODULE_DATA && nextValue === DEFERRED_MODULE_DATA) continue;
if (allowDeferredDelete && expectedValue === DEFERRED_MODULE_DATA && !nextExists) {
changes.push({ key, expected: "any", nextExists: false });
continue;
}
if (expectedValue === DEFERRED_MODULE_DATA || nextValue === DEFERRED_MODULE_DATA) continue;
if (expectedExists === nextExists && valuesEqual(expectedValue, nextValue)) continue;
changes.push({
key,
expected: expectedExists ? "value" : "missing",
expectedValue,
nextExists,
nextValue
});
}
return changes;
}
function toolboxChanges(expected, next) {
const expectedById = Object.fromEntries((expected || []).map((toolbox) => [toolbox.id, toolbox]));
const nextById = Object.fromEntries((next || []).map((toolbox) => [toolbox.id, toolbox]));
const changes = keyedChanges(expectedById, nextById);
const expectedIds = (expected || []).map((toolbox) => toolbox.id);
const nextIds = (next || []).map((toolbox) => toolbox.id);
const sharedIds = new Set(expectedIds.filter((id) => Object.hasOwn(nextById, id)));
const expectedSharedOrder = expectedIds.filter((id) => sharedIds.has(id));
const nextSharedOrder = nextIds.filter((id) => sharedIds.has(id));
const orderChanged = !valuesEqual(expectedSharedOrder, nextSharedOrder);
return {
changes,
expectedIds,
nextIds,
order: orderChanged ? { expectedIds, nextIds } : null
};
}
export function createStorageMutation(expected, next) {
const toolboxes = toolboxChanges(expected.toolboxes, next.toolboxes);
const links = keyedChanges(expected.links, next.links);
const modules = keyedChanges(expected.moduleData, next.moduleData, { allowDeferredDelete: true });
return {
toolboxes,
links,
modules,
changed: Boolean(toolboxes.changes.length || toolboxes.order || links.length || modules.length)
};
}
export function getStorageMutationNotice(mutation) {
return {
registry: Boolean(mutation.toolboxes.changes.length || mutation.toolboxes.order),
links: Boolean(mutation.links.length),
moduleKeys: mutation.modules.map((change) => change.key)
};
}

View file

@ -0,0 +1,300 @@
// Rôle : valide intégralement les exports JSON v2 avant toute préparation ou écriture locale.
import { TOOLBOX_MODULE_DEFINITIONS } from "../toolboxModuleRegistry.js";
import { compactModuleDataForStorage, MAX_TOOLBOX_SPACES } from "./toolboxStorage.js";
export const TOOLBOX_IMPORT_VERSION = 2;
function fail(message) {
throw new Error(`Import invalide : ${message}`);
}
function isRecord(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function assertRecord(value, path) {
if (!isRecord(value)) fail(`${path} doit être un objet.`);
}
function assertArray(value, path) {
if (!Array.isArray(value)) fail(`${path} doit être un tableau.`);
}
function assertString(value, path, { allowEmpty = false, allowColon = true } = {}) {
if (typeof value !== "string" || (!allowEmpty && !value.trim())) fail(`${path} doit être une chaîne non vide.`);
if (!allowColon && value.includes(":")) fail(`${path} ne peut pas contenir « : ».`);
}
function assertOptionalType(value, type, path) {
if (value !== undefined && typeof value !== type) fail(`${path} doit être de type ${type}.`);
}
function assertAllowedKeys(value, allowed, path) {
const unexpected = Object.keys(value).find((key) => !allowed.has(key));
if (unexpected) fail(`${path}.${unexpected} n'est pas reconnu dans le format v2.`);
}
function valuesEqual(left, right) {
if (Object.is(left, right)) return true;
if (!isRecord(left) && !Array.isArray(left)) return false;
if (!isRecord(right) && !Array.isArray(right)) return false;
if (Array.isArray(left) !== Array.isArray(right)) return false;
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
return leftKeys.length === rightKeys.length
&& leftKeys.every((key) => Object.hasOwn(right, key) && valuesEqual(left[key], right[key]));
}
function collectIds(items, path) {
assertArray(items, path);
const ids = new Set();
items.forEach((item, index) => {
assertRecord(item, `${path}[${index}]`);
assertString(item.id, `${path}[${index}].id`, { allowColon: false });
if (ids.has(item.id)) fail(`identifiant dupliqué « ${item.id} » dans ${path}.`);
ids.add(item.id);
});
return ids;
}
function optionalIds(items, path) {
return items === undefined ? new Set() : collectIds(items, path);
}
function assertReference(value, ids, path, { allowEmpty = true } = {}) {
if (value === undefined || (allowEmpty && value === "")) return;
assertString(value, path, { allowEmpty: false, allowColon: false });
if (!ids.has(value)) fail(`${path} référence l'identifiant absent « ${value} ».`);
}
function assertReferences(values, ids, path) {
if (values === undefined) return;
assertArray(values, path);
const seen = new Set();
values.forEach((value, index) => {
assertReference(value, ids, `${path}[${index}]`, { allowEmpty: false });
if (seen.has(value)) fail(`référence dupliquée « ${value} » dans ${path}.`);
seen.add(value);
});
}
function validateModuleReferences(type, data, path) {
if (type === "notepad") {
const pageIds = optionalIds(data.pages, `${path}.pages`);
assertReference(data.activePageId, pageIds, `${path}.activePageId`);
data.pages?.forEach((page, index) => optionalIds(page.drawings?.strokes, `${path}.pages[${index}].drawings.strokes`));
} else if (type === "memos") {
optionalIds(data.items, `${path}.items`);
} else if (type === "checklist") {
optionalIds(data.items, `${path}.items`);
const itemIds = new Set();
optionalIds(data.sections, `${path}.sections`);
data.sections?.forEach((section, sectionIndex) => {
const ids = optionalIds(section.items, `${path}.sections[${sectionIndex}].items`);
for (const id of ids) {
if (itemIds.has(id)) fail(`identifiant dupliqué « ${id} » dans les items de ${path}.sections.`);
itemIds.add(id);
}
});
} else if (type === "images") {
optionalIds(data.images, `${path}.images`);
} else if (type === "imageAnnotation") {
optionalIds(data.markers, `${path}.markers`);
optionalIds(data.drawings?.strokes, `${path}.drawings.strokes`);
} else if (type === "links") {
optionalIds(data.links, `${path}.links`);
} else if (type === "counters") {
optionalIds(data.counters, `${path}.counters`);
} else if (type === "combos") {
optionalIds(data.combos, `${path}.combos`);
} else if (type === "calculator") {
const ids = optionalIds(data.entries, `${path}.entries`);
data.entries?.forEach((entry, index) => assertReference(entry.parentId, ids, `${path}.entries[${index}].parentId`));
} else if (type === "randomizer") {
optionalIds(data.dice?.history, `${path}.dice.history`);
optionalIds(data.wheel?.entries, `${path}.wheel.entries`);
optionalIds(data.wheel?.history, `${path}.wheel.history`);
const playerIds = optionalIds(data.teams?.players, `${path}.teams.players`);
optionalIds(data.teams?.exclusions, `${path}.teams.exclusions`);
data.teams?.exclusions?.forEach((exclusion, index) => {
assertReference(exclusion.playerAId, playerIds, `${path}.teams.exclusions[${index}].playerAId`, { allowEmpty: false });
assertReferences(exclusion.playerBIds, playerIds, `${path}.teams.exclusions[${index}].playerBIds`);
});
optionalIds(data.teams?.teams, `${path}.teams.teams`);
data.teams?.teams?.forEach((team, index) => optionalIds(team.players, `${path}.teams.teams[${index}].players`));
optionalIds(data.teams?.history, `${path}.teams.history`);
} else if (type === "rngSimulator") {
const rateIds = optionalIds(data.rates, `${path}.rates`);
assertReference(data.activeRateId, rateIds, `${path}.activeRateId`);
} else if (type === "timer") {
optionalIds(data.stopwatch?.laps, `${path}.stopwatch.laps`);
optionalIds(data.countdowns, `${path}.countdowns`);
} else if (type === "calendar") {
optionalIds(data.events, `${path}.events`);
} else if (type === "taskPlanner") {
const taskIds = optionalIds(data.tasks, `${path}.tasks`);
optionalIds(data.relations, `${path}.relations`);
data.relations?.forEach((relation, index) => {
assertReference(relation.fromTaskId, taskIds, `${path}.relations[${index}].fromTaskId`, { allowEmpty: false });
assertReference(relation.toTaskId, taskIds, `${path}.relations[${index}].toTaskId`, { allowEmpty: false });
});
} else if (type === "goalTree") {
const nodeIds = optionalIds(data.nodes, `${path}.nodes`);
const itemIds = new Set();
data.nodes?.forEach((node, index) => {
assertReference(node.parentId, nodeIds, `${path}.nodes[${index}].parentId`);
assertReferences(node.parentIds, nodeIds, `${path}.nodes[${index}].parentIds`);
const ids = optionalIds(node.items, `${path}.nodes[${index}].items`);
for (const id of ids) {
if (itemIds.has(id)) fail(`identifiant dupliqué « ${id} » dans les items de ${path}.nodes.`);
itemIds.add(id);
}
});
} else if (type === "equipmentPlanner") {
const typeIds = optionalIds(data.types, `${path}.types`);
assertReferences(data.typeOrder, typeIds, `${path}.typeOrder`);
optionalIds(data.equipments, `${path}.equipments`);
data.equipments?.forEach((equipment, equipmentIndex) => {
assertReference(equipment.typeId, typeIds, `${path}.equipments[${equipmentIndex}].typeId`, { allowEmpty: false });
optionalIds(equipment.characteristics, `${path}.equipments[${equipmentIndex}].characteristics`);
optionalIds(equipment.materials, `${path}.equipments[${equipmentIndex}].materials`);
const socketIds = optionalIds(equipment.socketItems, `${path}.equipments[${equipmentIndex}].socketItems`);
equipment.socketItems?.forEach((socket, socketIndex) => optionalIds(socket.bonuses, `${path}.equipments[${equipmentIndex}].socketItems[${socketIndex}].bonuses`));
optionalIds(equipment.socketLinks, `${path}.equipments[${equipmentIndex}].socketLinks`);
equipment.socketLinks?.forEach((link, linkIndex) => {
assertReference(link.fromSocketItemId, socketIds, `${path}.equipments[${equipmentIndex}].socketLinks[${linkIndex}].fromSocketItemId`, { allowEmpty: false });
assertReference(link.toSocketItemId, socketIds, `${path}.equipments[${equipmentIndex}].socketLinks[${linkIndex}].toSocketItemId`, { allowEmpty: false });
});
});
}
}
function validateToolbox(toolbox, path) {
assertRecord(toolbox, path);
assertAllowedKeys(toolbox, new Set([
"id", "name", "icon", "customCover", "moduleColumns", "modules", "spaces",
"defaultSpaceId", "activeSpaceId", "tutorial", "updatedAt"
]), path);
assertString(toolbox.id, `${path}.id`, { allowColon: false });
assertString(toolbox.name, `${path}.name`);
assertOptionalType(toolbox.icon, "string", `${path}.icon`);
assertOptionalType(toolbox.customCover, "string", `${path}.customCover`);
assertOptionalType(toolbox.updatedAt, "string", `${path}.updatedAt`);
assertOptionalType(toolbox.tutorial, "boolean", `${path}.tutorial`);
if (toolbox.moduleColumns !== undefined && toolbox.moduleColumns !== 1 && toolbox.moduleColumns !== 2) {
fail(`${path}.moduleColumns doit valoir 1 ou 2.`);
}
const moduleIds = collectIds(toolbox.modules, `${path}.modules`);
const moduleById = new Map();
toolbox.modules.forEach((module, index) => {
assertAllowedKeys(module, new Set(["id", "type", "title", "scrollable", "collapsed"]), `${path}.modules[${index}]`);
assertString(module.type, `${path}.modules[${index}].type`);
if (!Object.hasOwn(TOOLBOX_MODULE_DEFINITIONS, module.type)) {
fail(`${path}.modules[${index}].type « ${module.type} » est inconnu.`);
}
assertOptionalType(module.title, "string", `${path}.modules[${index}].title`);
assertOptionalType(module.scrollable, "boolean", `${path}.modules[${index}].scrollable`);
assertOptionalType(module.collapsed, "boolean", `${path}.modules[${index}].collapsed`);
moduleById.set(module.id, module);
});
assertArray(toolbox.spaces, `${path}.spaces`);
if (!toolbox.spaces.length || toolbox.spaces.length > MAX_TOOLBOX_SPACES) {
fail(`${path}.spaces doit contenir entre 1 et ${MAX_TOOLBOX_SPACES} espaces.`);
}
const spaceIds = collectIds(toolbox.spaces, `${path}.spaces`);
const oneMemberships = [];
const twoMemberships = [];
toolbox.spaces.forEach((space, index) => {
const spacePath = `${path}.spaces[${index}]`;
assertAllowedKeys(space, new Set(["id", "name", "moduleOrder"]), spacePath);
assertString(space.name, `${spacePath}.name`);
assertRecord(space.moduleOrder, `${spacePath}.moduleOrder`);
assertAllowedKeys(space.moduleOrder, new Set(["one", "two"]), `${spacePath}.moduleOrder`);
assertArray(space.moduleOrder.one, `${spacePath}.moduleOrder.one`);
assertArray(space.moduleOrder.two, `${spacePath}.moduleOrder.two`);
if (space.moduleOrder.two.length !== 2) fail(`${spacePath}.moduleOrder.two doit contenir deux colonnes.`);
assertArray(space.moduleOrder.two[0], `${spacePath}.moduleOrder.two[0]`);
assertArray(space.moduleOrder.two[1], `${spacePath}.moduleOrder.two[1]`);
assertReferences(space.moduleOrder.one, moduleIds, `${spacePath}.moduleOrder.one`);
assertReferences(space.moduleOrder.two[0], moduleIds, `${spacePath}.moduleOrder.two[0]`);
assertReferences(space.moduleOrder.two[1], moduleIds, `${spacePath}.moduleOrder.two[1]`);
const one = new Set(space.moduleOrder.one);
const two = [...space.moduleOrder.two[0], ...space.moduleOrder.two[1]];
if (two.length !== one.size || two.some((id) => !one.has(id))) {
fail(`${spacePath}.moduleOrder.one et two ne contiennent pas les mêmes outils.`);
}
oneMemberships.push(...space.moduleOrder.one);
twoMemberships.push(...two);
});
for (const [label, memberships] of [["one", oneMemberships], ["two", twoMemberships]]) {
if (memberships.length !== moduleIds.size || new Set(memberships).size !== moduleIds.size) {
fail(`chaque outil de ${path}.modules doit apparaître exactement une fois dans les ordres ${label}.`);
}
}
assertReference(toolbox.defaultSpaceId, spaceIds, `${path}.defaultSpaceId`, { allowEmpty: false });
assertReference(toolbox.activeSpaceId, spaceIds, `${path}.activeSpaceId`, { allowEmpty: false });
if (toolbox.spaces[0].id !== toolbox.defaultSpaceId) fail(`${path}.defaultSpaceId doit désigner le premier espace.`);
return moduleById;
}
function validateModuleData(toolboxes, modules, global) {
assertRecord(modules, "modules");
const expected = new Map();
const toolboxModules = new Map();
toolboxes.forEach(({ toolbox, moduleById, path }) => {
toolboxModules.set(toolbox.id, moduleById);
for (const module of toolbox.modules) {
expected.set(global ? `${toolbox.id}:${module.id}` : module.id, { toolbox, module, path });
}
});
for (const [key, data] of Object.entries(modules)) {
const target = expected.get(key);
if (!target) fail(`modules.${key} ne correspond à aucun outil déclaré.`);
assertRecord(data, `modules.${key}`);
validateModuleReferences(target.module.type, data, `modules.${key}`);
if (target.module.type === "memos" && data.plannerLink && data.plannerLink !== "all") {
const planner = toolboxModules.get(target.toolbox.id).get(data.plannerLink);
if (!planner || planner.type !== "taskPlanner") {
fail(`modules.${key}.plannerLink référence un planificateur absent « ${data.plannerLink} ».`);
}
}
const compact = compactModuleDataForStorage(target.module.type, data);
if (!compact || !valuesEqual(compact, data)) {
fail(`modules.${key} ne respecte pas le format canonique du type « ${target.module.type} ».`);
}
}
}
export function validateToolboxImportPayload(payload, mode = "single") {
assertRecord(payload, "racine");
if (payload.version !== TOOLBOX_IMPORT_VERSION) {
fail(`version ${String(payload.version)} non prise en charge ; version attendue : ${TOOLBOX_IMPORT_VERSION}.`);
}
if (mode === "single") {
assertAllowedKeys(payload, new Set(["version", "toolbox", "modules"]), "racine");
const moduleById = validateToolbox(payload.toolbox, "toolbox");
validateModuleData([{ toolbox: payload.toolbox, moduleById, path: "toolbox" }], payload.modules, false);
return payload;
}
if (mode !== "global") fail(`mode de validation inconnu « ${mode} ».`);
assertAllowedKeys(payload, new Set(["version", "exportedAt", "toolboxes", "modules", "links"]), "racine");
assertString(payload.exportedAt, "exportedAt");
assertArray(payload.toolboxes, "toolboxes");
const toolboxIds = new Set();
const validated = payload.toolboxes.map((toolbox, index) => {
const path = `toolboxes[${index}]`;
const moduleById = validateToolbox(toolbox, path);
if (toolboxIds.has(toolbox.id)) fail(`identifiant dupliqué « ${toolbox.id} » dans toolboxes.`);
toolboxIds.add(toolbox.id);
return { toolbox, moduleById, path };
});
validateModuleData(validated, payload.modules, true);
assertRecord(payload.links, "links");
for (const [gameId, toolboxId] of Object.entries(payload.links)) {
assertString(gameId, "identifiant de jeu");
assertReference(toolboxId, toolboxIds, `links.${gameId}`, { allowEmpty: false });
}
return payload;
}

View file

@ -48,6 +48,7 @@ const TOOLBOX_ICON_FILES = [
export const TOOLBOX_ICONS = TOOLBOX_ICON_FILES.map((file) => `${TOOLBOX_ICON_BASE}${file}`);
export const DEFAULT_TOOLBOX_ICON = `${TOOLBOX_ICON_BASE}toolbox.png`;
export const MAX_TOOLBOX_SPACES = 5;
const LEGACY_TOOLBOX_UPDATED_AT = "1970-01-01T00:00:00.000Z";
export function normalizeToolboxIcon(icon) {
const value = String(icon || "").trim();
@ -137,7 +138,9 @@ export function normalizeToolboxSpaces(toolbox, modules) {
const moduleIds = modules.map((module) => module.id);
const rawSpaces = Array.isArray(toolbox?.spaces) ? toolbox.spaces.filter((space) => space && typeof space === "object") : [];
if (!rawSpaces.length) {
const id = uid("space");
// L'identifiant stable permet de comparer une ancienne toolbox avec sa version
// normalisée sans fabriquer un faux conflit entre deux lectures IndexedDB.
const id = "default";
return {
spaces: [{ id, name: "Défaut", moduleOrder: normalizeModuleOrder(toolbox?.moduleOrder, modules) }],
defaultSpaceId: id,
@ -200,7 +203,7 @@ export function normalizeToolbox(toolbox) {
moduleColumns: Number(toolbox.moduleColumns) === 1 ? 1 : 2,
modules,
...spaceState,
updatedAt: toolbox.updatedAt || new Date().toISOString()
updatedAt: toolbox.updatedAt || LEGACY_TOOLBOX_UPDATED_AT
};
if (toolbox.tutorial === true) normalized.tutorial = true;
return normalized;

View file

@ -1,19 +1,14 @@
// Rôle : synchronise l'état optimiste des toolboxes avec une file d'écritures IndexedDB.
import { useCallback, useEffect, useRef, useState } from "react";
import {
getAllModuleData as dbGetAllModuleData,
getModuleDataEntries as dbGetModuleDataEntries,
getLinks as dbGetLinks,
getSetting as dbGetSetting,
getStorageEstimate,
getToolboxSnapshot as dbGetToolboxSnapshot,
getToolboxes as dbGetToolboxes,
removeModuleData as dbRemoveModuleData,
removeModuleDataKeys as dbRemoveModuleDataKeys,
setLinks as dbSetLinks,
setModuleData as dbSetModuleData,
mutateToolboxStorage as dbMutateToolboxStorage,
setSetting as dbSetSetting,
setToolboxes as dbSetToolboxes,
setToolboxSnapshot as dbSetToolboxSnapshot
} from "../../../utils/indexedDbStorage.js";
import {
compactToolboxesForStorage,
@ -24,19 +19,62 @@ import {
import { applyModuleDataValue, removeModuleDataKeys } from "./optimisticModuleData.js";
import { createPersistenceQueue } from "./persistenceQueue.js";
import { createQuotaRefresh } from "./quotaRefresh.js";
import { DEFERRED_MODULE_DATA, getDeferredModuleKeys, mergeLoadedModuleData, splitModuleData } from "./deferredModuleData.js";
import { DEFERRED_MODULE_DATA, getDeferredModuleKeys, mergeLoadedModuleData } from "./deferredModuleData.js";
import { AUTO_BACKUP_DATA_CHANGED_EVENT } from "./autoBackup.js";
import { createStorageMutation, getStorageMutationNotice } from "./storageMutation.js";
const STORAGE_CHANNEL = "sokkog:toolbox-storage";
function normalizeToolboxes(toolboxes) {
return compactToolboxesForStorage(toolboxes).map(normalizeToolbox).filter(Boolean);
}
function normalizeToolboxesForStorage(toolboxes) {
return compactToolboxesForStorage(normalizeToolboxes(toolboxes));
}
async function readStoredState({ preservedModuleData = {}, refreshedModuleKeys = [] } = {}) {
const [toolboxes, links, toastPosition] = await Promise.all([
dbGetToolboxes(), dbGetLinks(), dbGetSetting("toastPosition", "right")
]);
const normalizedToolboxes = (Array.isArray(toolboxes) ? toolboxes : []).map(normalizeToolbox).filter(Boolean);
const registeredKeys = new Set(normalizedToolboxes.flatMap((toolbox) => (toolbox.modules || [])
.map((module) => `${toolbox.id}:${module.id}`)));
const deferredKeys = getDeferredModuleKeys(normalizedToolboxes);
const refreshed = new Set(refreshedModuleKeys);
const excludedKeys = [...registeredKeys].filter((key) => {
if (refreshed.has(key)) return false;
if (preservedModuleData[key] !== undefined && preservedModuleData[key] !== DEFERRED_MODULE_DATA) return true;
return deferredKeys.includes(key);
});
const excluded = new Set(excludedKeys);
const modules = await dbGetModuleDataEntries([...registeredKeys].filter((key) => !excluded.has(key)));
const moduleData = Object.fromEntries([
...deferredKeys.map((key) => [key, DEFERRED_MODULE_DATA]),
...(modules || []).map((entry) => [entry.key, entry.data])
]);
for (const key of excludedKeys) {
const preserved = preservedModuleData[key];
if (preserved !== undefined && preserved !== DEFERRED_MODULE_DATA) moduleData[key] = preserved;
}
for (const key of refreshed) {
if (deferredKeys.includes(key) && !(modules || []).some((entry) => entry.key === key)) delete moduleData[key];
}
return {
toolboxes: normalizedToolboxes,
links: links && typeof links === "object" ? links : {},
moduleData,
toastPosition: toastPosition === "left" ? "left" : "right"
};
}
export function useIndexedToolboxes(onError) {
const [ready, setReady] = useState(false);
const [loadError, setLoadError] = useState("");
const [loadAttempt, setLoadAttempt] = useState(0);
const writableRef = useRef(false);
const pendingReadsRef = useRef(new Map());
const storageChannelRef = useRef(null);
const [state, setState] = useState({ toolboxes: [], links: {}, moduleData: {}, toastPosition: "right" });
const [queue] = useState(() => createPersistenceQueue(state, setState));
const [storageUsage, setStorageUsage] = useState({ used: 0, limit: 0, ratio: 0 });
@ -68,22 +106,9 @@ export function useIndexedToolboxes(onError) {
let cancelled = false;
async function loadStore() {
try {
const [toolboxes, links, toastPosition] = await Promise.all([
dbGetToolboxes(), dbGetLinks(), dbGetSetting("toastPosition", "right")
]);
const normalizedToolboxes = (Array.isArray(toolboxes) ? toolboxes : []).map(normalizeToolbox).filter(Boolean);
const deferredKeys = getDeferredModuleKeys(normalizedToolboxes);
const modules = await dbGetAllModuleData(deferredKeys);
const storedState = await readStoredState();
if (cancelled) return;
queue.initialize({
toolboxes: normalizedToolboxes,
links: links && typeof links === "object" ? links : {},
moduleData: Object.fromEntries([
...deferredKeys.map((key) => [key, DEFERRED_MODULE_DATA]),
...(modules || []).map((entry) => [entry.key, entry.data])
]),
toastPosition: toastPosition === "left" ? "left" : "right"
});
queue.initialize(storedState);
writableRef.current = true;
setReady(true);
refreshQuota();
@ -97,6 +122,26 @@ export function useIndexedToolboxes(onError) {
return () => { cancelled = true; writableRef.current = false; };
}, [queue, refreshQuota, loadAttempt]);
useEffect(() => {
if (!ready || typeof BroadcastChannel === "undefined") return undefined;
const channel = new BroadcastChannel(STORAGE_CHANNEL);
storageChannelRef.current = channel;
channel.onmessage = (event) => {
if (!writableRef.current || !event.data || event.data.type !== "changed") return;
const current = queue.getCurrent();
const refreshedModuleKeys = (event.data.moduleKeys || []).filter((key) => current.moduleData[key] !== DEFERRED_MODULE_DATA);
void queue.enqueue(
(confirmed) => confirmed,
(next) => readStoredState({ preservedModuleData: next.moduleData, refreshedModuleKeys }),
reportStorageError
);
};
return () => {
channel.close();
if (storageChannelRef.current === channel) storageChannelRef.current = null;
};
}, [queue, ready, reportStorageError]);
function retryLoad() {
if (ready || !loadError) return;
setLoadError("");
@ -116,12 +161,44 @@ export function useIndexedToolboxes(onError) {
return result;
}
async function persistMutation(next, confirmed) {
const expectedStorage = {
toolboxes: compactToolboxesForStorage(confirmed.toolboxes),
links: confirmed.links,
moduleData: confirmed.moduleData
};
const nextStorage = {
toolboxes: compactToolboxesForStorage(next.toolboxes),
links: next.links,
moduleData: next.moduleData
};
const mutation = createStorageMutation(expectedStorage, nextStorage);
if (!mutation.changed) return next;
const notice = getStorageMutationNotice(mutation);
try {
await dbMutateToolboxStorage(mutation, { normalizeToolboxes: normalizeToolboxesForStorage });
} catch (error) {
if (error?.name === "StorageConflictError") {
error.confirmedState = await readStoredState({
preservedModuleData: confirmed.moduleData,
refreshedModuleKeys: notice.moduleKeys
});
}
throw error;
}
const persisted = await readStoredState({
preservedModuleData: next.moduleData
});
storageChannelRef.current?.postMessage({ type: "changed", ...notice });
return persisted;
}
function persistToolboxes(value) {
if (!writableRef.current) return false;
const apply = typeof value === "function" ? value : () => value;
enqueue(
(current) => ({ ...current, toolboxes: normalizeToolboxes(apply(current.toolboxes)) }),
(next) => dbSetToolboxes(compactToolboxesForStorage(next.toolboxes))
persistMutation
);
return true;
}
@ -130,7 +207,7 @@ export function useIndexedToolboxes(onError) {
if (!writableRef.current) return false;
enqueue(
(current) => ({ ...current, links: typeof value === "function" ? value(current.links) : value }),
(next) => dbSetLinks(next.links)
persistMutation
);
return true;
}
@ -147,10 +224,7 @@ export function useIndexedToolboxes(onError) {
const hasModule = (current) => current.toolboxes.some((toolbox) => toolbox.id === toolboxId && toolbox.modules.some((module) => module.id === moduleId));
enqueue(
(current) => hasModule(current) ? { ...current, moduleData: applyModuleDataValue(current.moduleData, key, compact) } : current,
(next) => {
if (!hasModule(next)) return;
return compact == null ? dbRemoveModuleData(key) : dbSetModuleData(key, compact);
}
persistMutation
);
return true;
}
@ -159,7 +233,7 @@ export function useIndexedToolboxes(onError) {
const key = moduleStorageKey(toolboxId, moduleId);
return enqueue(
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, [key]) }),
() => dbRemoveModuleData(key)
persistMutation
);
}
@ -169,7 +243,7 @@ export function useIndexedToolboxes(onError) {
if (!keys.length) return Promise.resolve(true);
return enqueue(
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, keys) }),
() => dbRemoveModuleDataKeys(keys)
persistMutation
);
}
@ -177,10 +251,7 @@ export function useIndexedToolboxes(onError) {
return enqueue((current) => {
const next = updater(current);
return { ...current, ...next, toolboxes: normalizeToolboxes(next.toolboxes) };
}, (next) => {
const { stored, deferred } = splitModuleData(next.moduleData);
return dbSetToolboxSnapshot(compactToolboxesForStorage(next.toolboxes), next.links, stored, deferred);
});
}, persistMutation);
}
const ensureModuleData = useCallback((toolboxId, moduleId) => {
@ -202,11 +273,15 @@ export function useIndexedToolboxes(onError) {
async function getExportSnapshot(toolboxId, options = {}) {
if (!writableRef.current) return null;
let snapshot;
const success = await queue.enqueue((current) => current, async (current) => {
const { deferred } = splitModuleData(current.moduleData);
const keys = deferred.filter((key) => !toolboxId || key.startsWith(`${toolboxId}:`));
const entries = await dbGetModuleDataEntries(keys);
snapshot = { ...current, moduleData: mergeLoadedModuleData(current.moduleData, keys, entries) };
const success = await queue.enqueue((current) => current, async () => {
const stored = await dbGetToolboxSnapshot(toolboxId);
const toolboxes = (stored.toolboxes || []).map(normalizeToolbox).filter(Boolean);
snapshot = {
toolboxes,
links: stored.links,
moduleData: stored.moduleData,
toastPosition: queue.getCurrent().toastPosition
};
}, options.onError || reportStorageError);
return success ? snapshot : null;
}

View file

@ -5,12 +5,12 @@ import {
createToolboxExportPayload,
globalModuleKey,
labelFromFileName,
MAX_TOOLBOX_SPACES,
normalizeToolbox,
remapMemosPlannerLink,
remapModuleOrderIds,
uid
} from "./storage/toolboxStorage.js";
import { validateToolboxImportPayload } from "./storage/toolboxImportValidation.js";
import { compressImage } from "../../utils/imageCompression.js";
import { getBackupFileName } from "./storage/autoBackup.js";
import { addModuleToToolboxSpace } from "./toolboxSpaceUtils.js";
@ -182,11 +182,7 @@ export function useToolboxActions({ store, notify, creationTemplate, setConfirmM
}
async function importToolboxPayload(file, gameId = "") {
const payload = JSON.parse(await file.text());
if (!payload.toolbox?.modules) throw new Error("Format d'outils invalide");
if (Array.isArray(payload.toolbox.spaces) && payload.toolbox.spaces.length > MAX_TOOLBOX_SPACES) {
throw new Error(`Une toolbox ne peut pas contenir plus de ${MAX_TOOLBOX_SPACES} espaces.`);
}
const payload = validateToolboxImportPayload(JSON.parse(await file.text()), "single");
const imported = normalizeToolbox({ ...payload.toolbox, id: uid("tbx"), updatedAt: new Date().toISOString() });
const moduleIdMap = new Map();
imported.modules = imported.modules.map((module) => {
@ -223,13 +219,7 @@ export function useToolboxActions({ store, notify, creationTemplate, setConfirmM
}
async function importAllToolboxesPayload(file) {
const payload = JSON.parse(await file.text());
if (!Array.isArray(payload.toolboxes) || !payload.modules || typeof payload.modules !== "object") {
throw new Error("Format d'import global invalide");
}
if (payload.toolboxes.some((toolbox) => Array.isArray(toolbox.spaces) && toolbox.spaces.length > MAX_TOOLBOX_SPACES)) {
throw new Error(`Une toolbox ne peut pas contenir plus de ${MAX_TOOLBOX_SPACES} espaces.`);
}
const payload = validateToolboxImportPayload(JSON.parse(await file.text()), "global");
const toolboxIdMap = new Map();
const moduleIdMap = new Map();
const importedToolboxes = payload.toolboxes.map((toolbox) => {

View file

@ -6,6 +6,14 @@ const MODULE_STORE = "modules";
let dbPromise;
export class StorageConflictError extends Error {
constructor(conflicts) {
super("Ces données ont été modifiées dans un autre onglet. La version enregistrée a été rechargée.");
this.name = "StorageConflictError";
this.conflicts = conflicts;
}
}
function openDatabase() {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => {
@ -161,6 +169,174 @@ export async function setToolboxSnapshot(toolboxes, links, moduleData, preserved
});
}
function changeMatches(change, exists, value) {
if (change.expected === "any") return true;
if (change.expected === "missing") return !exists;
return exists && storageValuesEqual(value, change.expectedValue);
}
export function storageValuesEqual(left, right) {
if (Object.is(left, right)) return true;
if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
if (Array.isArray(left) !== Array.isArray(right)) return false;
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) return false;
return leftKeys.every((key) => Object.hasOwn(right, key) && storageValuesEqual(left[key], right[key]));
}
function applyRecordChanges(current, changes, resource, conflicts) {
const next = { ...(current || {}) };
for (const change of changes) {
const exists = Object.hasOwn(current || {}, change.key);
if (!changeMatches(change, exists, current?.[change.key])) {
conflicts.push(`${resource}:${change.key}`);
continue;
}
if (change.nextExists) next[change.key] = change.nextValue;
else delete next[change.key];
}
return next;
}
function applyToolboxChanges(current, mutation, conflicts) {
const currentById = Object.fromEntries(current.map((toolbox) => [toolbox.id, toolbox]));
const changedById = new Map(mutation.changes.map((change) => [change.key, change]));
for (const change of mutation.changes) {
const exists = Object.hasOwn(currentById, change.key);
if (!changeMatches(change, exists, currentById[change.key])) conflicts.push(`toolbox:${change.key}`);
}
if (mutation.order) {
const expected = new Set(mutation.order.expectedIds);
const actualKnownOrder = current.map((toolbox) => toolbox.id).filter((id) => expected.has(id));
if (!storageValuesEqual(actualKnownOrder, mutation.order.expectedIds)) conflicts.push("toolboxes:order");
}
if (conflicts.length) return current;
const retained = current.flatMap((toolbox) => {
const change = changedById.get(toolbox.id);
if (!change) return [toolbox];
return change.nextExists ? [change.nextValue] : [];
});
const retainedIds = new Set(retained.map((toolbox) => toolbox.id));
const additions = mutation.nextIds
.filter((id) => !retainedIds.has(id) && changedById.get(id)?.nextExists)
.map((id) => changedById.get(id).nextValue);
const combined = [...additions, ...retained];
if (!mutation.order) return combined;
const expectedIds = new Set(mutation.expectedIds);
const remote = combined.filter((toolbox) => !expectedIds.has(toolbox.id) && !changedById.has(toolbox.id));
const combinedById = new Map(combined.map((toolbox) => [toolbox.id, toolbox]));
const ordered = mutation.nextIds.map((id) => combinedById.get(id)).filter(Boolean);
return [...remote, ...ordered];
}
export async function mutateToolboxStorage(mutation, { normalizeToolboxes = (value) => value } = {}) {
if (!mutation?.changed) return;
const db = await openDatabase();
await new Promise((resolve, reject) => {
const transaction = db.transaction([KV_STORE, MODULE_STORE], "readwrite");
const kv = transaction.objectStore(KV_STORE);
const modules = transaction.objectStore(MODULE_STORE);
const toolboxRequest = kv.get("toolboxes");
const linksRequest = kv.get("links");
const moduleRequests = new Map(mutation.modules.flatMap((change) => {
if (change.expected === "any") return [];
return [[change.key, {
kind: change.expected === "missing" ? "count" : "value",
request: change.expected === "missing" ? modules.count(change.key) : modules.get(change.key)
}]];
}));
let remaining = 2 + moduleRequests.size;
let failure;
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(failure || transaction.error);
transaction.onabort = () => reject(failure || transaction.error);
function applyWhenReady() {
remaining -= 1;
if (remaining) return;
try {
const currentToolboxes = normalizeToolboxes(Array.isArray(toolboxRequest.result) ? toolboxRequest.result : []);
const currentLinks = linksRequest.result && typeof linksRequest.result === "object" ? linksRequest.result : {};
const currentModules = {};
for (const [key, entry] of moduleRequests) {
if (entry.kind === "count" && entry.request.result > 0) currentModules[key] = true;
if (entry.kind === "value" && entry.request.result) currentModules[key] = entry.request.result.data;
}
const conflicts = [];
const nextToolboxes = applyToolboxChanges(currentToolboxes, mutation.toolboxes, conflicts);
const nextLinks = applyRecordChanges(currentLinks, mutation.links, "link", conflicts);
applyRecordChanges(currentModules, mutation.modules, "module", conflicts);
const validModuleKeys = new Set(nextToolboxes.flatMap((toolbox) => (toolbox.modules || [])
.map((module) => `${toolbox.id}:${module.id}`)));
for (const change of mutation.modules) {
if (change.nextExists && change.key.includes(":") && !validModuleKeys.has(change.key)) {
conflicts.push(`module-target:${change.key}`);
}
}
const validToolboxIds = new Set(nextToolboxes.map((toolbox) => toolbox.id));
for (const change of mutation.links) {
if (change.nextExists && change.nextValue && !validToolboxIds.has(change.nextValue)) {
conflicts.push(`link-target:${change.key}`);
}
}
if (conflicts.length) {
failure = new StorageConflictError([...new Set(conflicts)]);
transaction.abort();
return;
}
if (mutation.toolboxes.changes.length || mutation.toolboxes.order) kv.put(nextToolboxes, "toolboxes");
if (mutation.links.length) kv.put(nextLinks, "links");
for (const change of mutation.modules) {
if (change.nextExists) modules.put({ key: change.key, data: change.nextValue });
else modules.delete(change.key);
}
} catch (error) {
failure = error;
transaction.abort();
}
}
toolboxRequest.onsuccess = applyWhenReady;
linksRequest.onsuccess = applyWhenReady;
for (const { request } of moduleRequests.values()) request.onsuccess = applyWhenReady;
});
}
export async function getToolboxSnapshot(toolboxId = "") {
const db = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = db.transaction([KV_STORE, MODULE_STORE], "readonly");
const kv = transaction.objectStore(KV_STORE);
const modules = transaction.objectStore(MODULE_STORE);
const toolboxes = kv.get("toolboxes");
const links = kv.get("links");
const moduleEntries = [];
toolboxes.onsuccess = () => {
const storedToolboxes = Array.isArray(toolboxes.result) ? toolboxes.result : [];
const selected = toolboxId ? storedToolboxes.filter((item) => item?.id === toolboxId) : storedToolboxes;
for (const toolbox of selected) {
for (const module of toolbox?.modules || []) {
const request = modules.get(`${toolbox.id}:${module.id}`);
request.onsuccess = () => { if (request.result) moduleEntries.push(request.result); };
}
}
};
transaction.oncomplete = () => resolve({
toolboxes: Array.isArray(toolboxes.result) ? toolboxes.result : [],
links: links.result && typeof links.result === "object" ? links.result : {},
moduleData: Object.fromEntries(moduleEntries.map((entry) => [entry.key, entry.data]))
});
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
}
export async function getStorageEstimate() {
if (!navigator.storage?.estimate) return { usage: 0, quota: 0 };
return navigator.storage.estimate();