diff --git a/.forgejo/workflows/deploy-prod.yml b/.forgejo/workflows/deploy-prod.yml index 5db835f..4309ce5 100644 --- a/.forgejo/workflows/deploy-prod.yml +++ b/.forgejo/workflows/deploy-prod.yml @@ -23,14 +23,14 @@ jobs: run: printf '%s' "$REQUESTED_COMMIT" | grep -Eq '^[0-9a-f]{40}$' - name: Check out the requested commit - uses: https://data.forgejo.org/actions/checkout@v4 + uses: https://data.forgejo.org/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: ref: ${{ inputs.commit }} fetch-depth: 0 persist-credentials: false - name: Set up the pinned Node version - uses: https://data.forgejo.org/actions/setup-node@v4 + uses: https://data.forgejo.org/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24.11.1 cache: npm @@ -59,8 +59,6 @@ jobs: runs-on: docker env: DEPLOY_COMMIT: ${{ needs.validate.outputs.commit }} - DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} - DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }} steps: - name: Install the deployment clients @@ -71,6 +69,9 @@ jobs: fi - name: Configure the pinned production host key + env: + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} + DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }} run: | test -n "$DEPLOY_SSH_KEY" test -n "$DEPLOY_SSH_KNOWN_HOSTS" diff --git a/.forgejo/workflows/validate-main.yml b/.forgejo/workflows/validate-main.yml index edd6c45..e9dcce6 100644 --- a/.forgejo/workflows/validate-main.yml +++ b/.forgejo/workflows/validate-main.yml @@ -15,13 +15,13 @@ jobs: steps: - name: Check out the pushed commit - uses: https://data.forgejo.org/actions/checkout@v4 + uses: https://data.forgejo.org/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: ref: ${{ gitea.sha }} persist-credentials: false - name: Set up the pinned Node version - uses: https://data.forgejo.org/actions/setup-node@v4 + uses: https://data.forgejo.org/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 24.11.1 cache: npm @@ -49,12 +49,10 @@ jobs: runs-on: docker env: DEPLOY_COMMIT: ${{ needs.validate.outputs.commit }} - DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} - DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }} steps: - name: Check out the current main head - uses: https://data.forgejo.org/actions/checkout@v4 + uses: https://data.forgejo.org/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: ref: main persist-credentials: false @@ -81,6 +79,9 @@ jobs: - name: Configure the pinned production host key if: steps.freshness.outputs.deploy == 'true' + env: + DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} + DEPLOY_SSH_KNOWN_HOSTS: ${{ secrets.DEPLOY_SSH_KNOWN_HOSTS }} run: | test -n "$DEPLOY_SSH_KEY" test -n "$DEPLOY_SSH_KNOWN_HOSTS" diff --git a/docs/DELIVERY.md b/docs/DELIVERY.md index e615dfa..c11b274 100644 --- a/docs/DELIVERY.md +++ b/docs/DELIVERY.md @@ -101,7 +101,8 @@ sudo install -o root -g root -m 0755 \ sudo /usr/local/bin/deploy-sokko-g --help ``` -Cette installation doit être répétée après toute modification de +Le script exécute les fichiers de NVM sous le compte du service, jamais en root : ce +dossier lui appartient. Cette installation doit être répétée après toute modification de `scripts/deploy-sokko-g.sh`. Le workflow appelle volontairement la copie administrée sous `/usr/local/bin` et ne la remplace pas automatiquement. @@ -212,6 +213,10 @@ identifiants Discord, le jeu reste actif mais le bouton de connexion est remplac par un avis ; sans `CARDS_ADMIN_DISCORD_IDS`, personne n'a accès à l'administration. Vérifier donc `/api/cards/config` et les journaux après chaque activation. +Le jeu et ce mode de connexion restent inactifs tant que `CARDS_ENABLED` et +`CARDS_DEV_AUTH` ne valent pas explicitement `true`, y compris sans `NODE_ENV` ; +seul `npm run dev` les active de lui-même. + `CARDS_DEV_AUTH=true` expose un bouton « Version développement » qui ouvre une session locale avec les droits administrateur. Ce mode est réservé aux tests : `server.mjs` l'ignore et journalise une erreur lorsque `NODE_ENV=production`. @@ -336,6 +341,15 @@ stable `dragon-sidebar.webp`, puis `public, max-age=31536000, immutable` pour le bundle JavaScript hashé référencé par le document. Les réponses passaient par Caddy. Ce constat est daté et doit être refait après un changement de proxy. +## En-têtes de sécurité + +`server.mjs` ajoute à toutes ses réponses une CSP, HSTS (sans `includeSubDomains`), +`nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy` et `Permissions-Policy`. Le script +inline d'`index.html` est autorisé par son empreinte, calculée au démarrage. Une nouvelle +origine externe (image, API, police) doit être ajoutée à la CSP de ce fichier, sinon le +navigateur la bloque. Vite ne reçoit pas ces en-têtes : seuls `npm start` et les tests +`test:e2e:cards` les exercent. + ## Adresse d'écoute Sans `HOST`, le serveur Node écoute sur toutes les interfaces. La VM ayant une diff --git a/e2e/basic-tools.spec.js b/e2e/basic-tools.spec.js index 40f14f8..649feb9 100644 --- a/e2e/basic-tools.spec.js +++ b/e2e/basic-tools.spec.js @@ -2,6 +2,7 @@ import { expect, test } from "@playwright/test"; import { Buffer } from "node:buffer"; import { createToolboxImportPayload } from "./helpers/toolboxImport.js"; +import { solidPngDataUrl } from "./helpers/solidPng.js"; import { readStoredModuleData } from "./helpers/storage.js"; async function setup(page, type, data) { @@ -150,12 +151,11 @@ test("a simple checklist can hide and restore checked rows", async ({ page }) => }); test("images open a gallery and navigate the current collection without looping", async ({ page }) => { - const makeImage = (color) => `data:image/svg+xml,${encodeURIComponent(``)}`; const tool = await setup(page, "images", { images: [ - { id: "one", label: "First", dataUrl: makeImage("#8b5cf6") }, - { id: "two", label: "Second", dataUrl: makeImage("#22d3ee") }, - { id: "three", dataUrl: makeImage("#f6c453") } + { id: "one", label: "First", dataUrl: solidPngDataUrl([139, 92, 246]) }, + { id: "two", label: "Second", dataUrl: solidPngDataUrl([34, 211, 238]) }, + { id: "three", dataUrl: solidPngDataUrl([246, 196, 83]) } ] }); @@ -233,7 +233,7 @@ test("images open a gallery and navigate the current collection without looping" test("image gallery keeps proportional cards and compact centered rows at maximum zoom", async ({ page }) => { await page.setViewportSize({ width: 1550, height: 900 }); - const makeImage = (index) => `data:image/svg+xml,${encodeURIComponent(``)}`; + const makeImage = (index) => solidPngDataUrl([40 + index * 30, 90, 220 - index * 25]); const tool = await setup(page, "images", { images: Array.from({ length: 7 }, (_, index) => ({ id: `image-${index}`, label: `Image ${index + 1}`, dataUrl: makeImage(index) })) }); diff --git a/e2e/helpers/solidPng.js b/e2e/helpers/solidPng.js new file mode 100644 index 0000000..a7d1224 --- /dev/null +++ b/e2e/helpers/solidPng.js @@ -0,0 +1,28 @@ +// Rôle : génère de vraies images bitmap unies, seul format accepté par les outils d'image. +import { Buffer } from "node:buffer"; +import { crc32, deflateSync } from "node:zlib"; + +function chunk(type, data) { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type, "latin1"), data]); + const checksum = Buffer.alloc(4); + checksum.writeUInt32BE(crc32(body)); + return Buffer.concat([length, body, checksum]); +} + +export function solidPngDataUrl([red, green, blue], width = 640, height = 360) { + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header.set([8, 2, 0, 0, 0], 8); + const row = Buffer.alloc(1 + width * 3); + for (let x = 0; x < width; x += 1) row.set([red, green, blue], 1 + x * 3); + const png = Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", header), + chunk("IDAT", deflateSync(Buffer.concat(Array.from({ length: height }, () => row)))), + chunk("IEND", Buffer.alloc(0)) + ]); + return `data:image/png;base64,${png.toString("base64")}`; +} diff --git a/ops/systemd/sokko-g-cards-backup.service b/ops/systemd/sokko-g-cards-backup.service index ec40efd..033603d 100644 --- a/ops/systemd/sokko-g-cards-backup.service +++ b/ops/systemd/sokko-g-cards-backup.service @@ -6,6 +6,9 @@ ConditionPathExists=/data/webapps/private/sokko-g/nebula-cards.sqlite [Service] Type=oneshot User=shinuwa +# Empêche le processus et ses enfants d'obtenir des droits supplémentaires, notamment via sudo. +NoNewPrivileges=true +PrivateTmp=true WorkingDirectory=/data/webapps/sites/sokko-g Environment=NODE_ENV=production ExecStart=/home/shinuwa/.nvm/versions/node/v24.11.1/bin/node scripts/backup-nebula-cards.mjs scheduled /data/webapps/private/sokko-g/nebula-cards.sqlite /data/backups/sokko-g --keep 14 diff --git a/ops/systemd/sokko-g.service b/ops/systemd/sokko-g.service index 87d45fe..ce5c372 100644 --- a/ops/systemd/sokko-g.service +++ b/ops/systemd/sokko-g.service @@ -6,6 +6,9 @@ After=network.target [Service] Type=simple User=shinuwa +# Empêche le processus et ses enfants d'obtenir des droits supplémentaires, notamment via sudo. +NoNewPrivileges=true +PrivateTmp=true WorkingDirectory=/data/webapps/sites/sokko-g Environment=NODE_ENV=production Environment=PATH=/home/shinuwa/.nvm/versions/node/v24.11.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin diff --git a/scripts/deploy-sokko-g.sh b/scripts/deploy-sokko-g.sh index fded009..ed3856e 100755 --- a/scripts/deploy-sokko-g.sh +++ b/scripts/deploy-sokko-g.sh @@ -42,9 +42,9 @@ as_app_user() { restore_previous_release() { local previous_commit=$1 - rm -rf -- "$APP_ROOT/website/dist" + as_app_user rm -rf -- "$APP_ROOT/website/dist" if [[ -n "$backup_dist" && -d "$backup_dist" ]]; then - mv "$backup_dist" "$APP_ROOT/website/dist" + as_app_user mv "$backup_dist" "$APP_ROOT/website/dist" fi as_app_user git -C "$APP_ROOT" checkout --detach "$previous_commit" systemctl restart "$SERVICE_NAME" || true @@ -74,8 +74,9 @@ command -v flock >/dev/null echo "Node 24.11.1 and npm 11.17.0 must be installed under $NODE_HOME." >&2 exit 1 } -[[ "$($NODE_BIN --version)" == "v24.11.1" ]] -[[ "$(env PATH="$NODE_HOME/bin:/usr/bin:/bin" "$NPM_BIN" --version)" == "11.17.0" ]] +# Ces fichiers appartiennent au compte du service : les lancer en root lui donnerait les droits root. +[[ "$(as_app_user "$NODE_BIN" --version)" == "v24.11.1" ]] +[[ "$(as_app_user env PATH="$NODE_HOME/bin:/usr/bin:/bin" "$NPM_BIN" --version)" == "11.17.0" ]] systemctl show --property=ExecStart --value "$SERVICE_NAME" | grep -Fq "$NPM_BIN" exec 9>"$LOCK_FILE" @@ -113,10 +114,9 @@ as_app_user env \ as_app_user git -C "$APP_ROOT" checkout --detach "$requested_commit" backup_dist="$build_root/previous-dist" if [[ -d "$APP_ROOT/website/dist" ]]; then - mv "$APP_ROOT/website/dist" "$backup_dist" + as_app_user mv "$APP_ROOT/website/dist" "$backup_dist" fi -mv "$worktree/website/dist" "$APP_ROOT/website/dist" -chown -R "$APP_USER:$APP_USER" "$APP_ROOT/website/dist" +as_app_user mv "$worktree/website/dist" "$APP_ROOT/website/dist" if ! systemctl restart "$SERVICE_NAME" || ! systemctl is-active --quiet "$SERVICE_NAME"; then echo "The new release did not start; restoring $previous_commit." >&2 diff --git a/server.mjs b/server.mjs index f30221f..1492ffd 100644 --- a/server.mjs +++ b/server.mjs @@ -1,5 +1,6 @@ // Rôle : sert l'application Vite construite ou les sources publiques avec leur politique de cache. -import { createReadStream, existsSync, statSync } from "node:fs"; +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 { createServer } from "node:http"; @@ -71,8 +72,43 @@ function fileEtag(file) { return `W/"${size.toString(16)}-${Math.floor(mtimeMs).toString(16)}"`; } +// Le script inline d'index.html est autorisé par son empreinte, recalculée car un build peut le modifier. +function inlineScriptHashes(root) { + const indexFile = join(root, "index.html"); + if (!existsSync(indexFile)) return []; + return [...readFileSync(indexFile, "utf8").matchAll(/]*)?>([\s\S]*?)<\/script>/g)] + .filter(([, body]) => body.trim()) + .map(([, body]) => `'sha256-${createHash("sha256").update(body).digest("base64")}'`); +} + +function securityHeaders(root) { + const contentSecurityPolicy = [ + "default-src 'self'", + ["script-src 'self'", ...inlineScriptHashes(root)].join(" "), + // Le bloc-notes conserve ses couleurs dans des attributs style, relus depuis le stockage. + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: blob: https://cdn.discordapp.com", + "object-src 'none'", + "base-uri 'self'", + "form-action 'self'", + "frame-ancestors 'none'" + ].join("; "); + return { + "Content-Security-Policy": contentSecurityPolicy, + // Sans includeSubDomains : les autres applications du domaine gèrent leur propre transport. + "Strict-Transport-Security": "max-age=31536000", + "X-Content-Type-Options": "nosniff", + "X-Frame-Options": "DENY", + "Referrer-Policy": "strict-origin-when-cross-origin", + "Permissions-Policy": "camera=(), microphone=(), geolocation=()" + }; +} + export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) { + const headers = securityHeaders(root); + async function handleRequest(req, res) { + for (const [name, value] of Object.entries(headers)) res.setHeader(name, value); if (cardsApi && await cardsApi(req, res)) return; const file = resolvePath(req.url || "/", root, publicRoot); if (!file || !existsSync(file)) { diff --git a/services/cards/api.js b/services/cards/api.js index fc21954..0f666a9 100644 --- a/services/cards/api.js +++ b/services/cards/api.js @@ -118,8 +118,9 @@ export function createRateLimiter(now) { export function createCardsApiHandler({ projectRoot = resolve("."), env = process.env, - enabled = bool(env.CARDS_ENABLED, env.NODE_ENV !== "production"), - devAuth: requestedDevAuth = bool(env.CARDS_DEV_AUTH, env.NODE_ENV !== "production"), + // Un oubli de NODE_ENV ne doit jamais ouvrir le jeu ni la connexion factice : les deux se demandent explicitement. + enabled = bool(env.CARDS_ENABLED), + devAuth: requestedDevAuth = bool(env.CARDS_DEV_AUTH), // Réservé au serveur E2E : cette option n'est pas lisible depuis l'environnement, une erreur de configuration ne peut donc pas l'activer. allowProductionDevAuth = false, databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"), @@ -149,7 +150,7 @@ export function createCardsApiHandler({ database = new CardsDatabase(databasePath); service = new CardsService({ database, catalog, now, random, devPerks }); } - const secureCookies = env.NODE_ENV === "production"; + const secureCookies = env.NODE_ENV === "production" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://"); const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean)); service?.syncAdmins(adminIds, { keepDevAdmin: devAuth }); service?.runMaintenance(); diff --git a/tests/deployment-workflow.test.mjs b/tests/deployment-workflow.test.mjs index eb07ffe..68d173b 100644 --- a/tests/deployment-workflow.test.mjs +++ b/tests/deployment-workflow.test.mjs @@ -106,3 +106,30 @@ test("the production service uses the same pinned Node runtime", async () => { assert.match(service, /Environment=PATH=\/home\/shinuwa\/\.nvm\/versions\/node\/v24\.11\.1\/bin:/); assert.doesNotMatch(service, /v26\.3\.0/); }); + +test("the remote script never runs files owned by the service account as root", async () => { + const script = await readFile(remoteScriptPath, "utf8"); + + assert.match(script, /as_app_user "\$NODE_BIN" --version/); + assert.match(script, /as_app_user env PATH="\$NODE_HOME\/bin:\/usr\/bin:\/bin" "\$NPM_BIN" --version/); + assert.doesNotMatch(script, /\$\(\$NODE_BIN/); + assert.doesNotMatch(script, /\$\(env PATH=/); + assert.doesNotMatch(script, /chown -R/); + assert.doesNotMatch(script, /^\s*(?:mv .*(?:\$APP_ROOT|\$worktree|\$backup_dist)|rm -rf -- "\$APP_ROOT)/m); +}); + +test("the services cannot gain privileges through sudo", async () => { + for (const path of [servicePath, "ops/systemd/sokko-g-cards-backup.service"]) { + assert.match(await readFile(path, "utf8"), /^NoNewPrivileges=true$/m); + } +}); + +test("deployment secrets stay in one step and actions are pinned by commit", async () => { + for (const path of [deployWorkflowPath, validationWorkflowPath]) { + const workflow = await readFile(path, "utf8"); + assert.equal(workflow.match(/secrets\.DEPLOY_SSH_KEY/g)?.length, 1); + assert.doesNotMatch(workflow.match(/ {2}deploy:\n[\s\S]*?\n {4}steps:/)?.[0] || "", /secrets\./); + assert.match(workflow, /- name: Configure the pinned production host key\n(?: {8}if: .*\n)? {8}env:\n {10}DEPLOY_SSH_KEY: \$\{\{ secrets\.DEPLOY_SSH_KEY \}\}/); + for (const [, reference] of workflow.matchAll(/uses: \S+@(\S+)/g)) assert.match(reference, /^[0-9a-f]{40}$/); + } +}); diff --git a/tests/nebula-cards-api.test.mjs b/tests/nebula-cards-api.test.mjs index a0668f1..600b125 100644 --- a/tests/nebula-cards-api.test.mjs +++ b/tests/nebula-cards-api.test.mjs @@ -316,3 +316,19 @@ test("account deletion needs a CSRF token, clears the session cookie and logs th assert.match(String(deleted.headers["set-cookie"]), /sokkog_cards_session=;.*Max-Age=0/); assert.equal((await call(handler, { path: "/api/cards/session", headers: { cookie } })).json.authenticated, false); }); + +test("without explicit settings the game and the fake admin login stay off, whatever NODE_ENV says", async (t) => { + for (const env of [{}, { NODE_ENV: "test" }]) { + const handler = createCardsApiHandler({ projectRoot: resolve("."), databasePath: ":memory:", env }); + t.after(() => handler.close()); + const { json } = await call(handler, { path: "/api/cards/config" }); + assert.equal(json.enabled, false); + assert.equal(json.devAuth, false); + } + const enabledOnly = createCardsApiHandler({ projectRoot: resolve("."), databasePath: ":memory:", env: { CARDS_ENABLED: "true" } }); + t.after(() => enabledOnly.close()); + const { json } = await call(enabledOnly, { path: "/api/cards/config" }); + assert.equal(json.enabled, true); + assert.equal(json.devAuth, false); + assert.equal((await call(enabledOnly, { method: "POST", path: "/api/cards/auth/dev" })).status, 404); +}); diff --git a/tests/server-cache.test.mjs b/tests/server-cache.test.mjs index 11ae6dc..f708820 100644 --- a/tests/server-cache.test.mjs +++ b/tests/server-cache.test.mjs @@ -1,4 +1,5 @@ // Rôle : vérifie les en-têtes de cache du serveur Node sur des fichiers de production représentatifs. +import { createHash } from "node:crypto"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -97,3 +98,27 @@ test("stable files can be revalidated with an ETag while no-store and immutable assert.equal((await fetch(url("/"))).headers.get("etag"), null); assert.equal((await fetch(url("/assets/index-Ab12_cd34.js"))).headers.get("etag"), null); }); + +test("every response carries the security headers and the CSP allows only the inline script of the build", async (t) => { + const root = await mkdtemp(join(tmpdir(), "sokko-server-headers-")); + const inlineScript = "console.log('recovery');"; + await writeFixture(root, "index.html", ``); + const server = createStaticServer({ root, publicRoot: root }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(async () => { + await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); + await rm(root, { recursive: true, force: true }); + }); + + for (const path of ["/", "/missing.js"]) { + const { headers } = await fetch(`http://127.0.0.1:${server.address().port}${path}`); + const csp = headers.get("content-security-policy"); + assert.ok(csp.includes(`script-src 'self' 'sha256-${createHash("sha256").update(inlineScript).digest("base64")}';`), csp); + assert.doesNotMatch(csp, /script-src[^;]*unsafe/); + assert.match(csp, /frame-ancestors 'none'/); + assert.equal(headers.get("x-content-type-options"), "nosniff"); + assert.equal(headers.get("x-frame-options"), "DENY"); + assert.match(headers.get("strict-transport-security"), /^max-age=\d+$/); + assert.ok(headers.get("referrer-policy")); + } +}); diff --git a/tests/toolbox-import-validation.test.mjs b/tests/toolbox-import-validation.test.mjs index f288632..c8de9b5 100644 --- a/tests/toolbox-import-validation.test.mjs +++ b/tests/toolbox-import-validation.test.mjs @@ -3,7 +3,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { TOOLBOX_MODULE_DEFINITIONS } from "../website/src/features/toolboxes/toolboxModuleRegistry.js"; import { useToolboxActions } from "../website/src/features/toolboxes/useToolboxActions.js"; -import { createGlobalExportPayload, createToolboxExportPayload } from "../website/src/features/toolboxes/storage/toolboxStorage.js"; +import { createGlobalExportPayload, createToolboxExportPayload, normalizeImageAnnotationData, normalizeImagesData } from "../website/src/features/toolboxes/storage/toolboxStorage.js"; +import { compactImagesDataForStorage } from "../website/src/features/toolboxes/storage/modules/imageAnnotation.js"; import { validateToolboxImportPayload } from "../website/src/features/toolboxes/storage/toolboxImportValidation.js"; const MODULE_TYPES = Object.keys(TOOLBOX_MODULE_DEFINITIONS); @@ -286,3 +287,27 @@ test("invalid imports never reach the storage transaction", async () => { assert.equal(writes, 0); assert.match(message, /version 999/); }); + +test("images that could run scripts or reach another site are rejected at import", () => { + const unsafe = [ + "data:text/html;base64,PHNjcmlwdD4=", + "data:image/svg+xml;base64,PHN2Zz4=", + "https://example.com/pixel.png", + "javascript:alert(1)" + ]; + for (const dataUrl of unsafe) { + for (const [type, data] of [["images", { images: [{ id: "image", dataUrl }] }], ["imageAnnotation", { image: dataUrl, markers: [] }]]) { + const payload = clone(validIndividualPayload()); + payload.modules[payload.toolbox.modules.find((module) => module.type === type).id] = data; + assert.throws(() => validateToolboxImportPayload(payload), /format canonique/, `${type}: ${dataUrl}`); + } + } +}); + +test("unsafe images already stored are hidden and dropped from storage", () => { + const safe = { id: "safe", dataUrl: "data:image/webp;base64,AA==" }; + const stored = { images: [safe, { id: "bad", dataUrl: "data:image/svg+xml;base64,PHN2Zz4=" }, { id: "none" }] }; + assert.deepEqual(normalizeImagesData(stored).images, [safe]); + assert.deepEqual(compactImagesDataForStorage(stored), { images: [safe] }); + assert.equal(normalizeImageAnnotationData({ image: "data:text/html;base64,AA==" }).image, ""); +}); diff --git a/website/src/components/ImageViewer.jsx b/website/src/components/ImageViewer.jsx index 5a26a74..57eea9a 100644 --- a/website/src/components/ImageViewer.jsx +++ b/website/src/components/ImageViewer.jsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { DrawingControls } from "../features/toolboxes/modules/DrawingControls.jsx"; import { DrawingOverlay } from "../features/toolboxes/modules/DrawingOverlay.jsx"; +import { isSafeImageDataUrl } from "../features/toolboxes/storage/modules/shared.js"; import { DRAWING_COLORS, DRAWING_WIDTHS } from "../utils/drawingOptions.js"; import { Icon } from "./Icon.jsx"; import { ImageGallery } from "./ImageGallery.jsx"; @@ -55,6 +56,8 @@ function dataUrlToBlob(dataUrl) { } function openImageInNewTab(dataUrl) { + // Un blob hérite de l'origine du site : seul un format bitmap peut y être ouvert sans risque. + if (!isSafeImageDataUrl(dataUrl)) return; try { const url = URL.createObjectURL(dataUrlToBlob(dataUrl)); window.open(url, "_blank", "noopener,noreferrer"); diff --git a/website/src/features/toolboxes/modules/ImagesModule.jsx b/website/src/features/toolboxes/modules/ImagesModule.jsx index a89ba97..71bd79f 100644 --- a/website/src/features/toolboxes/modules/ImagesModule.jsx +++ b/website/src/features/toolboxes/modules/ImagesModule.jsx @@ -1,12 +1,14 @@ // Rôle : fournit l'outil images avec import, galerie, libellés et annotation rapide. -import { useState } from "react"; +import { useMemo, useState } from "react"; import { Icon } from "../../../components/Icon.jsx"; import { moveItem, useGroupedReorder } from "../../../hooks/useGroupedReorder.js"; import { ModuleEmptyMessage } from "./ModuleEmptyMessage.jsx"; import { ModuleTextExchangeConfiguration } from "./ModuleConfiguration.jsx"; +import { normalizeImagesData } from "../storage/toolboxStorage.js"; export function ImagesModule({ toolboxId, moduleId, context, editing, configurationTarget }) { - const data = context.getModuleData(toolboxId, moduleId, { images: [] }); + const storedData = context.getModuleData(toolboxId, moduleId, { images: [] }); + const data = useMemo(() => normalizeImagesData(storedData), [storedData]); const textContent = context.moduleText?.images || {}; const [dragOver, setDragOver] = useState(false); const pastePlaceholder = textContent.pastePlaceholder || "Coller une image ici"; diff --git a/website/src/features/toolboxes/modules/textImport/shared.js b/website/src/features/toolboxes/modules/textImport/shared.js index 7b647bb..01c752c 100644 --- a/website/src/features/toolboxes/modules/textImport/shared.js +++ b/website/src/features/toolboxes/modules/textImport/shared.js @@ -1,5 +1,5 @@ // Rôle : fournit les helpers communs aux formats texte des outils toolbox. -const IMAGE_DATA_URL_PATTERN = /^data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+$/i; +import { isSafeImageDataUrl } from "../../storage/modules/shared.js"; export function parseColonImportLines(text) { return String(text || "") @@ -67,7 +67,7 @@ export function formatMeta(meta) { } export function isValidImageDataUrl(value) { - return IMAGE_DATA_URL_PATTERN.test(String(value || "").trim()); + return isSafeImageDataUrl(String(value || "").trim()); } export function cloneDrawingData(drawings) { diff --git a/website/src/features/toolboxes/storage/modules/imageAnnotation.js b/website/src/features/toolboxes/storage/modules/imageAnnotation.js index 39091da..7adc885 100644 --- a/website/src/features/toolboxes/storage/modules/imageAnnotation.js +++ b/website/src/features/toolboxes/storage/modules/imageAnnotation.js @@ -1,6 +1,6 @@ // Rôle : normalise et compacte les images simples et annotations d'image. import { normalizeDrawingData } from "./drawing.js"; -import { uid } from "./shared.js"; +import { isSafeImageDataUrl, uid } from "./shared.js"; function clampPercent(value) { const parsed = Number(value); @@ -9,7 +9,7 @@ function clampPercent(value) { } export function normalizeImageAnnotationData(data) { - const image = String(data?.image || ""); + const image = isSafeImageDataUrl(data?.image) ? data.image : ""; const markers = (data?.markers || []) .map((marker) => ({ id: marker?.id || uid("marker"), @@ -20,9 +20,14 @@ export function normalizeImageAnnotationData(data) { return { image, markers, drawings: normalizeDrawingData(data?.drawings, { max: 100 }) }; } +// Écarte aussi les images déjà stockées par une ancienne version qui ne validait pas leur format. +export function normalizeImagesData(data) { + return { ...data, images: (Array.isArray(data?.images) ? data.images : []).filter((image) => isSafeImageDataUrl(image?.dataUrl)) }; +} + export function compactImagesDataForStorage(value) { - const images = (Array.isArray(value?.images) ? value.images : []) - .filter((image) => image?.dataUrl) + const { images: safeImages } = normalizeImagesData(value); + const images = safeImages .map((image) => { const compact = { id: image.id || uid("image"), dataUrl: image.dataUrl }; if (image.label) compact.label = image.label; diff --git a/website/src/features/toolboxes/storage/modules/shared.js b/website/src/features/toolboxes/storage/modules/shared.js index f619e11..6fd6512 100644 --- a/website/src/features/toolboxes/storage/modules/shared.js +++ b/website/src/features/toolboxes/storage/modules/shared.js @@ -1,4 +1,11 @@ // Rôle : fournit les primitives communes de normalisation et d'identifiants du stockage toolbox. +// Formats bitmap uniquement : un SVG ou un document HTML exécuterait ses scripts sur l'origine du site une fois ouvert. +const SAFE_IMAGE_DATA_URL = /^data:image\/(?:jpeg|jpg|png|webp|gif|avif);base64,[a-z0-9+/]+=*$/i; + +export function isSafeImageDataUrl(value) { + return typeof value === "string" && SAFE_IMAGE_DATA_URL.test(value); +} + export const ID_PREFIXES = { tbx: "t", space: "sp", diff --git a/website/src/features/toolboxes/storage/toolboxStorage.js b/website/src/features/toolboxes/storage/toolboxStorage.js index 97ebc36..8e4199c 100644 --- a/website/src/features/toolboxes/storage/toolboxStorage.js +++ b/website/src/features/toolboxes/storage/toolboxStorage.js @@ -11,7 +11,7 @@ export { normalizeCountersData } from "./modules/counters.js"; export { normalizeDrawingData } from "./modules/drawing.js"; export { normalizeEquipmentPlannerData, summarizeEquipmentPlannerData } from "./modules/equipmentPlanner.js"; export { normalizeGoalTreeData } from "./modules/goalTree.js"; -export { labelFromFileName, normalizeImageAnnotationData } from "./modules/imageAnnotation.js"; +export { labelFromFileName, normalizeImageAnnotationData, normalizeImagesData } from "./modules/imageAnnotation.js"; export { hostnameFromUrl, normalizeLinksData, normalizeUrl } from "./modules/links.js"; export { normalizeMemosData } from "./modules/memos.js"; export { normalizeNotepadData, sanitizeNotepadHtml } from "./modules/notepad.js";