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>
102 lines
4 KiB
JavaScript
102 lines
4 KiB
JavaScript
// 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.");
|
|
}
|
|
}
|