Send a toolbox through an encrypted link
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:
parent
957bfdc86f
commit
bec9ea5b2f
43 changed files with 2349 additions and 59 deletions
143
website/src/features/toolboxes/sharing/ReceiveToolboxPage.jsx
Normal file
143
website/src/features/toolboxes/sharing/ReceiveToolboxPage.jsx
Normal 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>
|
||||
);
|
||||
}
|
||||
161
website/src/features/toolboxes/sharing/ShareToolboxModal.jsx
Normal file
161
website/src/features/toolboxes/sharing/ShareToolboxModal.jsx
Normal 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>
|
||||
);
|
||||
}
|
||||
102
website/src/features/toolboxes/sharing/shareCrypto.js
Normal file
102
website/src/features/toolboxes/sharing/shareCrypto.js
Normal 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.");
|
||||
}
|
||||
}
|
||||
14
website/src/features/toolboxes/sharing/shareFormat.js
Normal file
14
website/src/features/toolboxes/sharing/shareFormat.js
Normal 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);
|
||||
}
|
||||
94
website/src/features/toolboxes/sharing/shareQuota.js
Normal file
94
website/src/features/toolboxes/sharing/shareQuota.js
Normal 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));
|
||||
}
|
||||
};
|
||||
}
|
||||
74
website/src/features/toolboxes/sharing/sharesApi.js
Normal file
74
website/src/features/toolboxes/sharing/sharesApi.js
Normal 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);
|
||||
}
|
||||
63
website/src/features/toolboxes/sharing/toolboxSharing.js
Normal file
63
website/src/features/toolboxes/sharing/toolboxSharing.js
Normal 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();
|
||||
}
|
||||
17
website/src/features/toolboxes/sharing/useSharesConfig.js
Normal file
17
website/src/features/toolboxes/sharing/useSharesConfig.js
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue