Send a toolbox through an encrypted link
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 20m39s
Validate and deploy Sokko G / deploy (push) Successful in 12s

Sharing a toolbox meant exporting a JSON file and passing it around by
hand. A toolbox can now be sent from the site while staying local first:
the browser compresses and encrypts the v2 export with AES-GCM, and the
key lives only in the link fragment, so the server keeps for at most
24 hours a copy it cannot read.

- Add the /api/shares service: upload, metadata, download and revoke,
  with files in SHARES_DIR, a purge every 10 minutes, and single-use
  links (the default) deleted only once fully downloaded.
- Cap the server load: 50 MiB per share, total storage, free disk
  space, daily volume, concurrent and stalled uploads, reads per link,
  plus a wide per-connection cap kept in memory without storing IPs.
- Limit each browser to 2 shares and 100 MiB per day and 2 active
  links, and show the existing link of a toolbox already shared.
- Add the send dialog (card and game drawer) and the /receive page,
  which previews or directly imports through the existing import path.
- Move shared HTTP helpers to services/http.js for both APIs.
- Document the format, delivery, server layout and privacy wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-11 16:26:05 +01:00
parent 957bfdc86f
commit bec9ea5b2f
43 changed files with 2349 additions and 59 deletions

View file

@ -3,6 +3,7 @@ import { Icon } from "./Icon.jsx";
import { ImageViewer } from "./ImageViewer.jsx";
import { AutoBackupModal, ConfirmModal, CreateToolboxModal, LinkToolboxModal, NotificationToast } from "./ToolboxModals.jsx";
import { navigate } from "../router/hashRouter.js";
import { ShareToolboxModal } from "../features/toolboxes/sharing/ShareToolboxModal.jsx";
import { uid } from "../features/toolboxes/storage/toolboxStorage.js";
function scrollToTopAfterNavigation() {
@ -30,6 +31,9 @@ export function AppOverlays({
setCreateModal,
linkModalGameId,
setLinkModalGameId,
shareToolboxId,
setShareToolboxId,
shareContent,
setDrawerGameId,
storageError,
storageErrorTitle,
@ -74,6 +78,13 @@ export function AppOverlays({
actions.linkToolboxToGame(gameId, toolboxId);
setDrawerGameId(gameId);
}} />}
{shareToolboxId && shareContent && toolboxes.some((toolbox) => toolbox.id === shareToolboxId) && <ShareToolboxModal
key={shareToolboxId}
toolbox={toolboxes.find((toolbox) => toolbox.id === shareToolboxId)}
content={shareContent}
actions={actions}
onClose={() => setShareToolboxId("")}
/>}
{autoBackupModalOpen && <AutoBackupModal backup={autoBackup} content={autoBackupContent} onExport={actions.exportAllToolboxes} onClose={() => setAutoBackupModalOpen(false)} />}
{storageError && <ConfirmModal title={storageErrorTitle} message={storageError} confirmLabel="Compris" cancelLabel="Fermer" danger onClose={() => setStorageError("")} />}
{image && <ImageViewer image={image} onClose={() => setImage(null)} createMarkerId={() => uid("marker")} />}

View file

@ -8,7 +8,7 @@ import { Tooltip } from "./Tooltip.jsx";
export function Shell({ route, content, games, drawerGameId = "", drawerVisible = false, compactGameLayout = false, reducedSidebar = false, cardsEnabled = false, actions, onOpenAutoBackup, children }) {
const gameId = route.split("/")[1] === "games" ? route.split("/")[2] || "" : "";
const game = games.find((item) => item.id === gameId);
const topbarLabel = route === "/design-system" && import.meta.env.DEV ? "Design system" : route.startsWith("/toolbox") ? content.topbar.toolbox : route.startsWith("/games") ? content.topbar.games : route === "/library" ? content.topbar.library : route.startsWith("/cards") ? content.topbar.cards : content.topbar.dashboard;
const topbarLabel = route === "/design-system" && import.meta.env.DEV ? "Design system" : route.startsWith("/toolbox") || route.startsWith("/receive/") ? content.topbar.toolbox : route.startsWith("/games") ? content.topbar.games : route === "/library" ? content.topbar.library : route.startsWith("/cards") ? content.topbar.cards : content.topbar.dashboard;
const toolboxOpen = Boolean(game && drawerGameId === game.id && drawerVisible);
const toolboxLabel = toolboxOpen ? "Masquer la toolbox" : "Afficher la toolbox";
const compactSidebar = Boolean(reducedSidebar || (!compactGameLayout && toolboxOpen));

View file

@ -65,6 +65,7 @@ export function ToolboxCard({ toolbox, game, actions, reorder }) {
<div className="card-actions nds-card-actions nds-toolbar">
<a className="card-icon-button nds-icon-button" data-size="md" href={`#/toolbox/${toolbox.id}`} aria-label={`Ouvrir ${toolbox.name}`} title="Ouvrir"><Icon name="open" /></a>
<button className="card-icon-button nds-icon-button" data-size="md" onClick={() => actions.exportToolbox(toolbox.id)} aria-label={`Exporter ${toolbox.name}`} title="Exporter"><Icon name="export" /></button>
{actions.sharingEnabled && <button className="card-icon-button nds-icon-button" data-size="md" onClick={() => actions.openShareToolbox(toolbox.id)} aria-label={`Envoyer ${toolbox.name}`} title="Envoyer"><Icon name="send" /></button>}
<button className="card-icon-button nds-icon-button" data-size="md" data-variant="danger" onClick={() => actions.setConfirmModal({
title: "Supprimer la toolbox",
message: `Supprimer "${toolbox.name}" et ses données locales ?`,

View file

@ -484,6 +484,7 @@ export function ToolboxDrawer({ gameId, game, siteContent, toolboxes, links, act
<button className="drawer-action-button nds-icon-button" data-size="sm" onClick={() => actions.setLinkModalGameId(gameId)} aria-label="Lier une toolbox" title="Lier"><Icon name="link" /></button>
<ImportButton className="drawer-action-button nds-icon-button import-icon-button" data-size="sm" ariaLabel="Importer une toolbox" title="Importer" icon="import" onFile={(file) => actions.importToolbox(file, gameId)} />
<button className="drawer-action-button nds-icon-button" data-size="sm" onClick={() => actions.exportToolbox(selectedId)} disabled={!selectedId} aria-label="Exporter la toolbox liée" title="Exporter"><Icon name="export" /></button>
{actions.sharingEnabled && <button className="drawer-action-button nds-icon-button" data-size="sm" onClick={() => actions.openShareToolbox(selectedId)} disabled={!selectedId} aria-label="Envoyer la toolbox liée" title="Envoyer"><Icon name="send" /></button>}
</div>
</div>
<button className="drawer-close-button nds-icon-button" data-size="sm" onClick={() => actions.setDrawerGameId("")} aria-label="Fermer" title="Fermer"><Icon name="close" /></button>

View file

@ -0,0 +1,143 @@
// Rôle : reçoit une toolbox envoyée par lien, la déchiffre dans ce navigateur et l'importe comme une copie locale.
import { useEffect, useState } from "react";
import { Icon } from "../../../components/Icon.jsx";
import { navigate } from "../../../router/hashRouter.js";
import { getDefaultModuleTitle } from "../toolboxModuleRegistry.js";
import { validateToolboxImportPayload } from "../storage/toolboxImportValidation.js";
import { DEFAULT_TOOLBOX_ICON, normalizeToolboxIcon } from "../storage/toolboxStorage.js";
import { decryptSharePayload, isShareKey } from "./shareCrypto.js";
import { fillTemplate, formatShareDate } from "./shareFormat.js";
import { downloadShare, loadShareMeta } from "./sharesApi.js";
// La clé suit le second « # » : elle ne quitte jamais le navigateur, même dans l'adresse de la page.
function readShareKey() {
return location.hash.split("#")[2] || "";
}
function errorMessage(content, error) {
if (error?.code === "SHARE_NOT_FOUND") return content.notFound;
if (error?.code === "SHARE_KEY_INVALID") return error.message;
if (error?.code === "SHARES_DISABLED") return content.disabled;
return error?.message || content.failed;
}
async function receivePayload(shareId, key, setProgress) {
const bytes = await downloadShare(shareId, { onProgress: (progress) => setProgress({ stage: "downloading", progress }) });
setProgress({ stage: "decrypting" });
const payload = await decryptSharePayload(bytes, key);
return validateToolboxImportPayload(payload, "single");
}
function ToolboxPreview({ payload, content }) {
const toolbox = payload.toolbox;
const counts = new Map();
toolbox.modules.forEach((module) => counts.set(module.type, (counts.get(module.type) || 0) + 1));
return (
<>
<div className="toolbox-receive-summary">
<img src={toolbox.customCover || normalizeToolboxIcon(toolbox.icon) || DEFAULT_TOOLBOX_ICON} alt="" />
<div>
<h2>{toolbox.name}</h2>
<p className="toolbox-receive-text">{fillTemplate(content.spaces, { count: toolbox.spaces?.length || 1, tools: toolbox.modules.length })}</p>
</div>
</div>
{counts.size > 0 && (
<ul className="toolbox-receive-tools">
{[...counts].map(([type, count]) => <li key={type} className="nds-badge" data-variant="neutral">{getDefaultModuleTitle(type)}{count > 1 ? ` × ${count}` : ""}</li>)}
</ul>
)}
</>
);
}
function ReceiveFlow({ shareId, shareKey, content, actions, onRetry }) {
const [state, setState] = useState({ phase: "checking", meta: null, payload: null, error: "" });
const [progress, setProgress] = useState(null);
useEffect(() => {
let active = true;
loadShareMeta(shareId)
.then(async (meta) => {
if (!active) return;
// Un lien à usage unique n'est téléchargé qu'à la demande : l'ouvrir le consomme.
if (meta.singleUse) {
setState({ phase: "confirm", meta, payload: null, error: "" });
return;
}
setState({ phase: "receiving", meta, payload: null, error: "" });
const payload = await receivePayload(shareId, shareKey, (value) => { if (active) setProgress(value); });
if (active) setState({ phase: "preview", meta, payload, error: "" });
})
.catch((error) => { if (active) setState({ phase: "error", meta: null, payload: null, error: errorMessage(content, error) }); })
.finally(() => { if (active) setProgress(null); });
return () => { active = false; };
}, [content, shareId, shareKey]);
async function importPayload(payload) {
setProgress({ stage: "importing" });
const toolbox = await actions.importReceivedToolbox(payload);
navigate(`/toolbox/${toolbox.id}`);
}
async function run(task) {
try {
await task();
} catch (error) {
setState((current) => ({ ...current, phase: "error", error: errorMessage(content, error) }));
} finally {
setProgress(null);
}
}
const busy = Boolean(progress);
const status = progress?.stage === "downloading"
? fillTemplate(content.downloading, { percent: Math.round((progress.progress || 0) * 100) })
: progress?.stage === "decrypting" ? content.decrypting
: progress?.stage === "importing" ? content.importing
: state.phase === "checking" ? content.checking : "";
return (
<>
{state.phase !== "preview" && <h1>{content.title}</h1>}
{state.phase === "preview" && <ToolboxPreview payload={state.payload} content={content} />}
{state.meta && state.phase !== "error" && <p className="toolbox-receive-text">{fillTemplate(content.expires, { date: formatShareDate(state.meta.expiresAt) })}</p>}
{status && <p className="toolbox-receive-text" role="status" aria-live="polite">{status}</p>}
{state.phase === "confirm" && <p className="nds-inline-notice" data-variant="warning" role="status">{content.singleUseNotice}</p>}
{(state.phase === "preview" || state.phase === "confirm") && <p className="toolbox-receive-text">{content.localNote}</p>}
{state.phase === "error" && <p className="nds-inline-notice" data-variant="danger" role="alert">{state.error}</p>}
<div className="nds-toolbar toolbox-receive-actions">
{state.phase === "preview" && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={() => void run(() => importPayload(state.payload))}><Icon name="import" />{content.import}</button>}
{state.phase === "confirm" && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={() => void run(async () => importPayload(await receivePayload(shareId, shareKey, setProgress)))}><Icon name="import" />{content.receiveAndImport}</button>}
{state.phase === "error" && <button className="nds-button" data-size="sm" type="button" onClick={onRetry}><Icon name="refresh" />{content.retry}</button>}
<a className="nds-button" data-size="sm" href="#/toolboxes">{content.back}</a>
</div>
</>
);
}
export function ReceiveToolboxPage({ shareId, siteContent, actions }) {
const content = siteContent.toolboxShare.receive;
const [shareKey, setShareKey] = useState(readShareKey);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
const onHashChange = () => setShareKey(readShareKey());
window.addEventListener("hashchange", onHashChange);
return () => window.removeEventListener("hashchange", onHashChange);
}, []);
return (
<section className="toolbox-receive">
<article className="card nds-card toolbox-receive-card">
<p className="eyebrow">{content.eyebrow}</p>
{isShareKey(shareKey)
? <ReceiveFlow key={`${shareId}:${shareKey}:${attempt}`} shareId={shareId} shareKey={shareKey} content={content} actions={actions} onRetry={() => setAttempt((value) => value + 1)} />
: <>
<h1>{content.title}</h1>
<p className="nds-inline-notice" data-variant="danger" role="alert">{content.keyMissing}</p>
<div className="nds-toolbar toolbox-receive-actions"><a className="nds-button" data-size="sm" href="#/toolboxes">{content.back}</a></div>
</>}
</article>
</section>
);
}

View file

@ -0,0 +1,161 @@
// Rôle : crée, affiche et révoque le lien d'envoi chiffré d'une toolbox, dans les limites de ce navigateur.
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { Icon } from "../../../components/Icon.jsx";
import { Modal } from "../../../components/Modal.jsx";
import { createShareQuota, SHARE_QUOTA } from "./shareQuota.js";
import { fillTemplate, formatMiB, formatShareDate } from "./shareFormat.js";
import { createToolboxShare, refreshActiveShares, revokeToolboxShare, ShareLimitError } from "./toolboxSharing.js";
function limitMessage(content, limit) {
if (limit.reason === "active") return fillTemplate(content.limitActive, { max: SHARE_QUOTA.maxActive });
if (limit.reason === "daily-count") return fillTemplate(content.limitDailyCount, { max: SHARE_QUOTA.maxPerDay, date: formatShareDate(limit.retryAt) });
if (limit.reason === "daily-bytes") return fillTemplate(content.limitDailyBytes, { max: formatMiB(SHARE_QUOTA.maxBytesPerDay), date: limit.retryAt ? formatShareDate(limit.retryAt) : "—" });
if (limit.reason === "too-large") return fillTemplate(content.tooLarge, { size: formatMiB(limit.size), max: formatMiB(limit.maxBytes) });
return "";
}
function ShareLink({ share, content, onRevoke, busy }) {
const inputRef = useRef(null);
const [copied, setCopied] = useState(false);
async function copy() {
try {
await navigator.clipboard.writeText(share.link);
setCopied(true);
} catch {
inputRef.current?.select();
}
}
return (
<section className="toolbox-share-link">
<label className="field">
<span>{content.linkLabel}</span>
<input ref={inputRef} className="nds-input" data-size="sm" type="text" readOnly value={share.link} onFocus={(event) => event.target.select()} data-modal-initial-focus="" />
</label>
<p className="toolbox-share-link-meta">
{fillTemplate(content.expires, { date: formatShareDate(share.expiresAt) })} {share.singleUse ? content.singleUseActive : content.reusableActive}
</p>
<div className="nds-toolbar toolbox-share-link-actions">
<button className="nds-button" data-size="sm" data-variant="primary" type="button" onClick={() => void copy()}><Icon name="copy" />{copied ? content.copied : content.copy}</button>
<button className="nds-button" data-size="sm" data-variant="danger" type="button" disabled={busy} onClick={() => onRevoke(share.id)}><Icon name="trash" />{content.revoke}</button>
</div>
</section>
);
}
export function ShareToolboxModal({ toolbox, content, actions, onClose }) {
const titleId = useId();
const descriptionId = useId();
const quota = useMemo(() => createShareQuota(), []);
const [shares, setShares] = useState(null);
const [singleUse, setSingleUse] = useState(true);
const [stage, setStage] = useState(null);
const [error, setError] = useState("");
const [revoking, setRevoking] = useState(false);
useEffect(() => {
let active = true;
refreshActiveShares(quota).then((list) => { if (active) setShares(list); });
return () => { active = false; };
}, [quota]);
const current = shares?.find((share) => share.toolboxId === toolbox.id) || null;
// Relu à chaque rendu : le journal du navigateur peut avoir changé depuis un autre onglet.
const limit = shares ? quota.check(0) : { ok: true };
const sending = Boolean(stage);
async function send() {
setError("");
try {
const share = await createToolboxShare({
toolboxId: toolbox.id,
buildPayload: actions.buildToolboxExportPayload,
maxBytes: actions.sharesMaxBytes,
singleUse,
quota,
onStage: setStage
});
// Si le stockage du navigateur est indisponible, le lien créé reste affiché pour cette session.
setShares(quota.activeShares().some((item) => item.id === share.id) ? quota.activeShares() : [...quota.activeShares(), share]);
} catch (cause) {
setError(cause instanceof ShareLimitError ? limitMessage(content, cause) : cause.message);
} finally {
setStage(null);
}
}
async function revoke(id) {
setError("");
setRevoking(true);
try {
await revokeToolboxShare(id, quota);
setShares(quota.activeShares());
actions.notify?.(content.revoked);
} catch (cause) {
setError(cause.message);
} finally {
setRevoking(false);
}
}
const otherShares = (shares || []).filter((share) => share.toolboxId !== toolbox.id);
return (
<Modal rootClassName="confirm-modal-root toolbox-share-modal-root" dialogClassName="confirm-modal nds-modal toolbox-share-modal themed-scrollbar" labelledBy={titleId} describedBy={descriptionId} onRequestClose={onClose} canClose={!sending}>
<header className="toolbox-share-modal-header">
<div>
<p className="eyebrow">{content.eyebrow}</p>
<h2 id={titleId}>{fillTemplate(content.title, { name: toolbox.name })}</h2>
</div>
<button className="nds-icon-button" data-size="sm" type="button" disabled={sending} onClick={onClose} aria-label={content.close} title={content.close}><Icon name="close" /></button>
</header>
<p id={descriptionId} className="toolbox-share-description">{content.description}</p>
{!shares && <p className="toolbox-share-status" role="status">{content.checking}</p>}
{shares && current && <>
<p className="nds-inline-notice" data-variant="info" role="status">{content.existing}</p>
<ShareLink share={current} content={content} onRevoke={(id) => void revoke(id)} busy={revoking} />
</>}
{shares && !current && sending && (
<p className="toolbox-share-status" role="status" aria-live="polite">
{stage.stage === "preparing" ? content.preparing : fillTemplate(content.uploading, { percent: Math.round((stage.progress || 0) * 100) })}
</p>
)}
{shares && !current && !sending && (limit.ok ? (
<form className="toolbox-share-form" onSubmit={(event) => {
event.preventDefault();
void send();
}}>
<label className="toolbox-share-option">
<input className="nds-checkbox" data-size="sm" type="checkbox" checked={singleUse} onChange={(event) => setSingleUse(event.target.checked)} />
<span><strong>{content.singleUseLabel}</strong><small>{content.singleUseHelp}</small></span>
</label>
<footer className="nds-modal-footer">
<button className="nds-button" data-size="sm" type="button" onClick={onClose}>{content.cancel}</button>
<button className="nds-button" data-size="sm" data-variant="primary" type="submit" data-modal-initial-focus=""><Icon name="send" />{content.create}</button>
</footer>
</form>
) : <p className="nds-inline-notice" data-variant="warning" role="status">{limitMessage(content, limit)}</p>)}
{error && <p className="nds-inline-notice toolbox-share-error" data-variant="danger" role="alert">{error}</p>}
{otherShares.length > 0 && (
<section className="toolbox-share-active" aria-labelledby={`${titleId}-active`}>
<h3 id={`${titleId}-active`}>{content.activeTitle}</h3>
<ul>
{otherShares.map((share) => (
<li key={share.id}>
<span><strong>{share.toolboxName}</strong><small>{fillTemplate(content.expires, { date: formatShareDate(share.expiresAt) })}</small></span>
<button className="nds-button" data-size="xs" data-variant="danger" type="button" disabled={revoking || sending} onClick={() => void revoke(share.id)}>{content.revoke}</button>
</li>
))}
</ul>
</section>
)}
<p className="toolbox-share-privacy">{content.privacy}</p>
<footer className="nds-modal-footer toolbox-share-close-footer">
{error && actions.exportToolbox && <button className="nds-button" data-size="sm" type="button" disabled={sending} onClick={() => void actions.exportToolbox(toolbox.id)}><Icon name="export" />{content.exportFallback}</button>}
<button className="nds-button" data-size="sm" type="button" disabled={sending} onClick={onClose}>{content.close}</button>
</footer>
</Modal>
);
}

View file

@ -0,0 +1,102 @@
// Rôle : compresse et chiffre une toolbox envoyée, pour que le serveur n'en garde qu'une copie illisible.
const MAGIC = new TextEncoder().encode("SKS1");
const IV_BYTES = 12;
const KEY_BYTES = 32;
// Un envoi de 50 Mo compressés ne doit pas pouvoir faire déborder la mémoire une fois décompressé.
export const SHARE_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024;
export class ShareCryptoError extends Error {
constructor(code, message) {
super(message);
this.name = "ShareCryptoError";
this.code = code;
}
}
function toBase64Url(bytes) {
let binary = "";
bytes.forEach((byte) => { binary += String.fromCharCode(byte); });
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function fromBase64Url(text) {
if (!/^[A-Za-z0-9_-]+$/.test(String(text || ""))) return null;
try {
const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
} catch {
return null;
}
}
function concat(...parts) {
const result = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
let offset = 0;
parts.forEach((part) => {
result.set(part, offset);
offset += part.length;
});
return result;
}
async function readLimited(stream, limit) {
const reader = stream.getReader();
const chunks = [];
let size = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > limit) {
await reader.cancel();
throw new ShareCryptoError("SHARE_FORMAT", "Cette toolbox est trop volumineuse une fois décompressée.");
}
chunks.push(value);
}
return concat(...chunks);
}
async function gzip(bytes) {
const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip"));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
function gunzip(bytes) {
return readLimited(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")), SHARE_MAX_DECOMPRESSED_BYTES);
}
export function isShareKey(text) {
return fromBase64Url(text)?.length === KEY_BYTES;
}
// Format : "SKS1", IV de 12 octets, puis le JSON compressé et chiffré en AES-GCM 256. L'en-tête est authentifié.
export async function encryptSharePayload(value) {
const plain = await gzip(new TextEncoder().encode(JSON.stringify(value)));
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: MAGIC }, key, plain));
const rawKey = new Uint8Array(await crypto.subtle.exportKey("raw", key));
return { bytes: concat(MAGIC, iv, cipher), key: toBase64Url(rawKey) };
}
export async function decryptSharePayload(input, keyText) {
const rawKey = fromBase64Url(keyText);
if (rawKey?.length !== KEY_BYTES) throw new ShareCryptoError("SHARE_KEY_INVALID", "Ce lien est incomplet : la clé de déchiffrement manque ou a été modifiée.");
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
if (bytes.length < MAGIC.length + IV_BYTES + 16 || MAGIC.some((byte, index) => bytes[index] !== byte)) {
throw new ShareCryptoError("SHARE_FORMAT", "Le contenu reçu n'est pas une toolbox envoyée depuis Sokko G.");
}
const key = await crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["decrypt"]);
let plain;
try {
plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(MAGIC.length, MAGIC.length + IV_BYTES), additionalData: MAGIC }, key, bytes.subarray(MAGIC.length + IV_BYTES));
} catch {
throw new ShareCryptoError("SHARE_KEY_INVALID", "Ce lien est incomplet ou a été modifié : la toolbox ne peut pas être déchiffrée.");
}
try {
return JSON.parse(new TextDecoder().decode(await gunzip(new Uint8Array(plain))));
} catch (error) {
if (error instanceof ShareCryptoError) throw error;
throw new ShareCryptoError("SHARE_FORMAT", "Le contenu reçu n'est pas une toolbox valide.");
}
}

View file

@ -0,0 +1,14 @@
// Rôle : met en forme les textes, dates et tailles affichés autour d'un envoi de toolbox.
const MIB = 1024 * 1024;
export function fillTemplate(text, values = {}) {
return String(text || "").replace(/\{(\w+)\}/g, (match, key) => (key in values ? String(values[key]) : match));
}
export function formatShareDate(value) {
return new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
}
export function formatMiB(bytes) {
return new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 1 }).format(bytes / MIB);
}

View file

@ -0,0 +1,94 @@
// Rôle : limite les envois de toolbox depuis ce navigateur et retient les liens encore valides pour pouvoir les révoquer.
// Ces limites se contournent facilement (navigation privée, autre navigateur) : les plafonds du serveur restent la vraie protection.
export const SENT_SHARES_STORAGE_KEY = "sokkog:sent-shares";
export const SHARE_LOG_STORAGE_KEY = "sokkog:share-log";
const DAY_MS = 24 * 60 * 60 * 1000;
const MIB = 1024 * 1024;
export const SHARE_QUOTA = Object.freeze({
maxActive: 2,
maxPerDay: 2,
maxBytesPerDay: 100 * MIB
});
function defaultStorage() {
try {
return globalThis.localStorage || null;
} catch {
return null;
}
}
function readList(storage, key) {
try {
const value = JSON.parse(storage?.getItem(key) || "[]");
return Array.isArray(value) ? value : [];
} catch {
return [];
}
}
function writeList(storage, key, list) {
try {
if (list.length) storage?.setItem(key, JSON.stringify(list));
else storage?.removeItem(key);
} catch {
// Stockage indisponible ou plein : les limites du navigateur ne s'appliquent plus, celles du serveur restent.
}
}
const isShare = (entry) => entry && typeof entry.id === "string" && typeof entry.toolboxId === "string"
&& typeof entry.deleteToken === "string" && Number.isFinite(entry.expiresAt);
const isLogEntry = (entry) => entry && Number.isFinite(entry.at) && Number.isFinite(entry.bytes) && entry.bytes >= 0;
export function createShareQuota({ storage = defaultStorage(), now = Date.now, quota = SHARE_QUOTA } = {}) {
function activeShares() {
const current = now();
const stored = readList(storage, SENT_SHARES_STORAGE_KEY);
const active = stored.filter((entry) => isShare(entry) && entry.expiresAt > current);
if (active.length !== stored.length) writeList(storage, SENT_SHARES_STORAGE_KEY, active);
return active;
}
// Le journal garde aussi les envois révoqués : révoquer puis renvoyer ne libère pas le quota du jour.
function recentLog() {
const since = now() - DAY_MS;
const stored = readList(storage, SHARE_LOG_STORAGE_KEY);
const recent = stored.filter((entry) => isLogEntry(entry) && entry.at > since).sort((a, b) => a.at - b.at);
if (recent.length !== stored.length) writeList(storage, SHARE_LOG_STORAGE_KEY, recent);
return recent;
}
return {
activeShares,
activeShareFor(toolboxId) {
return activeShares().find((entry) => entry.toolboxId === toolboxId) || null;
},
// Avant le chiffrement, `bytes` vaut 0 : seuls le nombre d'envois et le volume déjà utilisé comptent.
check(bytes = 0) {
if (activeShares().length >= quota.maxActive) return { ok: false, reason: "active" };
const log = recentLog();
if (log.length >= quota.maxPerDay) return { ok: false, reason: "daily-count", retryAt: log[log.length - quota.maxPerDay].at + DAY_MS };
const used = log.reduce((sum, entry) => sum + entry.bytes, 0);
if (used + bytes > quota.maxBytesPerDay) {
let freed = used;
const entry = log.find((item) => {
freed -= item.bytes;
return freed + bytes <= quota.maxBytesPerDay;
});
return { ok: false, reason: "daily-bytes", retryAt: entry ? entry.at + DAY_MS : null };
}
return { ok: true };
},
record(share, bytes) {
const entry = { id: share.id, toolboxId: share.toolboxId, toolboxName: share.toolboxName || "", expiresAt: share.expiresAt, deleteToken: share.deleteToken, singleUse: Boolean(share.singleUse), link: share.link || "" };
writeList(storage, SENT_SHARES_STORAGE_KEY, [...activeShares().filter((item) => item.id !== entry.id), entry]);
writeList(storage, SHARE_LOG_STORAGE_KEY, [...recentLog(), { at: now(), bytes }]);
return entry;
},
// Un lien révoqué, déjà utilisé ou expiré libère sa place d'envoi actif.
forget(id) {
writeList(storage, SENT_SHARES_STORAGE_KEY, activeShares().filter((entry) => entry.id !== id));
}
};
}

View file

@ -0,0 +1,74 @@
// Rôle : centralise les appels à l'API d'envoi de toolbox et rend leurs erreurs lisibles.
const FALLBACK_ERROR = "Le service d'envoi est indisponible. Réessayez plus tard.";
function apiError(status, payload, fallback = FALLBACK_ERROR) {
return Object.assign(new Error(payload?.error?.message || fallback), { status, code: payload?.error?.code || "" });
}
async function failedResponse(response) {
return apiError(response.status, await response.json().catch(() => null));
}
export async function loadSharesConfig() {
const response = await fetch("/api/shares/config", { headers: { Accept: "application/json" } });
if (!response.ok) throw await failedResponse(response);
return response.json();
}
// XMLHttpRequest reste nécessaire pour suivre la progression d'un envoi : fetch ne l'expose pas.
export function uploadShare(bytes, { singleUse = true, onProgress } = {}) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open("POST", "/api/shares");
request.setRequestHeader("Content-Type", "application/octet-stream");
request.setRequestHeader("X-Sokkog-Share", "1");
if (singleUse) request.setRequestHeader("X-Share-Single-Use", "1");
request.responseType = "json";
request.upload.onprogress = (event) => {
if (event.lengthComputable) onProgress?.(event.loaded / event.total);
};
request.onload = () => {
if (request.status === 201 && request.response?.id) resolve(request.response);
else reject(apiError(request.status, request.response));
};
request.onerror = () => reject(apiError(0, null));
request.send(bytes);
});
}
export async function loadShareMeta(id) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}/meta`, { headers: { Accept: "application/json" } });
if (!response.ok) throw await failedResponse(response);
return response.json();
}
export async function downloadShare(id, { onProgress } = {}) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}`);
if (!response.ok) throw await failedResponse(response);
const total = Number(response.headers.get("Content-Length")) || 0;
if (!response.body) return new Uint8Array(await response.arrayBuffer());
const reader = response.body.getReader();
const chunks = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
if (total) onProgress?.(received / total);
}
const bytes = new Uint8Array(received);
let offset = 0;
chunks.forEach((chunk) => {
bytes.set(chunk, offset);
offset += chunk.length;
});
return bytes;
}
// Un lien déjà expiré ou utilisé n'existe plus : la révocation est alors considérée comme faite.
export async function revokeShare(id, deleteToken) {
const response = await fetch(`/api/shares/${encodeURIComponent(id)}`, { method: "DELETE", headers: { "X-Share-Delete-Token": deleteToken } });
if (response.ok || response.status === 404) return true;
throw await failedResponse(response);
}

View file

@ -0,0 +1,63 @@
// Rôle : enchaîne l'export, le chiffrement, les quotas et l'envoi d'une toolbox, puis la révocation de ses liens.
import { encryptSharePayload } from "./shareCrypto.js";
import { createShareQuota } from "./shareQuota.js";
import { loadShareMeta, revokeShare, uploadShare } from "./sharesApi.js";
export class ShareLimitError extends Error {
constructor(reason, details = {}) {
super(reason);
this.name = "ShareLimitError";
this.reason = reason;
Object.assign(this, details);
}
}
export function shareLink(id, key, origin = globalThis.location?.origin || "") {
return `${origin}/#/receive/${id}#${key}`;
}
export async function createToolboxShare({ toolboxId, buildPayload, maxBytes, singleUse = true, onStage, quota = createShareQuota() }) {
const existing = quota.activeShareFor(toolboxId);
if (existing) return existing;
const before = quota.check(0);
if (!before.ok) throw new ShareLimitError(before.reason, { retryAt: before.retryAt });
onStage?.({ stage: "preparing" });
const built = await buildPayload(toolboxId);
if (!built) throw new Error("La toolbox n'a pas pu être lue. Réessayez.");
const { bytes, key } = await encryptSharePayload(built.payload);
if (bytes.length > maxBytes) throw new ShareLimitError("too-large", { size: bytes.length, maxBytes });
const sized = quota.check(bytes.length);
if (!sized.ok) throw new ShareLimitError(sized.reason, { retryAt: sized.retryAt });
onStage?.({ stage: "uploading", progress: 0 });
const result = await uploadShare(bytes, { singleUse, onProgress: (progress) => onStage?.({ stage: "uploading", progress }) });
return quota.record({
id: result.id,
toolboxId,
toolboxName: built.toolbox.name,
expiresAt: result.expiresAt,
deleteToken: result.deleteToken,
singleUse: result.singleUse,
link: shareLink(result.id, key)
}, bytes.length);
}
export async function revokeToolboxShare(shareId, quota = createShareQuota()) {
const entry = quota.activeShares().find((item) => item.id === shareId);
if (!entry) return;
await revokeShare(entry.id, entry.deleteToken);
quota.forget(entry.id);
}
// Retire de la liste les liens que le serveur ne connaît plus : utilisés, révoqués ailleurs ou expirés.
export async function refreshActiveShares(quota = createShareQuota()) {
await Promise.all(quota.activeShares().map(async (entry) => {
try {
await loadShareMeta(entry.id);
} catch (error) {
if (error.status === 404) quota.forget(entry.id);
}
}));
return quota.activeShares();
}

View file

@ -0,0 +1,17 @@
// Rôle : indique si le serveur accepte les envois de toolbox, et avec quelle taille maximale.
import { useEffect, useState } from "react";
import { loadSharesConfig } from "./sharesApi.js";
const DISABLED = { enabled: false, maxBytes: 0, ttlMs: 0 };
export function useSharesConfig() {
const [config, setConfig] = useState({ loading: true, ...DISABLED });
useEffect(() => {
let active = true;
loadSharesConfig()
.then((value) => { if (active) setConfig({ loading: false, ...DISABLED, ...value }); })
.catch(() => { if (active) setConfig({ loading: false, ...DISABLED }); });
return () => { active = false; };
}, []);
return config;
}

View file

@ -31,7 +31,7 @@ function getLibraryUrl() {
return `${window.location.origin}${window.location.pathname}#/library`;
}
export function useToolboxActions({ store, notify, creationTemplate, importContent, setConfirmModal, setCreateModal, setLinkModalGameId, setDrawerGameId, setImage }) {
export function useToolboxActions({ store, notify, creationTemplate, importContent, setConfirmModal, setCreateModal, setLinkModalGameId, setDrawerGameId, setImage, sharesConfig = null, setShareToolboxId = null }) {
const importText = {
replaceLinksTitle: importContent?.replaceLinksTitle || "Réattribuer des associations de jeu ?",
replaceLinksMessage: importContent?.replaceLinksMessage || "Des associations de jeu existantes ({count}) seront réattribuées aux copies importées. Les toolboxes déjà présentes seront conservées.",
@ -329,6 +329,15 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
return normalizedImport;
}
// Instantané cohérent d'une toolbox au format d'export v2, commun à l'export en fichier et à l'envoi.
async function buildToolboxExportPayload(id) {
const snapshot = await store.getExportSnapshot(id);
if (!snapshot) return null;
const toolbox = normalizeToolbox(snapshot.toolboxes.find((item) => item.id === id));
if (!toolbox) return null;
return { toolbox, payload: createToolboxExportPayload(toolbox, snapshot.moduleData) };
}
async function importAllToolboxesPayload(payload) {
const toolboxIdMap = new Map();
const moduleIdMap = new Map();
@ -456,13 +465,23 @@ export function useToolboxActions({ store, notify, creationTemplate, importConte
},
exportToolbox: async (id) => {
if (!store.ready) return false;
const snapshot = await store.getExportSnapshot(id);
if (!snapshot) return false;
const toolbox = normalizeToolbox(snapshot.toolboxes.find((item) => item.id === id));
if (!toolbox) return;
downloadJson(createToolboxExportPayload(toolbox, snapshot.moduleData), `${toolbox.name.toLowerCase().replace(/[^a-z0-9]+/gi, "-")}.sokkog.json`);
const built = await buildToolboxExportPayload(id);
if (!built) return false;
downloadJson(built.payload, `${built.toolbox.name.toLowerCase().replace(/[^a-z0-9]+/gi, "-")}.sokkog.json`);
notify("Export de la toolbox lancé.");
},
sharingEnabled: Boolean(sharesConfig?.enabled && setShareToolboxId),
sharesMaxBytes: sharesConfig?.maxBytes || 0,
openShareToolbox: (id) => setShareToolboxId?.(id),
buildToolboxExportPayload: (id) => (store.ready ? buildToolboxExportPayload(id) : Promise.resolve(null)),
// Une toolbox reçue suit le même contrat que l'import de fichier : validée, copiée avec de nouveaux identifiants, sans association de jeu.
importReceivedToolbox: async (payload) => {
if (!store.ready) throw new Error("Le stockage local n'est pas prêt.");
const toolbox = await importToolboxPayload(validateToolboxImportPayload(payload, "single"));
if (!toolbox) throw new Error("La toolbox reçue n'a pas pu être enregistrée dans ce navigateur.");
notify("Toolbox importée.");
return toolbox;
},
exportAllToolboxes: async () => {
if (!store.ready) return false;
const snapshot = await store.getExportSnapshot();

View file

@ -21,6 +21,7 @@ import { useAutoBackup } from "./features/toolboxes/storage/useAutoBackup.js";
import { GlobalMemosTicker } from "./features/toolboxes/GlobalMemosTicker.jsx";
import { useMediaQuery } from "./hooks/useMediaQuery.js";
import { useCardsConfig } from "./features/cards/useCardsConfig.js";
import { useSharesConfig } from "./features/toolboxes/sharing/useSharesConfig.js";
const assetRecoveryUrl = new URL(window.location.href);
if (assetRecoveryUrl.searchParams.has("_asset-recovery")) {
@ -46,6 +47,7 @@ function App() {
const compactGameLayout = useMediaQuery("(max-width: 1439px)");
const reducedSidebar = useMediaQuery("(max-width: 1024px)");
const cardsConfig = useCardsConfig();
const sharesConfig = useSharesConfig();
const {
siteContent,
siteContentError,
@ -64,6 +66,7 @@ function App() {
const [createModal, setCreateModal] = useState(null);
const [autoBackupModalOpen, setAutoBackupModalOpen] = useState(false);
const [linkModalGameId, setLinkModalGameId] = useState("");
const [shareToolboxId, setShareToolboxId] = useState("");
const [drawerGameId, setDrawerGameId] = useState("");
const [drawerVisible, setDrawerVisible] = useState(false);
const [drawerContext, setDrawerContext] = useState({ route, compactGameLayout });
@ -166,7 +169,9 @@ function App() {
setConfirmModal,
setLinkModalGameId,
setDrawerGameId: setGameToolbox,
setImage
setImage,
sharesConfig,
setShareToolboxId
});
useToolboxAlerts({
@ -297,6 +302,9 @@ function App() {
setCreateModal={setCreateModal}
linkModalGameId={linkModalGameId}
setLinkModalGameId={setLinkModalGameId}
shareToolboxId={shareToolboxId}
setShareToolboxId={setShareToolboxId}
shareContent={siteContent.toolboxShare}
setDrawerGameId={setGameToolbox}
storageError={storageError}
setStorageError={setStorageError}

View file

@ -9,6 +9,7 @@ const GamesPage = lazy(() => import("../features/games/GamesPage.jsx").then((mod
const LibraryPage = lazy(() => import("../pages/LibraryPage.jsx").then((module) => ({ default: module.LibraryPage })));
const CardsPage = lazy(() => import("../features/cards/CardsPage.jsx").then((module) => ({ default: module.CardsPage })));
const ToolboxPage = lazy(() => import("../features/toolboxes/ToolboxPages.jsx").then((module) => ({ default: module.ToolboxPage })));
const ReceiveToolboxPage = lazy(() => import("../features/toolboxes/sharing/ReceiveToolboxPage.jsx").then((module) => ({ default: module.ReceiveToolboxPage })));
const ToolboxesPage = lazy(() => import("../features/toolboxes/ToolboxPages.jsx").then((module) => ({ default: module.ToolboxesPage })));
const DesignSystemPage = import.meta.env.DEV
? lazy(() => import("../pages/DesignSystemPage.jsx").then((module) => ({ default: module.DesignSystemPage })))
@ -37,6 +38,7 @@ export function RouteContent(props) {
}
if (route === "/design-system" && DesignSystemPage) return <Suspense fallback={<RouteLoader />}><DesignSystemPage /></Suspense>;
if (route === "/toolboxes") return <Suspense fallback={<RouteLoader />}><ToolboxesPage {...props} /></Suspense>;
if (route.startsWith("/receive/")) return <Suspense fallback={<RouteLoader />}><ReceiveToolboxPage siteContent={props.siteContent} actions={props.actions} shareId={route.split("/")[2] || ""} /></Suspense>;
if (route.startsWith("/toolbox/")) return <Suspense fallback={<RouteLoader />}><ToolboxPage {...props} toolboxId={route.split("/")[2]} /></Suspense>;
if (route === "/games") return <Suspense fallback={<RouteLoader />}><GamesPage {...props} /></Suspense>;
if (route.startsWith("/games/")) return <Suspense fallback={<RouteLoader />}><GameRoute {...props} gameId={route.split("/")[2]} category={route.split("/")[3] || ""} /></Suspense>;

View file

@ -6,3 +6,4 @@
@use "overlays/notifications";
@use "overlays/tool-add";
@use "overlays/toolbox-management";
@use "overlays/toolbox-share";

View file

@ -44,6 +44,11 @@
-webkit-mask-image: url("/static/icons/import.svg");
}
.ui-icon-send {
mask-image: url("/static/icons/send.svg");
-webkit-mask-image: url("/static/icons/send.svg");
}
.ui-icon-link {
mask-image: url("/static/icons/link.svg");
-webkit-mask-image: url("/static/icons/link.svg");

View file

@ -0,0 +1,151 @@
// Rôle : stylise l'envoi d'une toolbox par lien et la page de réception.
.toolbox-share-modal.nds-modal {
width: min(620px, calc(100vw - 32px));
max-height: min(760px, calc(100vh - 32px));
overflow-y: auto;
}
.toolbox-share-modal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-4);
}
.toolbox-share-modal-header h2 {
margin-bottom: 0;
overflow-wrap: anywhere;
}
.toolbox-share-modal-header .eyebrow {
margin-bottom: 4px;
}
.toolbox-share-description,
.toolbox-share-privacy,
.toolbox-share-link-meta,
.toolbox-share-status {
color: var(--color-text-secondary);
line-height: 1.6;
}
.toolbox-share-privacy {
margin-top: var(--space-4);
font-size: var(--font-size-sm);
}
.toolbox-share-form,
.toolbox-share-link,
.toolbox-share-error,
.toolbox-share-active {
margin-top: var(--space-4);
}
.toolbox-share-option {
display: flex;
align-items: flex-start;
gap: var(--space-3);
padding: var(--space-4);
border: 1px solid rgba(165, 180, 252, 0.14);
border-radius: var(--radius-md);
background: rgba(5, 7, 17, 0.32);
cursor: pointer;
}
.toolbox-share-option input {
flex: none;
margin-top: 2px;
}
.toolbox-share-option span,
.toolbox-share-active li > span {
display: grid;
gap: 2px;
min-width: 0;
}
.toolbox-share-option small,
.toolbox-share-active small {
color: var(--color-text-secondary);
}
.toolbox-share-link .nds-input {
width: 100%;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.toolbox-share-link-actions {
margin-top: var(--space-3);
}
.toolbox-share-active h3 {
margin-bottom: var(--space-2);
font-size: var(--font-size-sm);
}
.toolbox-share-active ul {
display: grid;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.toolbox-share-active li {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}
.toolbox-share-active strong {
overflow-wrap: anywhere;
}
.toolbox-receive {
width: min(720px, 100%);
margin: 0 auto;
}
.toolbox-receive-card {
padding: var(--space-6);
}
.toolbox-receive-summary {
display: flex;
align-items: center;
gap: var(--space-4);
margin-top: var(--space-4);
}
.toolbox-receive-summary img {
flex: none;
width: 72px;
height: 72px;
border-radius: var(--radius-md);
object-fit: cover;
background: var(--gradient-nebula);
}
.toolbox-receive-summary h2 {
margin-bottom: 4px;
overflow-wrap: anywhere;
}
.toolbox-receive-tools {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: var(--space-4) 0 var(--space-3);
padding: 0;
list-style: none;
}
.toolbox-receive-text {
color: var(--color-text-secondary);
line-height: 1.6;
}
.toolbox-receive-actions {
margin-top: var(--space-5);
}