Compare commits

...

2 commits

Author SHA1 Message Date
bec9ea5b2f 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>
2026-11-11 16:26:05 +01:00
957bfdc86f Replace the reindeer and snowy owl cutouts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:24:31 +01:00
45 changed files with 2349 additions and 59 deletions

View file

@ -321,3 +321,11 @@
{"id":"int-c17c3702be7114f750b1f97592c4142c","kind":"field_change","created_at":"2026-11-09T12:23:33.595084433Z","actor":"Shinuwa","issue_id":"sokko-g-3ijw","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}}
{"id":"int-e910f5b4c041480fb8e708c515e62f6d","kind":"field_change","created_at":"2026-11-11T14:02:45.210027976Z","actor":"Shinuwa","issue_id":"sokko-g-0ku7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Associations orphelines écartées au chargement, à l'export et à l'import global ; le fichier .local/sokkog-global-2026-11-11.json s'importe (3 toolboxes, 24 outils)."}}
{"id":"int-f91a8b7bc318291bfa072ad6cff3b328","kind":"field_change","created_at":"2026-11-11T14:11:39.343142458Z","actor":"Shinuwa","issue_id":"sokko-g-ocss","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"mutateToolboxStorage retire dans la même transaction toute association vers une toolbox absente ; removeOrphanLinks nettoie la base au chargement ; linkToolboxToGame ignore une toolbox absente. Test e2e deux onglets : échoue sans la correction, passe avec."}}
{"id":"int-d28de3131c42a520f06d321263a669ec","kind":"field_change","created_at":"2026-11-11T14:50:18.862876421Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Service /api/shares, plafonds globaux et par IP, 12 tests Node verts"}}
{"id":"int-6378b76c98c8bdcfa2f74fdea06bba39","kind":"field_change","created_at":"2026-11-11T14:51:24.312207352Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"shareCrypto + 4 tests"}}
{"id":"int-004298093967fbc8b05fc840955c975c","kind":"field_change","created_at":"2026-11-11T14:52:24.919381848Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"shareQuota + 6 tests"}}
{"id":"int-6f72aff4d5cec2ce43f5e59904b90bd1","kind":"field_change","created_at":"2026-11-11T14:56:46.772990114Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.4","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Modale d'envoi, actions, bouton Envoyer (carte + panneau), icône send"}}
{"id":"int-7bd1e13eb668bac356b7db8ff45ece93","kind":"field_change","created_at":"2026-11-11T15:03:48.107906893Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.5","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Page /receive/<id>, aperçu, usage unique, erreurs"}}
{"id":"int-9661c05d4303c503386906be9e7bfe2e","kind":"field_change","created_at":"2026-11-11T15:05:17.423843268Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.6","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Textes, confidentialité, README, STORAGE_SCHEMA, DELIVERY, SERVER, FEATURE_CHECKLIST, TEST_STRATEGY, .env.example"}}
{"id":"int-b0f7c0738ccd020c2119804114729180","kind":"field_change","created_at":"2026-11-11T15:16:40.162652313Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf.7","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"E2E dev (4 parcours) et production (CSP) verts ; npm run check:full vert"}}
{"id":"int-86fb8c17d94b19eb047cad4b1ba58585","kind":"field_change","created_at":"2026-11-11T15:16:56.520484817Z","actor":"Shinuwa","issue_id":"sokko-g-dfyf","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Envoi de toolbox par lien chiffré livré en local, validé par check:full ; mise en production à faire par l'utilisateur"}}

View file

@ -20,3 +20,17 @@ DISCORD_REDIRECT_URI=https://sokkog.example.com/api/cards/auth/callback
CARDS_ADMIN_DISCORD_IDS=
# Connexion factice qui accorde les droits administrateur : réservée au développement, ignorée en production.
CARDS_DEV_AUTH=false
# Envoi de toolbox par lien chiffré. Désactivé par défaut en production ; le serveur de développement l'active sauf avec la valeur false.
SHARES_ENABLED=false
# Dossier des envois chiffrés, hors de la copie du site ; obligatoire en production quand l'envoi est activé. Il n'est pas sauvegardé.
SHARES_DIR=/data/webapps/private/sokko-g/shares
# Plafonds facultatifs, en octets ou en nombre. Valeurs par défaut : 2 Gio stockés, 500 envois actifs, 5 Gio d'espace libre minimal,
# 5 Gio reçus par 24 h, 3 envois simultanés, et par connexion 10 envois et 300 Mio par 24 h.
SHARES_MAX_TOTAL_BYTES=
SHARES_MAX_ACTIVE=
SHARES_MIN_FREE_BYTES=
SHARES_DAILY_BYTES=
SHARES_MAX_CONCURRENT_UPLOADS=
SHARES_IP_DAILY_UPLOADS=
SHARES_IP_DAILY_BYTES=

View file

@ -4,8 +4,10 @@ Webapp React pour préparer et accompagner des sessions gaming sur second écran
Sokko G propose des toolboxes modulaires stockées uniquement dans le navigateur,
des guides maintenus dans le dépôt et Sokko TCG, un mini-jeu de collection
avec compte Discord. Seul Sokko TCG stocke côté serveur les données requises
avec compte Discord. Seul Sokko TCG garde durablement des données côté serveur,
pour l'identité, les possessions et les échanges ; les toolboxes restent locales.
L'envoi d'une toolbox par lien n'en confie au serveur qu'une copie chiffrée,
illisible pour lui, pendant 24 heures au plus.
L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran. Les mises en page sont validées à partir de 768 px ; le projet ne prévoit pas d'interface ni de navigation dédiées au téléphone.
@ -15,6 +17,7 @@ L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran.
- 17 types d’outils regroupés dans la Librairie : notes et suivi, références, calcul et données, temps et routines, builds et commandes. Le [registre des outils](website/src/features/toolboxes/toolboxModuleRegistry.js) est l’inventaire technique de référence.
- Copie d’un exemple de la Librairie vers une toolbox, avec remappage de ses dépendances.
- Import/export JSON v2 d’une toolbox ou de toutes les toolboxes, validé avant toute écriture.
- Envoi d’une toolbox par lien chiffré dans le navigateur : le serveur garde 24 h au plus une copie qu’il ne peut pas lire, à usage unique par défaut, et le destinataire l’importe comme un fichier. Limites par navigateur (2 envois par 24 h, 2 liens actifs, 100 Mio par jour) et plafonds globaux côté serveur.
- Sauvegarde automatique facultative vers un dossier local, avec export manuel toujours disponible.
- Association locale entre une page jeu et une toolbox.
- Bascule Guide / Toolbox sous 1440 px et panneau latéral redimensionnable à partir de 1440 px sur les pages jeux.
@ -67,6 +70,12 @@ Discord, SQLite, administration, contact de confidentialité et origine publique
[`docs/DELIVERY.md`](docs/DELIVERY.md), et l'organisation du serveur dans
[`docs/SERVER.md`](docs/SERVER.md).
L'envoi de toolbox par lien reste désactivé en production tant que `SHARES_ENABLED`
ne vaut pas `true` ; il demande alors `SHARES_DIR`. Le serveur de développement
l'active par défaut dans `.local/shares`. Les plafonds facultatifs sont décrits dans
`.env.example`, l'activation dans [`docs/DELIVERY.md`](docs/DELIVERY.md) et le
format dans [`docs/STORAGE_SCHEMA.md`](docs/STORAGE_SCHEMA.md).
Le parcours joueur est accessible sur `/#/cards`. Les comptes autorisés disposent
d'un tableau de bord séparé sur `/#/cards/admin`.

View file

@ -313,14 +313,54 @@ le rejouerait sinon sur le fichier restauré. Le test Node restaure une vraie sa
exemplaires ; une restauration d'exploitation doit aussi être répétée sur un
environnement non public avant l'activation.
## Activation de l'envoi de toolbox
L'envoi par lien chiffré est désactivé par défaut et indépendant de Sokko TCG.
Ses variables vont dans le même fichier d'environnement du service,
`/etc/sokko-g/cards.env` (voir la section précédente pour vérifier que l'unité le
charge) :
- `SHARES_ENABLED=true` ;
- `SHARES_DIR=/data/webapps/private/sokko-g/shares`, créé pour le compte du
service : `install -d -m 0700 /data/webapps/private/sokko-g/shares`. Sans cette
variable en production, l'envoi reste désactivé et le journal l'indique au
démarrage ;
- facultativement, les plafonds `SHARES_MAX_TOTAL_BYTES`, `SHARES_MAX_ACTIVE`,
`SHARES_MIN_FREE_BYTES`, `SHARES_DAILY_BYTES`, `SHARES_MAX_CONCURRENT_UPLOADS`,
`SHARES_IP_DAILY_UPLOADS` et `SHARES_IP_DAILY_BYTES`, décrits dans
`.env.example`. Les valeurs par défaut gardent au plus 2 Gio d'envois, laissent
toujours 5 Gio libres sur le disque et refusent plus de 5 Gio reçus par 24 h.
Ce dossier ne contient que des copies chiffrées, supprimées après 24 h : il n'est
pas inclus dans les sauvegardes et ne doit pas l'être. Caddy n'impose aucune
limite de taille de corps par défaut ; si une directive `request_body` est ajoutée
au `Caddyfile`, elle doit accepter au moins 50 Mio pour `/api/shares`.
Pour couper l'envoi en urgence : `SHARES_ENABLED=false`, puis
`systemctl restart sokko-g`. Le bouton « Envoyer » disparaît, les liens existants
répondent « service indisponible » et leurs fichiers restent jusqu'à leur purge,
qu'il est possible d'anticiper en vidant le dossier. Chaque envoi refusé par un
plafond est journalisé (`journalctl -u sokko-g | grep "Toolbox share refused"`),
sans adresse IP ni contenu.
Après activation, vérifier depuis l'origine publique :
```bash
curl -s https://sokkog.shinuwa.fr/api/shares/config
```
La réponse doit contenir `"enabled":true`. Envoyer ensuite une toolbox depuis un
navigateur et l'ouvrir dans une fenêtre privée.
## Serveur Node et fichiers statiques
`npm run build` produit l'application dans `website/dist`. `npm start` sert ce
répertoire avec `server.mjs` et, lorsque la fonctionnalité est activée, expose
l'API `/api/cards`. Les tests E2E de production servent le build avec ce même
serveur, Sokko TCG désactivé : ils couvrent le comportement du build dans le
navigateur sous la CSP de `server.mjs`, mais pas l'API `/api/cards`, que
`npm run test:e2e:cards` valide.
répertoire avec `server.mjs` et, lorsque les fonctionnalités sont activées, expose
les API `/api/cards` et `/api/shares`. Les tests E2E de production servent le build
avec ce même serveur, Sokko TCG désactivé et l'envoi de toolbox activé dans un
dossier temporaire : ils couvrent le comportement du build dans le navigateur sous
la CSP de `server.mjs`, dont un envoi et une réception complets, mais pas l'API
`/api/cards`, que `npm run test:e2e:cards` valide.
La politique de cache du serveur est la suivante :

View file

@ -68,6 +68,7 @@ Checklist à suivre lors de l'ajout ou de la modification d'un outil, d'une page
- Vérifier le quota de stockage si l'outil manipule des données lourdes.
- Pour la sauvegarde locale, vérifier la feature detection, les permissions sans popup au démarrage, le nommage en date locale, la déduplication quotidienne, le remplacement manuel, la rétention de dix fichiers et la conservation des fichiers étrangers.
- Vérifier qu'un échec de sauvegarde fichier conserve la date de la dernière réussite et laisse l'export manuel accessible. Une écriture toolbox confirmée pendant la création du fichier doit rester marquée pour la sauvegarde suivante.
- Pour l'envoi par lien, vérifier que le lien ne contient la clé qu'après le second `#`, que l'usage unique est coché par défaut, qu'une toolbox déjà envoyée réaffiche son lien et que la révocation libère sa place sans rendre le quota du jour. Côté destinataire, vérifier dans un profil isolé l'aperçu d'un lien réutilisable, la réception directe d'un lien à usage unique puis son refus à la seconde ouverture, et les messages de lien révoqué, de clé absente ou altérée. Les parcours `e2e/toolbox-share.spec.js` et `e2e/production/toolbox-share.spec.js` couvrent ces cas ; les plafonds du serveur et l'expiration sont couverts par `tests/toolbox-shares-api.test.mjs`.
- Pour les imports JSON individuels et globaux, vérifier qu'ils ajoutent des copies sans supprimer la collection. Toute réattribution d'une association de jeu existante doit être annoncée et confirmée avant la première écriture ; l'annulation ne modifie rien.
## Page Jeu

View file

@ -47,6 +47,7 @@ Internet -> Caddy (VM network) -> 192.168.0.100:3102 -> Node server.mjs (VM weba
| `/data/webapps/sites/sokkog` | Ancienne version, à ignorer et à supprimer |
| `/data/webapps/apps` | Applications utilisées ponctuellement (`abondance-bot`, `codex-reset-alerts`, `gameservers-control`, `ntfy`, `palico-bot`, `projects`) |
| `/data/webapps/private/sokko-g` | Base Sokko TCG, à créer à l'activation |
| `/data/webapps/private/sokko-g/shares` | Envois de toolbox chiffrés, 24 h au plus, non sauvegardés ; à créer à l'activation de l'envoi |
| `/data/backups/sokko-g` | Sauvegardes quotidiennes de cette base, à créer à l'activation |
| `/etc/sokko-g/cards.env` | Secrets Sokko TCG, à créer à l'activation |
| `/var/lib/sokko-g` | Commits livrés (`current-commit`, `previous-commit`) ; appartient à `root` |
@ -75,6 +76,8 @@ Forgejo n'a pas été relevé.
## Sauvegardes
- **Envois de toolbox :** volontairement exclus des sauvegardes ; ce sont des copies
chiffrées supprimées au bout de 24 heures.
- **Base Sokko TCG :** une copie par nuit, 14 conservées, sur le disque `/data`, dès
l'installation du minuteur (voir `DELIVERY.md`).
- **VM `webapps` :** copies manuelles occasionnelles, récupérées puis conservées sur un

View file

@ -207,7 +207,8 @@ ignorées au chargement sans être effacées.
Le cache Cards n'appartient pas à la base `sokkog`, n'est inclus dans aucun
export ou import de toolbox et n'est jamais converti en inventaire de
production. Les toolboxes restent entièrement locales et leur contrat ci-dessous
ne change pas.
ne change pas. Un envoi par lien en transmet seulement une copie chiffrée (voir
« Envoi de toolbox par lien »).
## Préférences locales hors toolbox
@ -1570,6 +1571,69 @@ Formats :
- `imageAnnotation` : image base64, lignes `@marker: x,y,label` et `@drawings: {...}` pour les dessins permanents.
- `timer` : metas globales, lignes `lap | ...` et `countdown | ...`; les échéances temporelles sont recalculées à l'import.
## Envoi de toolbox par lien
Un envoi transporte exactement l'export individuel v2 décrit ci-dessus
(`createToolboxExportPayload`, sur le même snapshot transactionnel). Le
destinataire le valide avec `validateToolboxImportPayload(payload, "single")` et
l'importe par le même chemin que l'import de fichier : nouvelle toolbox, nouveaux
identifiants, aucune association de jeu. Aucun champ n'est ajouté au format public.
### Format chiffré `SKS1`
`website/src/features/toolboxes/sharing/shareCrypto.js` :
```text
"SKS1" (4 octets) | IV (12 octets) | AES-GCM 256 ( gzip ( JSON de l'export v2 ) )
```
- La clé, aléatoire pour chaque envoi, est encodée en base64url (43 caractères) et
placée après le second `#` du lien : `https://<origine>/#/receive/<id>#<clé>`.
Rien après le premier `#` n'est transmis au serveur.
- L'en-tête `SKS1` est authentifié (`additionalData`) : un contenu modifié, une clé
fausse ou tronquée échouent au déchiffrement.
- La décompression est plafonnée à 256 Mio pour qu'un envoi ne puisse pas saturer
la mémoire du destinataire.
### Données du navigateur expéditeur
Deux entrées `localStorage`, jamais exportées ni sauvegardées :
- `sokkog:sent-shares` : liens encore valides, `{ id, toolboxId, toolboxName,
expiresAt, deleteToken, singleUse, link }`. Le lien complet, clé comprise, sert à
réafficher le lien d'une toolbox déjà envoyée ; `deleteToken` permet de le
révoquer. Les entrées expirées sont supprimées à la lecture ; un lien que le
serveur ne connaît plus (`/meta` en 404 : utilisé, révoqué) est retiré à
l'ouverture de la fenêtre d'envoi.
- `sokkog:share-log` : `{ at, bytes }` pour chaque envoi des dernières 24 h,
révocations comprises.
Règles appliquées avant tout chiffrement (`shareQuota.js`) : une toolbox ayant un
lien valide réaffiche ce lien, 2 liens actifs au plus, 2 envois et 100 Mio par
24 h glissantes, 50 Mio par envoi chiffré. Un stockage indisponible ou corrompu
n'empêche pas l'envoi : ces limites sont une première barrière, les plafonds du
serveur restent la protection réelle.
### Stockage côté serveur
`services/shares/` écrit dans `SHARES_DIR` (`.local/shares` en développement) :
- `<id>.bin` : le contenu `SKS1` reçu, inchangé ; `<id>.json` : `{ createdAt,
expiresAt, size, singleUse, reads, deleteTokenHash }`. `id` vaut 16 octets
aléatoires en base64url ; seul le SHA-256 du jeton de révocation est conservé.
- Un envoi est écrit dans `<id>.part`, renommé une fois complet, puis rendu lisible
par l'écriture de ses métadonnées. Au démarrage, les fichiers incomplets,
orphelins, illisibles ou expirés sont supprimés.
- Durée de vie : 24 h. La purge passe au démarrage puis toutes les 10 minutes ;
l'expiration est aussi vérifiée à chaque lecture.
- Usage unique : l'envoi est réservé dès le début d'une lecture (une seconde
lecture simultanée reçoit 404) et supprimé quand la réponse a été entièrement
transmise. Une lecture interrompue lève la réservation. `/meta` ne consomme
jamais un lien. Un lien réutilisable répond au plus 50 fois.
- Aucune adresse IP n'est écrite sur le disque. Les compteurs par connexion
utilisent une empreinte HMAC dont la clé change à chaque démarrage, et restent
en mémoire.
## A maintenir à chaque update
Quand un outil change de structure :

View file

@ -21,6 +21,7 @@ not bugs, missing scenarios or a percentage of work remaining.
| HTTP cache policy of the delivered Node server | `tests/server-cache.test.mjs`; production E2E remains responsible for stale bundle recovery |
| Node server resilience: hostile requests, invalid Cards configuration, clean shutdown | `tests/server-robustness.test.mjs` |
| Sokko TCG ownership, recharge, idempotence, transfers, campaign codes, account deletion and backup/restore | `tests/nebula-cards.test.mjs`, `tests/nebula-cards-api.test.mjs`, then `e2e/nebula-cards.spec.js` against the delivered Node API and a temporary SQLite database |
| Toolbox sharing by encrypted link: server caps, single use, expiry, browser quotas, encryption, send and receive under the production CSP | `tests/toolbox-shares-api.test.mjs` (real HTTP server, temporary directory), `tests/toolbox-share-crypto.test.mjs`, `tests/toolbox-share-quota.test.mjs`, then `e2e/toolbox-share.spec.js` with isolated recipient contexts and `e2e/production/toolbox-share.spec.js` |
| Shared reorder policy and module order | `e2e/grouped-reorder.spec.js`, `module-order.spec.js` |
| Toolbox creation, import/export, text exchange | `e2e/toolbox.spec.js`, `text-exchange.spec.js`; Node toolbox module tests |
| Links: creation, copy, category removal preserving links, deletion and reload | `e2e/basic-tools.spec.js` |

View file

@ -0,0 +1,38 @@
// Rôle : vérifie qu'un envoi de toolbox chiffré fonctionne de bout en bout sous la CSP du serveur Node.
import { expect, test } from "@playwright/test";
async function watchCsp(page, violations) {
await page.exposeFunction("reportCspViolation", (violation) => violations.push(violation));
await page.addInitScript(() => {
globalThis.document.addEventListener("securitypolicyviolation", (event) => globalThis.reportCspViolation(`${event.violatedDirective} ${event.blockedURI}`));
});
}
test("a toolbox is sent and received under the production CSP", async ({ page, browser }) => {
const violations = [];
await watchCsp(page, violations);
await page.goto("/#/toolboxes");
await page.getByRole("button", { name: "Nouvelle toolbox" }).click();
const creation = page.getByRole("dialog", { name: "Nouvelle toolbox" });
await creation.getByLabel("Nom").fill("Envoi CSP");
await creation.getByRole("button", { name: "Créer", exact: true }).click();
await page.goto("/#/toolboxes");
await page.getByRole("button", { name: "Envoyer Envoi CSP", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Envoyer « Envoi CSP »" });
await dialog.getByRole("button", { name: "Créer le lien" }).click();
const link = await dialog.getByLabel("Lien à transmettre").inputValue();
expect(link).toMatch(/\/#\/receive\/[A-Za-z0-9_-]{22}#[A-Za-z0-9_-]{43}$/);
const context = await browser.newContext();
const recipient = await context.newPage();
const recipientViolations = [];
await watchCsp(recipient, recipientViolations);
await recipient.goto(link);
await recipient.getByRole("button", { name: "Recevoir et importer" }).click();
await expect(recipient.getByRole("heading", { name: "Envoi CSP", exact: true })).toBeVisible();
await context.close();
expect(violations).toEqual([]);
expect(recipientViolations).toEqual([]);
});

131
e2e/toolbox-share.spec.js Normal file
View file

@ -0,0 +1,131 @@
// Rôle : vérifie l'envoi d'une toolbox par lien chiffré, sa réception dans un navigateur isolé et les limites d'envoi.
import { expect, test } from "@playwright/test";
import { Buffer } from "node:buffer";
import { readFile } from "node:fs/promises";
import { fileURLToPath, URL } from "node:url";
const fixture = JSON.parse(await readFile(new URL("./fixtures/toolbox-export.json", import.meta.url), "utf8"));
const coverPath = fileURLToPath(new URL("../website/public/static/img/toolbox-icons/sword.webp", import.meta.url));
const cover = `data:image/webp;base64,${(await readFile(coverPath)).toString("base64")}`;
async function importToolbox(page, name) {
await page.goto("/#/toolboxes");
await page.getByText("Importer une toolbox").locator("input[type='file']").setInputFiles({
name: "share.json",
mimeType: "application/json",
buffer: Buffer.from(JSON.stringify({ ...fixture, toolbox: { ...fixture.toolbox, name, customCover: cover } }))
});
await expect(page.getByRole("link", { name: `Ouvrir ${name}` }).first()).toBeVisible();
}
function shareDialog(page, name) {
return page.getByRole("dialog", { name: `Envoyer « ${name} »` });
}
async function createShare(page, name, { singleUse = true } = {}) {
await page.getByRole("button", { name: `Envoyer ${name}`, exact: true }).click();
const dialog = shareDialog(page, name);
const option = dialog.getByRole("checkbox", { name: /Supprimer après la première utilisation/ });
await expect(option).toBeChecked();
if (!singleUse) await option.uncheck();
await dialog.getByRole("button", { name: "Créer le lien" }).click();
const link = dialog.getByLabel("Lien à transmettre");
await expect(link).toHaveValue(/\/#\/receive\/[A-Za-z0-9_-]{22}#[A-Za-z0-9_-]{43}$/);
return { dialog, link: await link.inputValue() };
}
// Chaque destinataire a son propre contexte : ni stockage local, ni quotas, ni toolboxes partagés avec l'expéditeur.
async function openAsRecipient(browser, link) {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(link);
return { context, page };
}
async function expectImported(page, name) {
await expect(page).toHaveURL(/#\/toolbox\/[^/]+$/);
await expect(page.getByRole("heading", { name, exact: true })).toBeVisible();
const notepad = page.locator("[data-module-type='notepad']");
await expect(notepad.getByText("Imported fixture note")).toBeVisible();
}
test("a single-use link imports the toolbox once in another browser", async ({ page, browser }) => {
await importToolbox(page, "Envoi unique");
const { dialog, link } = await createShare(page, "Envoi unique");
await expect(dialog.getByText("Il ne fonctionne qu’une fois.")).toBeVisible();
const first = await openAsRecipient(browser, link);
await expect(first.page.getByText("Ce lien ne fonctionne qu’une fois")).toBeVisible();
await first.page.getByRole("button", { name: "Recevoir et importer" }).click();
await expectImported(first.page, "Envoi unique");
await first.page.goto("/#/toolboxes");
await expect(first.page.getByRole("link", { name: "Ouvrir Envoi unique" }).first().locator("img")).toHaveAttribute("src", /^data:image\/webp;base64,/);
await first.context.close();
const second = await openAsRecipient(browser, link);
await expect(second.page.getByRole("alert")).toContainText("a déjà été utilisé");
await second.context.close();
// Le lien consommé libère sa place : la toolbox peut être renvoyée.
await dialog.getByRole("button", { name: "Fermer" }).last().click();
await page.getByRole("button", { name: "Envoyer Envoi unique", exact: true }).click();
await expect(shareDialog(page, "Envoi unique").getByRole("button", { name: "Créer le lien" })).toBeVisible();
});
test("a reusable link imports twice, is shown again instead of a new one, and can be revoked", async ({ page, browser }) => {
await importToolbox(page, "Envoi partagé");
const { dialog, link } = await createShare(page, "Envoi partagé", { singleUse: false });
await expect(dialog.getByText("Il peut être utilisé plusieurs fois.")).toBeVisible();
for (let index = 0; index < 2; index += 1) {
const recipient = await openAsRecipient(browser, link);
await expect(recipient.page.getByRole("heading", { name: "Envoi partagé" })).toBeVisible();
await expect(recipient.page.getByText("Bloc Note")).toBeVisible();
await recipient.page.getByRole("button", { name: "Importer dans mes toolboxes" }).click();
await expectImported(recipient.page, "Envoi partagé");
await recipient.context.close();
}
await dialog.getByRole("button", { name: "Fermer" }).last().click();
await page.getByRole("button", { name: "Envoyer Envoi partagé", exact: true }).click();
const reopened = shareDialog(page, "Envoi partagé");
await expect(reopened.getByText("Cette toolbox a déjà un lien valide.")).toBeVisible();
await expect(reopened.getByLabel("Lien à transmettre")).toHaveValue(link);
await reopened.getByRole("button", { name: "Révoquer" }).click();
await expect(reopened.getByRole("button", { name: "Créer le lien" })).toBeVisible();
const late = await openAsRecipient(browser, link);
await expect(late.page.getByRole("alert")).toContainText("a été révoqué");
await late.context.close();
});
test("a missing or altered key is refused before anything is imported", async ({ page, browser }) => {
await importToolbox(page, "Envoi altéré");
const { link } = await createShare(page, "Envoi altéré", { singleUse: false });
const [base, key] = [link.slice(0, link.lastIndexOf("#")), link.slice(link.lastIndexOf("#") + 1)];
const altered = `${base}#${key[0] === "A" ? "B" : "A"}${key.slice(1)}`;
const recipient = await openAsRecipient(browser, altered);
await expect(recipient.page.getByRole("alert")).toContainText("a été modifié");
await expect(recipient.page.getByRole("button", { name: "Importer dans mes toolboxes" })).toHaveCount(0);
await recipient.page.goto(base);
await expect(recipient.page.getByRole("alert")).toContainText("la clé de déchiffrement manque");
await recipient.context.close();
});
test("this browser allows two shares per day", async ({ page }) => {
await importToolbox(page, "Quota un");
await importToolbox(page, "Quota deux");
await importToolbox(page, "Quota trois");
const first = await createShare(page, "Quota un", { singleUse: false });
await first.dialog.getByRole("button", { name: "Révoquer" }).click();
await first.dialog.getByRole("button", { name: "Fermer" }).last().click();
const second = await createShare(page, "Quota deux", { singleUse: false });
await second.dialog.getByRole("button", { name: "Fermer" }).last().click();
await page.getByRole("button", { name: "Envoyer Quota trois", exact: true }).click();
const dialog = shareDialog(page, "Quota trois");
await expect(dialog.getByText(/limite de 2 envois par 24 heures/)).toBeVisible();
await expect(dialog.getByRole("button", { name: "Créer le lien" })).toHaveCount(0);
await expect(dialog.getByText("Quota deux")).toBeVisible();
});

View file

@ -15,7 +15,7 @@
"preview": "vite preview",
"lists:index": "node scripts/generate-list-indexes.mjs",
"lint": "eslint .",
"lint:cards": "eslint server.mjs vite.config.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx",
"lint:cards": "eslint server.mjs vite.config.js services/http.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx",
"check": "node --check server.mjs && node --check vite.config.js && npm run lint && npm run lists:index && npm test && npm run build",
"check:cards": "node --check server.mjs && node --check vite.config.js && npm run lint:cards && npm run test:cards && npm run test:e2e:cards",
"check:full": "npm run check && E2E_PORT=4181 npm run test:e2e && npm run test:e2e:production && npm run test:e2e:cards",

View file

@ -1,9 +1,12 @@
// Rôle : configure les diagnostics navigateur Playwright sans les intégrer au check de prod.
import { defineConfig, devices } from "@playwright/test";
import { tmpdir } from "node:os";
import { join } from "node:path";
const port = Number(process.env.E2E_PORT || 5173);
const baseURL = `http://localhost:${port}`;
const isolatedCardsEnvironment = process.env.E2E_PORT ? "CARDS_DB_PATH=:memory: CARDS_DEV_AUTH=true " : "";
// Un dossier d'envois propre à chaque port : une exécution isolée ne relit pas les envois du serveur de développement.
const isolatedCardsEnvironment = process.env.E2E_PORT ? `CARDS_DB_PATH=:memory: CARDS_DEV_AUTH=true SHARES_DIR=${join(tmpdir(), `sokko-e2e-shares-${port}`)} ` : "";
export default defineConfig({
testDir: "./e2e",

View file

@ -1,5 +1,7 @@
// Rôle : vérifie le build de production servi par server.mjs, sans réutiliser une instance Vite de développement.
import { defineConfig, devices } from "@playwright/test";
import { tmpdir } from "node:os";
import { join } from "node:path";
export default defineConfig({
testDir: "./e2e/production",
@ -14,7 +16,7 @@ export default defineConfig({
webServer: {
// Le serveur Node livré, et non Vite Preview : il porte la CSP et les en-têtes de production.
command: "node server.mjs",
env: { HOST: "127.0.0.1", PORT: "4173", CARDS_ENABLED: "false" },
env: { HOST: "127.0.0.1", PORT: "4173", CARDS_ENABLED: "false", SHARES_ENABLED: "true", SHARES_DIR: join(tmpdir(), "sokko-e2e-production-shares") },
url: "http://127.0.0.1:4173",
reuseExistingServer: false,
timeout: 120000

View file

@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
import { loadProjectEnv } from "./scripts/load-project-env.mjs";
import { createCardsApiHandler } from "./services/cards/api.js";
import { createSharesApiHandler } from "./services/shares/api.js";
import { createServer } from "node:http";
import { extname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@ -104,11 +105,12 @@ function securityHeaders(root) {
};
}
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) {
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null, sharesApi = null } = {}) {
const headers = securityHeaders(root);
async function handleRequest(req, res) {
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
if (sharesApi && await sharesApi(req, res)) return;
if (cardsApi && await cardsApi(req, res)) return;
const file = resolvePath(req.url || "/", root, publicRoot);
if (!file || !existsSync(file)) {
@ -150,6 +152,7 @@ export function createStaticServer({ root = defaultRoot, publicRoot = defaultPub
});
});
if (cardsApi?.close) server.once("close", cardsApi.close);
if (sharesApi?.close) server.once("close", sharesApi.close);
return server;
}
@ -163,13 +166,24 @@ export function createCardsApi(options = {}) {
}
}
export function startServer({ cardsApiOptions = {} } = {}) {
// Une configuration d'envoi invalide désactive seulement l'envoi de toolbox.
export function createSharesApi(options = {}) {
try {
return createSharesApiHandler({ projectRoot, ...options });
} catch (error) {
console.error("Toolbox sharing is disabled because its configuration is invalid:", error);
return createSharesApiHandler({ projectRoot, ...options, enabled: false });
}
}
export function startServer({ cardsApiOptions = {}, sharesApiOptions = {} } = {}) {
loadProjectEnv();
const port = Number(process.env.PORT || 5173);
// En production, limite l'écoute au réseau privé : seul le proxy doit pouvoir joindre le serveur.
const host = process.env.HOST || undefined;
const cardsApi = createCardsApi(cardsApiOptions);
const server = createStaticServer({ cardsApi });
const sharesApi = createSharesApi(sharesApiOptions);
const server = createStaticServer({ cardsApi, sharesApi });
server.on("error", (error) => {
if (error.code === "EADDRINUSE") {

View file

@ -4,28 +4,15 @@ import { join, resolve } from "node:path";
import { CardsDatabase } from "./database.js";
import { loadCardsCatalog, publicCatalog } from "./catalog.js";
import { CardsService, DEV_DISCORD_ID } from "./service.js";
import { bool, createRateLimiter, json } from "../http.js";
export { createRateLimiter };
const JSON_LIMIT = 64 * 1024;
const DISCORD_TIMEOUT_MS = 10_000;
const MAINTENANCE_INTERVAL_MS = 24 * 60 * 60 * 1000;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
function json(res, status, body) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff"
});
res.end(payload);
}
function redirect(res, location, cookies = []) {
const headers = { Location: location, "Cache-Control": "no-store" };
if (cookies.length) headers["Set-Cookie"] = cookies;
@ -106,25 +93,6 @@ function routeMatch(pathname, pattern) {
}
}
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0]}:${scope}`;
const minute = Math.floor(now() / 60_000);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
};
limiter.bucketCount = () => buckets.size;
return limiter;
}
export function createCardsApiHandler({
projectRoot = resolve("."),
env = process.env,

46
services/http.js Normal file
View file

@ -0,0 +1,46 @@
// Rôle : regroupe les petits outils HTTP partagés par les API du serveur Node.
export function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
export function json(res, status, body, headers = {}) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
...headers
});
res.end(payload);
}
export function httpError(status, code, message, extra = {}) {
return Object.assign(new Error(message), { status, code, ...extra });
}
// Caddy remplace X-Forwarded-For par l'adresse réelle du client (voir docs/SERVER.md).
export function clientAddress(req) {
return String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0].trim();
}
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${clientAddress(req)}:${scope}`;
const minute = Math.floor(now() / 60_000);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw httpError(429, "RATE_LIMITED", "Trop de tentatives. Réessayez dans quelques instants.");
};
limiter.bucketCount = () => buckets.size;
return limiter;
}

377
services/shares/api.js Normal file
View file

@ -0,0 +1,377 @@
// Rôle : expose l'API d'envoi de toolbox chiffrée et applique les plafonds qui protègent le serveur.
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { rm, statfs as fsStatfs } from "node:fs/promises";
import { join, resolve } from "node:path";
import { bool, clientAddress, createRateLimiter, httpError, json } from "../http.js";
import { SHARE_ID_PATTERN, ShareStore } from "./store.js";
export const SHARE_TTL_MS = 24 * 60 * 60 * 1000;
export const SHARE_MAX_BYTES = 50 * 1024 * 1024;
// En-tête "SKS1", IV de 12 octets et étiquette AES-GCM de 16 octets : un envoi plus petit ne peut pas être valide.
export const SHARE_MIN_BYTES = 4 + 12 + 16;
const SHARE_MAGIC = "SKS1";
const DAY_MS = 24 * 60 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
const PURGE_INTERVAL_MS = 10 * 60 * 1000;
const GIB = 1024 * 1024 * 1024;
const MIB = 1024 * 1024;
export const DEFAULT_SHARE_LIMITS = Object.freeze({
maxTotalBytes: 2 * GIB,
maxActiveShares: 500,
minFreeBytes: 5 * GIB,
dailyBytes: 5 * GIB,
maxConcurrentUploads: 3,
uploadTimeoutMs: 2 * 60 * 1000,
// Sans donnée reçue pendant ce délai, l'envoi est coupé : un client volontairement lent ne garde pas une place.
uploadIdleTimeoutMs: 15 * 1000,
maxReads: 50,
ipDailyUploads: 10,
ipDailyBytes: 300 * MIB,
ipUploadsPerMinute: 5,
readsPerMinute: 60
});
const ENV_LIMITS = {
maxTotalBytes: "SHARES_MAX_TOTAL_BYTES",
maxActiveShares: "SHARES_MAX_ACTIVE",
minFreeBytes: "SHARES_MIN_FREE_BYTES",
dailyBytes: "SHARES_DAILY_BYTES",
maxConcurrentUploads: "SHARES_MAX_CONCURRENT_UPLOADS",
ipDailyUploads: "SHARES_IP_DAILY_UPLOADS",
ipDailyBytes: "SHARES_IP_DAILY_BYTES"
};
function limitsFromEnv(env) {
const limits = {};
for (const [key, name] of Object.entries(ENV_LIMITS)) {
const raw = String(env[name] ?? "").trim();
if (!raw) continue;
const value = Number(raw);
if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${name} must be a non-negative integer.`);
limits[key] = value;
}
return limits;
}
function tokenHash(token) {
return createHash("sha256").update(String(token)).digest();
}
function sendEmpty(res, status, headers = {}) {
res.writeHead(status, { "Cache-Control": "no-store", ...headers });
res.end();
}
function shareNotFound() {
return httpError(404, "SHARE_NOT_FOUND", "Ce lien a expiré, a été révoqué ou a déjà été utilisé.");
}
// Volume reçu sur 24 h glissantes, compté par heure : la mémoire reste bornée quel que soit le nombre d'envois.
function createHourlyVolume() {
const buckets = new Map();
return {
total(now) {
const oldest = Math.floor((now - DAY_MS) / HOUR_MS);
let sum = 0;
for (const [hour, bytes] of buckets) {
if (hour <= oldest) buckets.delete(hour);
else sum += bytes;
}
return sum;
},
add(now, bytes) {
const hour = Math.floor(now / HOUR_MS);
buckets.set(hour, (buckets.get(hour) || 0) + bytes);
}
};
}
export function createSharesApiHandler({
projectRoot = resolve("."),
env = process.env,
enabled = bool(env.SHARES_ENABLED),
dir = env.SHARES_DIR || join(projectRoot, ".local", "shares"),
now = Date.now,
statfs = fsStatfs,
limits: overrides = {}
} = {}) {
const limits = { ...DEFAULT_SHARE_LIMITS, ...limitsFromEnv(env), ...overrides };
let store = null;
let purgeTimer = null;
if (enabled) {
// Sans dossier explicite, les envois iraient dans la copie du site, remplacée à chaque livraison.
if (env.NODE_ENV === "production" && !env.SHARES_DIR) throw new TypeError("SHARES_DIR is required when toolbox sharing is enabled in production.");
store = new ShareStore({ dir, now });
purgeTimer = setInterval(() => {
store.purge().catch((error) => console.error(error));
pruneIpUsage();
}, PURGE_INTERVAL_MS);
purgeTimer.unref();
}
const rateLimit = createRateLimiter(now);
// L'adresse IP n'est conservée qu'en mémoire, sous une empreinte dont la clé change à chaque démarrage.
const ipSecret = randomBytes(32);
const ipUsage = new Map();
const globalVolume = createHourlyVolume();
let uploadsInFlight = 0;
let reservedBytes = 0;
const ipKey = (req) => createHmac("sha256", ipSecret).update(clientAddress(req)).digest("base64url");
function recentIpUploads(key) {
const since = now() - DAY_MS;
const entries = (ipUsage.get(key) || []).filter((entry) => entry.at > since);
if (entries.length) ipUsage.set(key, entries);
else ipUsage.delete(key);
return entries;
}
function pruneIpUsage() {
for (const key of [...ipUsage.keys()]) recentIpUploads(key);
}
function refuse(status, code, message, extra = {}) {
console.warn(`Toolbox share refused: ${code}`);
return httpError(status, code, message, extra);
}
async function freeBytes() {
const stats = await statfs(store.dir);
return Number(stats.bavail) * Number(stats.bsize);
}
// Tous les refus possibles sont décidés avant de lire le corps de la requête.
async function checkCapacity(req, size) {
const key = ipKey(req);
const ipEntries = recentIpUploads(key);
if (ipEntries.length >= limits.ipDailyUploads || ipEntries.reduce((sum, entry) => sum + entry.bytes, 0) + size > limits.ipDailyBytes) {
throw refuse(429, "SHARE_IP_QUOTA", "Trop d'envois depuis cette connexion aujourd'hui. Réessayez demain.");
}
if (globalVolume.total(now()) + reservedBytes + size > limits.dailyBytes) {
throw refuse(429, "SHARE_DAILY_QUOTA", "Le service d'envoi a atteint sa limite du jour. Réessayez plus tard.");
}
if (uploadsInFlight >= limits.maxConcurrentUploads) {
throw refuse(503, "SHARE_BUSY", "Le service d'envoi est occupé. Réessayez dans quelques instants.", { headers: { "Retry-After": "30" } });
}
if (store.count + uploadsInFlight >= limits.maxActiveShares || store.totalBytes + reservedBytes + size > limits.maxTotalBytes) {
throw refuse(507, "SHARE_STORAGE_FULL", "Le service d'envoi est plein. Réessayez plus tard.");
}
if (await freeBytes() - reservedBytes - size < limits.minFreeBytes) {
throw refuse(507, "SHARE_STORAGE_FULL", "Le service d'envoi est plein. Réessayez plus tard.");
}
return key;
}
function receiveBody(req, file, size) {
return new Promise((resolvePromise, reject) => {
const out = createWriteStream(file, { flags: "wx", mode: 0o600 });
let received = 0;
let header = Buffer.alloc(0);
let ended = false;
let settled = false;
let idleTimer = null;
const finish = (error) => {
if (settled) return;
settled = true;
clearTimeout(totalTimer);
clearTimeout(idleTimer);
if (error) {
out.destroy();
reject(error);
} else {
resolvePromise();
}
};
const totalTimer = setTimeout(() => finish(httpError(408, "SHARE_TIMEOUT", "L'envoi a pris trop de temps.")), limits.uploadTimeoutMs);
const armIdle = () => {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => finish(httpError(408, "SHARE_TIMEOUT", "L'envoi a pris trop de temps.")), limits.uploadIdleTimeoutMs);
};
armIdle();
req.on("data", (chunk) => {
if (settled) return;
received += chunk.length;
if (received > size) return finish(httpError(413, "SHARE_TOO_LARGE", "Cette toolbox dépasse la taille maximale d'envoi."));
if (header.length < SHARE_MAGIC.length) {
header = Buffer.concat([header, chunk.subarray(0, SHARE_MAGIC.length - header.length)]);
if (header.length === SHARE_MAGIC.length && header.toString("latin1") !== SHARE_MAGIC) {
return finish(httpError(400, "SHARE_FORMAT", "Le contenu envoyé n'est pas une toolbox chiffrée."));
}
}
armIdle();
if (!out.write(chunk)) {
req.pause();
out.once("drain", () => req.resume());
}
});
req.on("end", () => {
ended = true;
if (settled) return;
if (received !== size) return finish(httpError(400, "SHARE_INCOMPLETE", "L'envoi est incomplet."));
out.end();
});
req.on("close", () => {
if (!ended) finish(httpError(400, "SHARE_ABORTED", "L'envoi a été interrompu."));
});
// Un client qui coupe la connexion n'est pas une erreur du serveur.
req.on("error", () => finish(httpError(400, "SHARE_ABORTED", "L'envoi a été interrompu.")));
out.on("error", finish);
out.on("finish", () => finish());
});
}
async function handleUpload(req, res) {
if (req.headers["x-sokkog-share"] !== "1") throw httpError(400, "SHARE_HEADER_REQUIRED", "Requête d'envoi invalide.");
const type = String(req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
if (type !== "application/octet-stream") throw httpError(415, "SHARE_CONTENT_TYPE", "Requête d'envoi invalide.");
rateLimit(req, "shares-upload", limits.ipUploadsPerMinute);
const declared = req.headers["content-length"];
if (declared == null || !/^\d+$/.test(String(declared))) throw httpError(411, "SHARE_LENGTH_REQUIRED", "Requête d'envoi invalide.");
const size = Number(declared);
if (size > SHARE_MAX_BYTES) throw httpError(413, "SHARE_TOO_LARGE", "Cette toolbox dépasse la taille maximale d'envoi.");
if (size < SHARE_MIN_BYTES) throw httpError(400, "SHARE_FORMAT", "Le contenu envoyé n'est pas une toolbox chiffrée.");
const key = await checkCapacity(req, size);
const id = randomBytes(16).toString("base64url");
const deleteToken = randomBytes(24).toString("base64url");
const part = store.partPath(id);
uploadsInFlight += 1;
reservedBytes += size;
try {
await receiveBody(req, part, size);
const createdAt = now();
const meta = { createdAt, expiresAt: createdAt + SHARE_TTL_MS, size, singleUse: req.headers["x-share-single-use"] === "1", reads: 0, deleteTokenHash: tokenHash(deleteToken).toString("hex") };
await store.commit(id, meta);
const entries = recentIpUploads(key);
entries.push({ at: createdAt, bytes: size });
ipUsage.set(key, entries);
globalVolume.add(createdAt, size);
json(res, 201, { id, deleteToken, expiresAt: meta.expiresAt, singleUse: meta.singleUse });
} catch (error) {
await rm(part, { force: true });
throw error;
} finally {
uploadsInFlight -= 1;
reservedBytes -= size;
}
}
function readableShare(id) {
if (!SHARE_ID_PATTERN.test(id)) throw httpError(400, "INVALID_SHARE_ID", "Lien d'envoi invalide.");
const meta = store.get(id);
if (!meta || (!meta.singleUse && meta.reads >= limits.maxReads)) throw shareNotFound();
return meta;
}
function handleDownload(id, res) {
const meta = readableShare(id);
if (meta.singleUse) store.claim(id);
else void store.recordRead(id).catch((error) => console.error(error));
const stream = createReadStream(store.binPath(id));
let finished = false;
res.on("finish", () => {
finished = true;
if (meta.singleUse) void store.remove(id).catch((error) => console.error(error));
});
// Une lecture interrompue laisse le lien utilisable : le destinataire peut réessayer.
res.on("close", () => {
if (!finished && meta.singleUse) store.release(id);
stream.destroy();
});
stream.once("open", () => {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": meta.size,
"Cache-Control": "no-store",
"X-Share-Expires-At": String(meta.expiresAt),
"X-Share-Single-Use": meta.singleUse ? "1" : "0"
});
stream.pipe(res);
});
stream.once("error", () => {
if (meta.singleUse) store.release(id);
if (res.headersSent) res.destroy();
else json(res, 404, { error: { code: "SHARE_NOT_FOUND", message: shareNotFound().message } });
});
}
async function handleDelete(id, req, res) {
if (!SHARE_ID_PATTERN.test(id)) throw httpError(400, "INVALID_SHARE_ID", "Lien d'envoi invalide.");
const meta = store.metas.get(id);
if (!meta || meta.expiresAt <= now()) throw shareNotFound();
const expected = Buffer.from(meta.deleteTokenHash, "hex");
if (!timingSafeEqual(tokenHash(req.headers["x-share-delete-token"] || ""), expected)) {
throw httpError(403, "SHARE_FORBIDDEN", "Ce lien ne peut pas être révoqué depuis ce navigateur.");
}
await store.remove(id);
sendEmpty(res, 204);
}
async function handler(req, res) {
let url;
try {
url = new URL(req.url || "/", "http://localhost");
} catch {
return false;
}
if (url.pathname !== "/api/shares" && !url.pathname.startsWith("/api/shares/")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/shares/config") {
rateLimit(req, "shares-config", limits.readsPerMinute * 2);
json(res, 200, { enabled, maxBytes: SHARE_MAX_BYTES, ttlMs: SHARE_TTL_MS });
return true;
}
if (!enabled) throw httpError(503, "SHARES_DISABLED", "L'envoi de toolbox est désactivé sur ce serveur.");
if (url.pathname === "/api/shares") {
if (req.method !== "POST") throw httpError(405, "METHOD_NOT_ALLOWED", "Méthode non prise en charge.");
await handleUpload(req, res);
return true;
}
const match = url.pathname.match(/^\/api\/shares\/([^/]+)(\/meta)?$/);
if (!match) throw httpError(404, "NOT_FOUND", "Route d'envoi introuvable.");
const [, id, metaRoute] = match;
if (req.method === "GET" && metaRoute) {
rateLimit(req, "shares-read", limits.readsPerMinute);
const meta = readableShare(id);
json(res, 200, { size: meta.size, expiresAt: meta.expiresAt, singleUse: meta.singleUse });
return true;
}
if (req.method === "GET") {
rateLimit(req, "shares-read", limits.readsPerMinute);
handleDownload(id, res);
return true;
}
if (req.method === "DELETE" && !metaRoute) {
rateLimit(req, "shares-read", limits.readsPerMinute);
await handleDelete(id, req, res);
return true;
}
throw httpError(405, "METHOD_NOT_ALLOWED", "Méthode non prise en charge.");
} catch (error) {
if (res.headersSent) {
res.destroy();
return true;
}
const status = error.status || 500;
// Le corps d'un envoi refusé n'est pas lu : la connexion est fermée pour ne pas le recevoir pour rien.
const closing = req.method === "POST" && !req.readableEnded;
json(res, status, { error: { code: error.code || "INTERNAL_ERROR", message: error.status ? error.message : "Une erreur serveur est survenue." } }, {
...(error.headers || {}),
...(closing ? { Connection: "close" } : {})
});
if (closing) res.once("finish", () => req.destroy());
if (!error.status) console.error(error);
return true;
}
}
handler.close = () => {
clearInterval(purgeTimer);
};
handler.store = store;
handler.limits = limits;
return handler;
}

165
services/shares/store.js Normal file
View file

@ -0,0 +1,165 @@
// Rôle : conserve sur disque les envois de toolbox chiffrés, le temps de leur validité, et les purge à l'échéance.
import { mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
import { rename, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
export const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{22}$/;
// Un fichier .part plus ancien n'appartient plus à aucun envoi en cours : ils sont tous coupés bien avant.
const ABANDONED_PART_MS = 60 * 60 * 1000;
function isMeta(value) {
return value && typeof value === "object"
&& Number.isSafeInteger(value.createdAt)
&& Number.isSafeInteger(value.expiresAt)
&& Number.isSafeInteger(value.size) && value.size > 0
&& typeof value.singleUse === "boolean"
&& Number.isSafeInteger(value.reads) && value.reads >= 0
&& typeof value.deleteTokenHash === "string";
}
function readJson(file) {
try {
return JSON.parse(readFileSync(file, "utf8"));
} catch {
return null;
}
}
function fileSize(file) {
try {
return statSync(file).size;
} catch {
return -1;
}
}
export class ShareStore {
constructor({ dir, now = Date.now }) {
this.dir = dir;
this.now = now;
this.metas = new Map();
// Envois à usage unique en cours de lecture : une seconde lecture simultanée ne doit pas les obtenir.
this.claimed = new Set();
this.totalBytes = 0;
this.load();
}
binPath(id) {
return join(this.dir, `${id}.bin`);
}
partPath(id) {
return join(this.dir, `${id}.part`);
}
metaPath(id) {
return join(this.dir, `${id}.json`);
}
// Lecture synchrone au démarrage : tout ce qui est incomplet, illisible ou expiré est supprimé.
load() {
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
const names = readdirSync(this.dir);
const now = this.now();
for (const name of names) {
const file = join(this.dir, name);
if (name.endsWith(".part") || name.endsWith(".tmp")) {
rmSync(file, { force: true });
continue;
}
if (!name.endsWith(".json")) continue;
const id = name.slice(0, -5);
const meta = readJson(file);
const binSize = fileSize(this.binPath(id));
if (!SHARE_ID_PATTERN.test(id) || !isMeta(meta) || meta.expiresAt <= now || binSize !== meta.size) {
rmSync(file, { force: true });
rmSync(this.binPath(id), { force: true });
continue;
}
this.metas.set(id, meta);
this.totalBytes += meta.size;
}
// Un contenu sans métadonnées vient d'une écriture interrompue.
for (const name of names) {
if (name.endsWith(".bin") && !this.metas.has(name.slice(0, -4))) rmSync(join(this.dir, name), { force: true });
}
}
get count() {
return this.metas.size;
}
// Renvoie un envoi encore lisible, ou null s'il est absent, expiré ou déjà pris par une lecture à usage unique.
get(id) {
const meta = this.metas.get(id);
if (!meta) return null;
if (meta.expiresAt <= this.now()) {
void this.remove(id).catch((error) => console.error(error));
return null;
}
if (this.claimed.has(id)) return null;
return meta;
}
async writeMeta(id, meta) {
const tmp = join(this.dir, `${id}.json.tmp`);
await writeFile(tmp, JSON.stringify(meta), { mode: 0o600 });
await rename(tmp, this.metaPath(id));
}
// Le contenu complet est déjà dans le fichier .part : il devient lisible une fois ses métadonnées écrites.
async commit(id, meta) {
await rename(this.partPath(id), this.binPath(id));
try {
await this.writeMeta(id, meta);
} catch (error) {
await rm(this.binPath(id), { force: true });
throw error;
}
this.metas.set(id, meta);
this.totalBytes += meta.size;
}
async recordRead(id) {
const meta = this.metas.get(id);
if (!meta) return;
meta.reads += 1;
await this.writeMeta(id, meta);
}
claim(id) {
this.claimed.add(id);
}
release(id) {
this.claimed.delete(id);
}
async remove(id) {
const meta = this.metas.get(id);
if (!meta) return false;
this.metas.delete(id);
this.claimed.delete(id);
this.totalBytes -= meta.size;
// Les métadonnées partent d'abord : un redémarrage entre les deux supprime le contenu orphelin.
await rm(this.metaPath(id), { force: true });
await rm(this.binPath(id), { force: true });
return true;
}
async purge() {
const now = this.now();
for (const [id, meta] of [...this.metas]) {
if (meta.expiresAt <= now) await this.remove(id);
}
for (const name of readdirSync(this.dir)) {
if (!name.endsWith(".part") && !name.endsWith(".tmp")) continue;
const file = join(this.dir, name);
try {
if (now - statSync(file).mtimeMs > ABANDONED_PART_MS) await rm(file, { force: true });
} catch {
// Le fichier a été renommé ou supprimé entre-temps.
}
}
}
}

View file

@ -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",

View 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");
});

View 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);
});

View 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;
}
});

View file

@ -3,6 +3,7 @@ import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { loadProjectEnv } from "./scripts/load-project-env.mjs";
import { createCardsApiHandler } from "./services/cards/api.js";
import { createSharesApiHandler } from "./services/shares/api.js";
import { resolve } from "node:path";
loadProjectEnv();
@ -25,10 +26,29 @@ function nebulaCardsApi() {
};
}
function toolboxSharesApi() {
return {
name: "toolbox-shares-api",
apply: "serve",
configureServer(server) {
// Les plafonds par connexion sont levés : toute la suite E2E part de la même adresse. Les quotas du navigateur restent actifs.
const handler = createSharesApiHandler({
projectRoot: resolve("."),
enabled: process.env.SHARES_ENABLED !== "false",
limits: { ipDailyUploads: 100_000, ipDailyBytes: Number.MAX_SAFE_INTEGER, ipUploadsPerMinute: 100_000, readsPerMinute: 100_000, minFreeBytes: 0 }
});
server.middlewares.use(async (req, res, next) => {
if (!await handler(req, res)) next();
});
server.httpServer?.once("close", handler.close);
}
};
}
export default defineConfig({
root: "website",
publicDir: "public",
plugins: [react(), nebulaCardsApi()],
plugins: [react(), nebulaCardsApi(), toolboxSharesApi()],
server: {
host: devHost,
port: Number(process.env.PORT || 5173)

View file

@ -15,7 +15,7 @@
"sidebar": {
"badge": "Local first",
"note": "Données stockées dans ce navigateur.",
"cardsNote": "Les toolboxes restent locales. Sokko TCG utilise un compte sécurisé."
"cardsNote": "Les toolboxes restent locales, sauf le temps d’un envoi chiffré. Sokko TCG utilise un compte sécurisé."
},
"topbar": {
"dashboard": "Dashboard",
@ -142,7 +142,7 @@
},
"privacy": {
"title": "Confidentialité de Sokko TCG",
"intro": "Sokko TCG est le seul espace de Sokko G à stocker des données sur le serveur. Vos toolboxes restent dans votre navigateur.",
"intro": "Sokko TCG est le seul espace de Sokko G à garder durablement des données sur le serveur. Vos toolboxes restent dans votre navigateur ; quand vous en envoyez une, le serveur en garde une copie chiffrée, qu’il ne peut pas lire, pendant 24 heures au plus. Votre adresse IP sert alors seulement, en mémoire, à limiter les abus.",
"collectedTitle": "Données conservées",
"collected": "Votre identifiant, votre pseudo et votre avatar Discord, ainsi que votre collection, vos ouvertures, vos échanges et votre historique de jeu. La connexion Discord ne demande ni votre e-mail ni vos messages. Un cookie garde votre session ouverte et une copie de votre collection reste dans ce navigateur pour la consultation hors connexion.",
"purposeTitle": "Utilisation",
@ -3106,6 +3106,55 @@
"emptyTitle": "Aucune toolbox",
"emptyText": "Créez une première toolbox pour stocker vos outils dans ce navigateur."
},
"toolboxShare": {
"eyebrow": "Envoi",
"title": "Envoyer « {name} »",
"description": "Sokko G crée un lien chiffré vers une copie de cette toolbox. Le serveur la garde 24 heures au plus, sans pouvoir la lire. Toute personne qui a le lien peut l’importer dans son navigateur.",
"checking": "Vérification des envois en cours…",
"singleUseLabel": "Supprimer après la première utilisation",
"singleUseHelp": "Le lien ne fonctionne qu’une fois. Décochez pour le partager avec plusieurs personnes jusqu’à son expiration.",
"create": "Créer le lien",
"cancel": "Annuler",
"close": "Fermer",
"preparing": "Chiffrement de la toolbox…",
"uploading": "Envoi : {percent} %",
"linkLabel": "Lien à transmettre",
"copy": "Copier",
"copied": "Lien copié",
"expires": "Valable jusqu’au {date}.",
"singleUseActive": "Il ne fonctionne qu’une fois.",
"reusableActive": "Il peut être utilisé plusieurs fois.",
"revoke": "Révoquer",
"revoked": "Lien révoqué.",
"existing": "Cette toolbox a déjà un lien valide. Révoquez-le pour en créer un nouveau.",
"limitActive": "Vous avez déjà {max} envois en cours. Révoquez-en un pour envoyer cette toolbox.",
"limitDailyCount": "Vous avez atteint la limite de {max} envois par 24 heures. Nouvel envoi possible le {date}.",
"limitDailyBytes": "Cet envoi dépasserait la limite de {max} Mo envoyés par 24 heures. Nouvel envoi possible le {date}.",
"tooLarge": "Cette toolbox pèse {size} Mo une fois chiffrée, au-delà de la limite de {max} Mo. Utilisez plutôt l’export en fichier.",
"activeTitle": "Autres envois en cours",
"exportFallback": "Exporter en fichier",
"privacy": "La clé de déchiffrement fait partie du lien et n’est jamais envoyée au serveur. Votre adresse IP sert seulement, en mémoire, à limiter les abus. Vos limites d’envoi et la liste de vos liens sont gardées dans ce navigateur.",
"receive": {
"eyebrow": "Toolbox reçue",
"title": "Recevoir une toolbox",
"checking": "Vérification du lien…",
"downloading": "Téléchargement : {percent} %",
"decrypting": "Déchiffrement…",
"importing": "Import dans ce navigateur…",
"expires": "Lien valable jusqu’au {date}.",
"spaces": "{count} espace(s), {tools} outil(s)",
"localNote": "La toolbox sera copiée dans ce navigateur, comme un import de fichier. Elle ne reste liée ni à l’expéditeur ni au serveur.",
"import": "Importer dans mes toolboxes",
"singleUseNotice": "Ce lien ne fonctionne qu’une fois : la toolbox sera importée dès sa réception.",
"receiveAndImport": "Recevoir et importer",
"notFound": "Ce lien a expiré, a été révoqué ou a déjà été utilisé. Demandez à l’expéditeur de vous en envoyer un nouveau.",
"keyMissing": "Ce lien est incomplet : la clé de déchiffrement manque. Copiez-le en entier, y compris la partie après le dernier #.",
"disabled": "L’envoi de toolbox n’est pas disponible sur ce serveur.",
"failed": "Impossible de recevoir la toolbox. Réessayez plus tard.",
"retry": "Réessayer",
"back": "Voir mes toolboxes"
}
},
"guideChecklist": {
"label": "Lien avec le guide",
"selectLabel": "Checklist associée",

View file

@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21 3L10.5 13.5M21 3L14.5 21L10.5 13.5M21 3L3 9.5L10.5 13.5" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 256 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 583 KiB

After

Width:  |  Height:  |  Size: 626 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 451 KiB

After

Width:  |  Height:  |  Size: 850 KiB

Before After
Before After

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);
}