Close the security gaps found by the application audit
Imported toolboxes could run scripts on the site origin through image data URLs, so only bitmap images are now accepted at import, display and opening. The Cards game and its fake admin login no longer turn on when NODE_ENV is missing, and the Node server now sends a CSP and the other security headers. The deployment script no longer runs files owned by the service account as root, the services cannot gain privileges through sudo, and the deployment key stays in a single workflow step with actions pinned by commit. The script and systemd units must still be reinstalled on the server after delivery. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1adccb4e04
commit
7046515d20
20 changed files with 233 additions and 36 deletions
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="${color}"/></svg>`)}`;
|
||||
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(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="hsl(${index * 45} 70% 45%)"/></svg>`)}`;
|
||||
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) }))
|
||||
});
|
||||
|
|
|
|||
28
e2e/helpers/solidPng.js
Normal file
28
e2e/helpers/solidPng.js
Normal file
|
|
@ -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")}`;
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
38
server.mjs
38
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(/<script(?:\s[^>]*)?>([\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)) {
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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}$/);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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", `<script>${inlineScript}</script><script type="module" src="/assets/a.js"></script>`);
|
||||
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"));
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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, "");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue