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
|
|
@ -199,6 +199,8 @@ export function validateSiteContent(site) {
|
|||
"cards.collection.resetFilters",
|
||||
"cards.history.pendingCards",
|
||||
...["eyebrow", "title", "description", "summaryTitle", "summaryName", "summaryCards", "summaryOpenings", "deleteTitle", "deleteText", "deleteButton", "confirmTitle", "confirmMessage", "confirmLabel", "deleted"].map((key) => `cards.account.${key}`),
|
||||
...["eyebrow", "title", "description", "checking", "singleUseLabel", "singleUseHelp", "create", "cancel", "close", "preparing", "uploading", "linkLabel", "copy", "copied", "expires", "singleUseActive", "reusableActive", "revoke", "revoked", "existing", "limitActive", "limitDailyCount", "limitDailyBytes", "tooLarge", "activeTitle", "exportFallback", "privacy"].map((key) => `toolboxShare.${key}`),
|
||||
...["eyebrow", "title", "checking", "downloading", "decrypting", "importing", "expires", "spaces", "localNote", "import", "singleUseNotice", "receiveAndImport", "notFound", "keyMissing", "disabled", "failed", "retry", "back"].map((key) => `toolboxShare.receive.${key}`),
|
||||
...["title", "intro", "collectedTitle", "collected", "purposeTitle", "purpose", "visibilityTitle", "visibility", "retentionTitle", "retention", "rightsTitle", "rights", "controllerLabel", "controllerMissing", "contactLabel", "contactMissing"].map((key) => `cards.privacy.${key}`),
|
||||
"cards.recycling.barLabel",
|
||||
"cards.recycling.viewDuplicates",
|
||||
|
|
|
|||
51
tests/toolbox-share-crypto.test.mjs
Normal file
51
tests/toolbox-share-crypto.test.mjs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
// Rôle : vérifie que le chiffrement d'un envoi de toolbox est réversible avec la bonne clé seulement.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { decryptSharePayload, encryptSharePayload, isShareKey, ShareCryptoError } from "../website/src/features/toolboxes/sharing/shareCrypto.js";
|
||||
|
||||
const sample = {
|
||||
version: 2,
|
||||
toolbox: { id: "tbx1", name: "Monster Hunter Wilds — été", modules: [{ id: "mod1", type: "checklist", title: "Quêtes" }] },
|
||||
modules: { mod1: { sections: [{ id: "sec1", title: "Rang élevé", items: [] }] } }
|
||||
};
|
||||
|
||||
async function rejectsWith(promise, code) {
|
||||
await assert.rejects(promise, (error) => error instanceof ShareCryptoError && error.code === code);
|
||||
}
|
||||
|
||||
test("an encrypted share decrypts back to the same payload", async () => {
|
||||
const { bytes, key } = await encryptSharePayload(sample);
|
||||
assert.ok(isShareKey(key));
|
||||
assert.equal(new TextDecoder().decode(bytes.subarray(0, 4)), "SKS1");
|
||||
assert.equal(new TextDecoder().decode(bytes).includes("Monster"), false);
|
||||
assert.deepEqual(await decryptSharePayload(bytes, key), sample);
|
||||
assert.deepEqual(await decryptSharePayload(bytes.buffer, key), sample);
|
||||
});
|
||||
|
||||
test("each share uses its own key and IV", async () => {
|
||||
const first = await encryptSharePayload(sample);
|
||||
const second = await encryptSharePayload(sample);
|
||||
assert.notEqual(first.key, second.key);
|
||||
assert.notDeepEqual(first.bytes.subarray(4, 16), second.bytes.subarray(4, 16));
|
||||
});
|
||||
|
||||
test("a wrong, missing or malformed key is refused", async () => {
|
||||
const { bytes } = await encryptSharePayload(sample);
|
||||
const other = await encryptSharePayload(sample);
|
||||
await rejectsWith(decryptSharePayload(bytes, other.key), "SHARE_KEY_INVALID");
|
||||
await rejectsWith(decryptSharePayload(bytes, ""), "SHARE_KEY_INVALID");
|
||||
await rejectsWith(decryptSharePayload(bytes, "abc"), "SHARE_KEY_INVALID");
|
||||
await rejectsWith(decryptSharePayload(bytes, "not+base64url/"), "SHARE_KEY_INVALID");
|
||||
assert.equal(isShareKey(other.key.slice(1)), false);
|
||||
});
|
||||
|
||||
test("tampered content or an unknown format is refused", async () => {
|
||||
const { bytes, key } = await encryptSharePayload(sample);
|
||||
const tampered = bytes.slice();
|
||||
tampered[tampered.length - 1] ^= 1;
|
||||
await rejectsWith(decryptSharePayload(tampered, key), "SHARE_KEY_INVALID");
|
||||
const header = bytes.slice();
|
||||
header[0] = 0;
|
||||
await rejectsWith(decryptSharePayload(header, key), "SHARE_FORMAT");
|
||||
await rejectsWith(decryptSharePayload(new Uint8Array(10), key), "SHARE_FORMAT");
|
||||
});
|
||||
98
tests/toolbox-share-quota.test.mjs
Normal file
98
tests/toolbox-share-quota.test.mjs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// Rôle : vérifie les limites d'envoi de toolbox appliquées par le navigateur.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createShareQuota, SENT_SHARES_STORAGE_KEY, SHARE_LOG_STORAGE_KEY } from "../website/src/features/toolboxes/sharing/shareQuota.js";
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const MIB = 1024 * 1024;
|
||||
|
||||
function memoryStorage() {
|
||||
const values = new Map();
|
||||
return {
|
||||
values,
|
||||
getItem: (key) => (values.has(key) ? values.get(key) : null),
|
||||
setItem: (key, value) => values.set(key, String(value)),
|
||||
removeItem: (key) => values.delete(key)
|
||||
};
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const storage = memoryStorage();
|
||||
const clock = { value: Date.UTC(2026, 10, 11, 12) };
|
||||
const quota = createShareQuota({ storage, now: () => clock.value });
|
||||
let counter = 0;
|
||||
const send = (toolboxId, bytes = MIB) => {
|
||||
counter += 1;
|
||||
return quota.record({ id: `share${counter}`, toolboxId, toolboxName: toolboxId, expiresAt: clock.value + DAY, deleteToken: `token${counter}`, link: `https://sokkog.test/#/receive/share${counter}#key` }, bytes);
|
||||
};
|
||||
return { storage, clock, quota, send };
|
||||
}
|
||||
|
||||
test("a toolbox that was already sent keeps its existing link", () => {
|
||||
const { quota, send } = setup();
|
||||
assert.equal(quota.activeShareFor("tbx1"), null);
|
||||
const entry = send("tbx1");
|
||||
assert.deepEqual(quota.activeShareFor("tbx1"), entry);
|
||||
assert.equal(entry.link, "https://sokkog.test/#/receive/share1#key");
|
||||
assert.equal(quota.activeShareFor("tbx2"), null);
|
||||
});
|
||||
|
||||
test("at most two shares can be active at once", () => {
|
||||
const { quota, send, clock } = setup();
|
||||
send("tbx1");
|
||||
assert.deepEqual(quota.check(), { ok: true });
|
||||
clock.value += 1000;
|
||||
send("tbx2");
|
||||
assert.deepEqual(quota.check(), { ok: false, reason: "active" });
|
||||
});
|
||||
|
||||
test("revoking frees an active slot but not the daily quota", () => {
|
||||
const { quota, send, clock } = setup();
|
||||
const started = clock.value;
|
||||
const first = send("tbx1");
|
||||
clock.value += 60 * 60 * 1000;
|
||||
send("tbx2");
|
||||
quota.forget(first.id);
|
||||
assert.equal(quota.activeShares().length, 1);
|
||||
assert.deepEqual(quota.check(), { ok: false, reason: "daily-count", retryAt: started + DAY });
|
||||
clock.value = started + DAY + 1;
|
||||
quota.forget("share2");
|
||||
assert.deepEqual(quota.check(), { ok: true });
|
||||
});
|
||||
|
||||
test("no more than 100 MiB can be sent within 24 hours", () => {
|
||||
const { quota, send, clock } = setup();
|
||||
const started = clock.value;
|
||||
send("tbx1", 60 * MIB);
|
||||
quota.forget("share1");
|
||||
assert.deepEqual(quota.check(30 * MIB), { ok: true });
|
||||
assert.deepEqual(quota.check(50 * MIB), { ok: false, reason: "daily-bytes", retryAt: started + DAY });
|
||||
clock.value += 2 * 60 * 60 * 1000;
|
||||
assert.equal(quota.check(0).ok, true);
|
||||
});
|
||||
|
||||
test("expired shares and old log entries are dropped", () => {
|
||||
const { quota, send, clock, storage } = setup();
|
||||
send("tbx1");
|
||||
send("tbx2");
|
||||
clock.value += DAY;
|
||||
assert.deepEqual(quota.activeShares(), []);
|
||||
assert.deepEqual(quota.check(), { ok: true });
|
||||
assert.equal(storage.values.has(SENT_SHARES_STORAGE_KEY), false);
|
||||
assert.equal(storage.values.has(SHARE_LOG_STORAGE_KEY), false);
|
||||
});
|
||||
|
||||
test("corrupted or unavailable storage never blocks sharing", () => {
|
||||
const { storage, quota } = setup();
|
||||
storage.setItem(SENT_SHARES_STORAGE_KEY, "{not json");
|
||||
storage.setItem(SHARE_LOG_STORAGE_KEY, JSON.stringify([{ at: "x" }, null]));
|
||||
assert.deepEqual(quota.activeShares(), []);
|
||||
assert.deepEqual(quota.check(), { ok: true });
|
||||
|
||||
const throwing = { getItem() { throw new Error("blocked"); }, setItem() { throw new Error("blocked"); }, removeItem() { throw new Error("blocked"); } };
|
||||
const blocked = createShareQuota({ storage: throwing });
|
||||
assert.deepEqual(blocked.check(), { ok: true });
|
||||
assert.doesNotThrow(() => blocked.record({ id: "a", toolboxId: "t", expiresAt: Date.now() + DAY, deleteToken: "x" }, 1));
|
||||
assert.doesNotThrow(() => blocked.forget("a"));
|
||||
assert.equal(createShareQuota({ storage: null }).check().ok, true);
|
||||
});
|
||||
316
tests/toolbox-shares-api.test.mjs
Normal file
316
tests/toolbox-shares-api.test.mjs
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
// Rôle : vérifie le contrat HTTP de l'envoi de toolbox, l'usage unique, l'expiration et chaque plafond qui protège le serveur.
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, readdirSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { get as httpGet } from "node:http";
|
||||
import { connect } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { createSharesApi, createStaticServer } from "../server.mjs";
|
||||
import { SHARE_MAX_BYTES, SHARE_TTL_MS, createSharesApiHandler } from "../services/shares/api.js";
|
||||
|
||||
const TB = 1024 ** 4;
|
||||
// Les refus attendus sont journalisés par le service : ils ne doivent pas encombrer la sortie des tests.
|
||||
console.warn = () => {};
|
||||
|
||||
function payload(size = 256, fill = 7) {
|
||||
const bytes = Buffer.alloc(size, fill);
|
||||
bytes.write("SKS1", 0, "latin1");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
async function setup(t, options = {}) {
|
||||
const root = await mkdtemp(join(tmpdir(), "sokko-shares-root-"));
|
||||
const dir = options.dir || await mkdtemp(join(tmpdir(), "sokko-shares-"));
|
||||
await writeFile(join(root, "index.html"), "<main>Sokko G</main>");
|
||||
const clock = { value: Date.UTC(2026, 10, 11, 12) };
|
||||
const sharesApi = createSharesApiHandler({
|
||||
enabled: true,
|
||||
dir,
|
||||
env: { NODE_ENV: "test" },
|
||||
now: () => clock.value,
|
||||
statfs: options.statfs || (async () => ({ bavail: TB, bsize: 1 })),
|
||||
limits: options.limits || {}
|
||||
});
|
||||
const server = createStaticServer({ root, publicRoot: root, sharesApi });
|
||||
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
t.after(async () => {
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolvePromise) => server.close(resolvePromise));
|
||||
await rm(root, { recursive: true, force: true });
|
||||
if (!options.dir) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
return { base, dir, clock, sharesApi, port: server.address().port };
|
||||
}
|
||||
|
||||
function upload(base, body = payload(), { singleUse = false, headers = {} } = {}) {
|
||||
return fetch(`${base}/api/shares`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/octet-stream", "X-Sokkog-Share": "1", ...(singleUse ? { "X-Share-Single-Use": "1" } : {}), ...headers },
|
||||
body
|
||||
});
|
||||
}
|
||||
|
||||
async function created(base, body, options) {
|
||||
const response = await upload(base, body, options);
|
||||
assert.equal(response.status, 201, await response.clone().text());
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function download(base, id) {
|
||||
const response = await fetch(`${base}/api/shares/${id}`);
|
||||
return { status: response.status, headers: response.headers, body: Buffer.from(await response.arrayBuffer()) };
|
||||
}
|
||||
|
||||
// Envoie les en-têtes et une partie du corps à la main, pour simuler un client lent ou interrompu.
|
||||
function rawUpload(port, { declared, sent = Buffer.alloc(0) }) {
|
||||
const socket = connect(port, "127.0.0.1");
|
||||
const response = new Promise((resolvePromise) => {
|
||||
let data = "";
|
||||
socket.on("data", (chunk) => { data += chunk; });
|
||||
socket.on("close", () => resolvePromise(data.split("\r\n")[0]));
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
socket.write(`POST /api/shares HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/octet-stream\r\nX-Sokkog-Share: 1\r\nContent-Length: ${declared}\r\n\r\n`);
|
||||
if (sent.length) socket.write(sent);
|
||||
return { socket, response };
|
||||
}
|
||||
|
||||
function waitFor(predicate, timeoutMs = 3000) {
|
||||
const started = Date.now();
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const tick = () => {
|
||||
if (predicate()) return resolvePromise();
|
||||
if (Date.now() - started > timeoutMs) return reject(new Error("condition not reached"));
|
||||
setTimeout(tick, 10);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
}
|
||||
|
||||
const partFiles = (dir) => readdirSync(dir).filter((name) => name.endsWith(".part"));
|
||||
|
||||
test("config reports whether sharing is enabled", async (t) => {
|
||||
const { base } = await setup(t);
|
||||
assert.deepEqual(await (await fetch(`${base}/api/shares/config`)).json(), { enabled: true, maxBytes: SHARE_MAX_BYTES, ttlMs: SHARE_TTL_MS });
|
||||
|
||||
const disabled = createSharesApiHandler({ enabled: false, env: {} });
|
||||
const server = createStaticServer({ root: tmpdir(), publicRoot: tmpdir(), sharesApi: disabled });
|
||||
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
|
||||
t.after(() => new Promise((resolvePromise) => server.close(resolvePromise)));
|
||||
const disabledBase = `http://127.0.0.1:${server.address().port}`;
|
||||
assert.equal((await (await fetch(`${disabledBase}/api/shares/config`)).json()).enabled, false);
|
||||
const refused = await upload(disabledBase);
|
||||
assert.equal(refused.status, 503);
|
||||
assert.equal((await refused.json()).error.code, "SHARES_DISABLED");
|
||||
});
|
||||
|
||||
test("a reusable share can be read several times and revoked with its token only", async (t) => {
|
||||
const { base } = await setup(t);
|
||||
const body = payload(4096, 3);
|
||||
const share = await created(base, body);
|
||||
assert.match(share.id, /^[A-Za-z0-9_-]{22}$/);
|
||||
assert.equal(share.singleUse, false);
|
||||
|
||||
const meta = await (await fetch(`${base}/api/shares/${share.id}/meta`)).json();
|
||||
assert.deepEqual(meta, { size: body.length, expiresAt: share.expiresAt, singleUse: false });
|
||||
for (let index = 0; index < 2; index += 1) {
|
||||
const read = await download(base, share.id);
|
||||
assert.equal(read.status, 200);
|
||||
assert.equal(read.headers.get("cache-control"), "no-store");
|
||||
assert.equal(read.headers.get("x-share-expires-at"), String(share.expiresAt));
|
||||
assert.deepEqual(read.body, body);
|
||||
}
|
||||
|
||||
const wrong = await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": "nope" } });
|
||||
assert.equal(wrong.status, 403);
|
||||
const revoked = await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": share.deleteToken } });
|
||||
assert.equal(revoked.status, 204);
|
||||
assert.equal((await download(base, share.id)).status, 404);
|
||||
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 404);
|
||||
});
|
||||
|
||||
test("a single-use share is deleted once fully read, and meta does not consume it", async (t) => {
|
||||
const { base, dir } = await setup(t);
|
||||
const share = await created(base, payload(), { singleUse: true });
|
||||
assert.equal(share.singleUse, true);
|
||||
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 200);
|
||||
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 200);
|
||||
|
||||
const first = await download(base, share.id);
|
||||
assert.equal(first.status, 200);
|
||||
assert.equal(first.headers.get("x-share-single-use"), "1");
|
||||
const second = await download(base, share.id);
|
||||
assert.equal(second.status, 404);
|
||||
assert.equal(JSON.parse(second.body).error.code, "SHARE_NOT_FOUND");
|
||||
await waitFor(() => !existsSync(join(dir, `${share.id}.bin`)) && !existsSync(join(dir, `${share.id}.json`)));
|
||||
});
|
||||
|
||||
test("a single-use share stays available after an interrupted read and refuses a concurrent one", async (t) => {
|
||||
const { base, port } = await setup(t);
|
||||
const body = payload(16 * 1024 * 1024, 9);
|
||||
const share = await created(base, body, { singleUse: true });
|
||||
|
||||
// La première lecture reste ouverte sans être consommée : une seconde lecture simultanée est refusée.
|
||||
const pending = await new Promise((resolvePromise) => {
|
||||
const request = httpGet({ host: "127.0.0.1", port, path: `/api/shares/${share.id}` }, (response) => {
|
||||
response.pause();
|
||||
resolvePromise({ request, response });
|
||||
});
|
||||
});
|
||||
assert.equal(pending.response.statusCode, 200);
|
||||
assert.equal((await download(base, share.id)).status, 404);
|
||||
|
||||
pending.request.destroy();
|
||||
let read = null;
|
||||
for (let attempt = 0; attempt < 50 && read?.status !== 200; attempt += 1) {
|
||||
await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));
|
||||
read = await download(base, share.id);
|
||||
}
|
||||
assert.equal(read.status, 200);
|
||||
assert.equal(read.body.length, body.length);
|
||||
assert.equal((await download(base, share.id)).status, 404);
|
||||
});
|
||||
|
||||
test("uploads are validated before anything is stored", async (t) => {
|
||||
const { base, dir, port } = await setup(t);
|
||||
const missingHeader = await fetch(`${base}/api/shares`, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: payload() });
|
||||
assert.equal(missingHeader.status, 400);
|
||||
assert.equal((await missingHeader.json()).error.code, "SHARE_HEADER_REQUIRED");
|
||||
assert.equal((await upload(base, payload(), { headers: { "Content-Type": "application/json" } })).status, 415);
|
||||
|
||||
const badMagic = await upload(base, Buffer.alloc(256, 1));
|
||||
assert.equal(badMagic.status, 400);
|
||||
assert.equal((await badMagic.json()).error.code, "SHARE_FORMAT");
|
||||
assert.equal((await upload(base, payload(8))).status, 400);
|
||||
|
||||
const tooLarge = rawUpload(port, { declared: SHARE_MAX_BYTES + 1 });
|
||||
assert.match(await tooLarge.response, / 413 /);
|
||||
|
||||
const aborted = rawUpload(port, { declared: 4096, sent: payload(1024) });
|
||||
await waitFor(() => partFiles(dir).length === 1);
|
||||
aborted.socket.destroy();
|
||||
await waitFor(() => partFiles(dir).length === 0);
|
||||
assert.deepEqual(readdirSync(dir), []);
|
||||
|
||||
assert.equal((await fetch(`${base}/api/shares/short`)).status, 400);
|
||||
assert.equal((await fetch(`${base}/api/shares/..%2F..%2Fetc%2Fpasswd`)).status, 400);
|
||||
assert.equal((await fetch(`${base}/api/shares/${"a".repeat(22)}`)).status, 404);
|
||||
assert.equal((await fetch(`${base}/api/shares`)).status, 405);
|
||||
});
|
||||
|
||||
test("shares expire after 24 hours and are purged from disk", async (t) => {
|
||||
const { base, dir, clock, sharesApi } = await setup(t);
|
||||
const share = await created(base, payload());
|
||||
clock.value += SHARE_TTL_MS - 1;
|
||||
assert.equal((await download(base, share.id)).status, 200);
|
||||
clock.value += 1;
|
||||
assert.equal((await download(base, share.id)).status, 404);
|
||||
assert.equal((await fetch(`${base}/api/shares/${share.id}`, { method: "DELETE", headers: { "X-Share-Delete-Token": share.deleteToken } })).status, 404);
|
||||
|
||||
const other = await created(base, payload());
|
||||
clock.value += SHARE_TTL_MS;
|
||||
await sharesApi.store.purge();
|
||||
assert.equal(existsSync(join(dir, `${other.id}.bin`)), false);
|
||||
assert.equal(sharesApi.store.totalBytes, 0);
|
||||
});
|
||||
|
||||
test("a restart keeps valid shares and drops expired, partial and orphan files", async (t) => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "sokko-shares-restart-"));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
const first = await setup(t, { dir });
|
||||
const kept = await created(first.base, payload(300));
|
||||
await writeFile(join(dir, `${"b".repeat(22)}.part`), "partial");
|
||||
await writeFile(join(dir, `${"c".repeat(22)}.bin`), "orphan");
|
||||
|
||||
const reloaded = createSharesApiHandler({ enabled: true, dir, env: {}, now: () => first.clock.value });
|
||||
t.after(reloaded.close);
|
||||
assert.equal(reloaded.store.count, 1);
|
||||
assert.equal(reloaded.store.totalBytes, 300);
|
||||
assert.deepEqual(readdirSync(dir).sort(), [`${kept.id}.bin`, `${kept.id}.json`].sort());
|
||||
|
||||
const later = createSharesApiHandler({ enabled: true, dir, env: {}, now: () => first.clock.value + SHARE_TTL_MS });
|
||||
t.after(later.close);
|
||||
assert.equal(later.store.count, 0);
|
||||
assert.deepEqual(readdirSync(dir), []);
|
||||
});
|
||||
|
||||
test("total storage, share count and free disk space are capped", async (t) => {
|
||||
const { base } = await setup(t, { limits: { maxTotalBytes: 600 } });
|
||||
await created(base, payload(400));
|
||||
const full = await upload(base, payload(400));
|
||||
assert.equal(full.status, 507);
|
||||
assert.equal((await full.json()).error.code, "SHARE_STORAGE_FULL");
|
||||
await created(base, payload(200));
|
||||
|
||||
const count = await setup(t, { limits: { maxActiveShares: 1 } });
|
||||
await created(count.base, payload());
|
||||
assert.equal((await upload(count.base, payload())).status, 507);
|
||||
|
||||
const disk = await setup(t, { statfs: async () => ({ bavail: 1000, bsize: 1024 }), limits: { minFreeBytes: 1000 * 1024 - 100 } });
|
||||
assert.equal((await upload(disk.base, payload(50))).status, 201);
|
||||
assert.equal((await upload(disk.base, payload(200))).status, 507);
|
||||
});
|
||||
|
||||
test("the daily volume is capped for the whole service and per connection", async (t) => {
|
||||
const global = await setup(t, { limits: { dailyBytes: 500 } });
|
||||
await created(global.base, payload(300));
|
||||
const refused = await upload(global.base, payload(300));
|
||||
assert.equal(refused.status, 429);
|
||||
assert.equal((await refused.json()).error.code, "SHARE_DAILY_QUOTA");
|
||||
global.clock.value += 24 * 60 * 60 * 1000 + 60 * 60 * 1000;
|
||||
assert.equal((await upload(global.base, payload(300))).status, 201);
|
||||
|
||||
const perIp = await setup(t, { limits: { ipDailyUploads: 2 } });
|
||||
await created(perIp.base, payload());
|
||||
await created(perIp.base, payload());
|
||||
const third = await upload(perIp.base, payload());
|
||||
assert.equal(third.status, 429);
|
||||
assert.equal((await third.json()).error.code, "SHARE_IP_QUOTA");
|
||||
// Une autre connexion, derrière le proxy, garde son propre compteur.
|
||||
assert.equal((await upload(perIp.base, payload(), { headers: { "X-Forwarded-For": "203.0.113.9" } })).status, 201);
|
||||
|
||||
const bytes = await setup(t, { limits: { ipDailyBytes: 500 } });
|
||||
await created(bytes.base, payload(300));
|
||||
assert.equal((await upload(bytes.base, payload(300))).status, 429);
|
||||
|
||||
const minute = await setup(t, { limits: { ipUploadsPerMinute: 1 } });
|
||||
await created(minute.base, payload());
|
||||
assert.equal((await upload(minute.base, payload())).status, 429);
|
||||
});
|
||||
|
||||
test("concurrent uploads are capped and a stalled upload is cut off", async (t) => {
|
||||
const { base, dir, port } = await setup(t, { limits: { maxConcurrentUploads: 1, uploadIdleTimeoutMs: 200 } });
|
||||
const stalled = rawUpload(port, { declared: 4096, sent: payload(512) });
|
||||
await waitFor(() => partFiles(dir).length === 1);
|
||||
const busy = await upload(base, payload());
|
||||
assert.equal(busy.status, 503);
|
||||
assert.equal(busy.headers.get("retry-after"), "30");
|
||||
assert.match(await stalled.response, / 408 /);
|
||||
await waitFor(() => partFiles(dir).length === 0);
|
||||
assert.equal((await upload(base, payload())).status, 201);
|
||||
});
|
||||
|
||||
test("a reusable share stops answering after its maximum number of reads", async (t) => {
|
||||
const { base } = await setup(t, { limits: { maxReads: 2 } });
|
||||
const share = await created(base, payload());
|
||||
assert.equal((await download(base, share.id)).status, 200);
|
||||
assert.equal((await download(base, share.id)).status, 200);
|
||||
assert.equal((await download(base, share.id)).status, 404);
|
||||
assert.equal((await fetch(`${base}/api/shares/${share.id}/meta`)).status, 404);
|
||||
});
|
||||
|
||||
test("production requires an explicit directory, and an invalid configuration only disables sharing", () => {
|
||||
assert.throws(() => createSharesApiHandler({ enabled: true, env: { NODE_ENV: "production" } }), /SHARES_DIR/);
|
||||
assert.throws(() => createSharesApiHandler({ enabled: true, dir: tmpdir(), env: { SHARES_MAX_TOTAL_BYTES: "lots" } }), /SHARES_MAX_TOTAL_BYTES/);
|
||||
const originalError = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
const fallback = createSharesApi({ enabled: true, env: { NODE_ENV: "production" } });
|
||||
assert.equal(fallback.store, null);
|
||||
} finally {
|
||||
console.error = originalError;
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue