sokko-g/tests/server-cache.test.mjs
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:42:13 +01:00

138 lines
6.5 KiB
JavaScript

/**
* @file 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, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import assert from "node:assert/strict";
import { test } from "node:test";
import { createStaticServer } from "../server.mjs";
async function writeFixture(root, path, content) {
const file = join(root, path);
await mkdir(dirname(file), { recursive: true });
await writeFile(file, content);
return file;
}
test("production server separates stable files from versioned assets", async (t) => {
const root = await mkdtemp(join(tmpdir(), "sokko-server-cache-"));
await writeFixture(root, "index.html", "<main>Sokko G</main>");
await writeFixture(root, "data/site.json", JSON.stringify({ title: "Sokko G" }));
await writeFixture(root, "assets/index-Ab12_cd34.js", "console.log('versioned');");
await writeFixture(root, "assets/runtime.js", "console.log('stable');");
const imageFile = await writeFixture(root, "static/img/hero.png", "image-v1");
const server = createStaticServer({ root, publicRoot: root });
await new Promise((resolve, reject) => {
server.once("error", reject);
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 });
});
const address = server.address();
const request = (path) => fetch(`http://127.0.0.1:${address.port}${path}`);
const html = await request("/");
assert.equal(html.status, 200);
assert.equal(html.headers.get("cache-control"), "no-store");
const spaFallback = await request("/toolbox/example");
assert.equal(spaFallback.status, 200);
assert.equal(spaFallback.headers.get("cache-control"), "no-store");
const json = await request("/data/site.json");
assert.equal(json.status, 200);
assert.equal(json.headers.get("cache-control"), "no-cache");
const bundle = await request("/assets/index-Ab12_cd34.js");
assert.equal(bundle.status, 200);
assert.equal(bundle.headers.get("cache-control"), "public, max-age=31536000, immutable");
const stableScript = await request("/assets/runtime.js");
assert.equal(stableScript.status, 200);
assert.equal(stableScript.headers.get("cache-control"), "no-cache");
const firstImage = await request("/static/img/hero.png");
assert.equal(firstImage.headers.get("cache-control"), "no-cache");
assert.equal(await firstImage.text(), "image-v1");
await writeFile(imageFile, "image-v2");
const replacedImage = await request("/static/img/hero.png");
assert.equal(await replacedImage.text(), "image-v2");
const missingBundle = await request("/assets/index-OldHash9.js");
assert.equal(missingBundle.status, 404);
assert.equal(missingBundle.headers.get("cache-control"), "no-store");
});
test("stable files can be revalidated with an ETag while no-store and immutable responses stay unconditional", async (t) => {
const root = await mkdtemp(join(tmpdir(), "sokko-server-etag-"));
await writeFixture(root, "index.html", "<main>Sokko G</main>");
await writeFixture(root, "assets/index-Ab12_cd34.js", "console.log('versioned');");
const imageFile = await writeFixture(root, "static/img/card.webp", "image-v1");
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) => server.close(resolve));
await rm(root, { recursive: true, force: true });
});
const url = (path) => `http://127.0.0.1:${server.address().port}${path}`;
const first = await fetch(url("/static/img/card.webp"));
const etag = first.headers.get("etag");
assert.match(etag, /^W\/"/);
assert.equal(await first.text(), "image-v1");
const unchanged = await fetch(url("/static/img/card.webp"), { headers: { "If-None-Match": `"other", ${etag}` } });
assert.equal(unchanged.status, 304);
assert.equal(unchanged.headers.get("cache-control"), "no-cache");
assert.equal(await unchanged.text(), "");
await writeFile(imageFile, "image-version-2");
const replaced = await fetch(url("/static/img/card.webp"), { headers: { "If-None-Match": etag } });
assert.equal(replaced.status, 200);
assert.equal(await replaced.text(), "image-version-2");
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"));
}
});
test("client code never evaluates strings, since the production CSP forbids unsafe-eval", async () => {
const entries = await readdir("website/src", { recursive: true, withFileTypes: true });
const sources = entries.filter((entry) => entry.isFile() && /\.(jsx?|mjs)$/.test(entry.name));
assert.ok(sources.length > 0);
for (const entry of sources) {
const path = join(entry.parentPath, entry.name);
const source = await readFile(path, "utf8");
assert.doesNotMatch(source, /(?<![\w.])(?:new\s+)?Function\s*\(|(?<![\w.])eval\s*\(/, path);
}
});