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

@ -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();