Fix cache policy for stable public assets

This commit is contained in:
Shinuwa 2026-10-23 10:41:10 +02:00
parent ffb020ee98
commit 75592d7d7a
6 changed files with 171 additions and 40 deletions

View file

@ -102,3 +102,4 @@
{"id":"int-a7f31afcb66a0c2f9a2802ec7fcb0f25","kind":"field_change","created_at":"2026-10-22T20:52:18.039208354Z","actor":"Shinuwa","issue_id":"sokko-g-203","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Ajout Librairie vers toolbox livré avec copie vide/état courant, création transactionnelle, remappage des IDs et dépendances, tests unitaires et Playwright."}}
{"id":"int-a4d97f7295591e6d4affc3be37716e82","kind":"field_change","created_at":"2026-10-22T20:59:56.2557932Z","actor":"Shinuwa","issue_id":"sokko-g-xnm","extra":{"field":"status","new_value":"deferred","old_value":"open"}}
{"id":"int-1d89b4925c5f2f13cc06799a38e7aa0a","kind":"field_change","created_at":"2026-10-22T21:26:48.145195662Z","actor":"Shinuwa","issue_id":"sokko-g-qru","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Vulnerable build dependencies updated within compatible ranges; npm ci and npm audit succeed with 0 vulnerabilities; check, 195 development E2E tests, and 2 production E2E tests pass."}}
{"id":"int-f9129c0d163031072641ff2ba12cef12","kind":"field_change","created_at":"2026-10-23T08:38:03.134514281Z","actor":"Shinuwa","issue_id":"sokko-g-x8x","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Cache immutable limité aux assets Vite hashés ; HTML et 404 en no-store, JSON et fichiers stables en no-cache. Test HTTP direct de server.mjs ajouté, remplacement d’image et bundle manquant couverts, politique proxy documentée. Validation : 163 tests Node, 195 E2E développement et 2 E2E production via check:full. Le proxy externe reste à vérifier lors d’une livraison autorisée."}}

View file

@ -34,6 +34,8 @@ npm run build
Le build est généré dans `website/dist`.
`npm start` sert cette version statique avec `server.mjs`.
La politique de cache HTTP et les vérifications attendues côté proxy sont
documentées dans [`docs/DELIVERY.md`](docs/DELIVERY.md).
## Configuration

39
docs/DELIVERY.md Normal file
View file

@ -0,0 +1,39 @@
# Livraison
## Serveur statique
`npm run build` produit l'application dans `website/dist`. `npm start` sert ce
répertoire avec `server.mjs`. Les tests de Vite Preview couvrent le comportement
du build dans le navigateur, mais pas les en-têtes HTTP de ce serveur Node.
La politique de cache du serveur est la suivante :
| Ressource | `Cache-Control` | Raison |
| --- | --- | --- |
| HTML et fallback des routes React | `no-store` | Le document doit toujours pouvoir pointer vers le build courant. |
| JSON éditorial et données de jeu | `no-cache` | Le navigateur peut stocker la réponse, mais doit la redemander avant réutilisation. |
| Fichiers hashés sous `/assets/` | `public, max-age=31536000, immutable` | Une nouvelle version reçoit une nouvelle URL lors du build Vite. |
| Images, icônes et autres fichiers à URL stable | `no-cache` | Un remplacement au même chemin doit être visible sans vider le cache. |
| Ressources absentes | `no-store` | Un ancien bundle manquant ne doit pas laisser une réponse 404 persistante. |
`tests/server-cache.test.mjs` démarre directement `server.mjs` sur un port
éphémère et vérifie ces cinq cas. Il ne remplace pas les tests E2E de production,
qui continuent à valider le chargement et la récupération d'un bundle périmé.
## Proxy de production
La configuration du proxy et le script `/usr/local/bin/deploy-sokko-g` sont
externes à ce dépôt. Le proxy doit transmettre les en-têtes ci-dessus sans
ajouter de cache immuable aux URL stables. Cette propriété doit être vérifiée
sur l'origine publique après une livraison autorisée, par exemple avec :
```bash
curl -I https://example.invalid/
curl -I https://example.invalid/data/site.json
curl -I https://example.invalid/static/img/dragon-sidebar.png
curl -I https://example.invalid/assets/<fichier-hashé>.js
```
Le nom du bundle doit être repris depuis le build effectivement livré. Une
prévisualisation Vite locale ne permet pas de conclure sur les règles ajoutées
par le proxy.

View file

@ -18,6 +18,7 @@ not bugs, missing scenarios or a percentage of work remaining.
| Data loss, startup failure, deferred media | `e2e/persistence.spec.js`, `storage-startup.spec.js`, `deferred-media.spec.js`; Node persistence queue and image action tests |
| React lifecycle, shared editing and navigation | `e2e/editor-lifecycle.spec.js`, `inline-edit.spec.js`, `form-reorder.spec.js`, `shell-behavior.spec.js`, `session-state.spec.js` |
| Public data loading, retry and stale responses | `e2e/app-data.spec.js` |
| HTTP cache policy of the delivered Node server | `tests/server-cache.test.mjs`; production E2E remains responsible for stale bundle recovery |
| 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` |
@ -49,6 +50,8 @@ automatic follow-on batches required to finish this audit.
Run targeted tests while implementing a grouped change, then `npm run check:full`
as the final gate: lint, Node tests, build, development E2E and production E2E.
Use the direct Node server test for HTTP headers; Vite Preview does not exercise
the cache policy implemented by `server.mjs` or any production proxy override.
Review the diff and report actual failures or limits before closing the task.
Do not introduce visual snapshots solely to prove that a page loads.
Keep detailed command logs outside tracked source and report concise results.

View file

@ -1,19 +1,16 @@
// Rôle : sert l'application Vite construite ou les sources publiques en local.
// Rôle : sert l'application Vite construite ou les sources publiques avec leur politique de cache.
import { createReadStream, existsSync, statSync } from "node:fs";
import { loadProjectEnv } from "./scripts/load-project-env.mjs";
import { createServer } from "node:http";
import { extname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const modulePath = fileURLToPath(import.meta.url);
const projectRoot = resolve(fileURLToPath(new URL(".", import.meta.url)));
const websiteRoot = join(projectRoot, "website");
const distRoot = join(websiteRoot, "dist");
const root = existsSync(distRoot) ? distRoot : websiteRoot;
const publicRoot = existsSync(distRoot) ? distRoot : join(websiteRoot, "public");
loadProjectEnv();
const port = Number(process.env.PORT || 5173);
const defaultRoot = existsSync(distRoot) ? distRoot : websiteRoot;
const defaultPublicRoot = existsSync(distRoot) ? distRoot : join(websiteRoot, "public");
const types = {
".html": "text/html; charset=utf-8",
@ -33,11 +30,11 @@ function isInsideRoot(parent, file) {
return Boolean(relativePath) && !relativePath.startsWith("..") && !relativePath.startsWith("/");
}
function fileIfReadable(file) {
return isInsideRoot(root, file) && existsSync(file) && statSync(file).isFile() ? file : null;
function fileIfReadable(parent, file) {
return isInsideRoot(parent, file) && existsSync(file) && statSync(file).isFile() ? file : null;
}
function resolvePath(url) {
function resolvePath(url, root, publicRoot) {
let requested;
try {
requested = decodeURIComponent(new URL(url, "http://localhost").pathname);
@ -45,46 +42,68 @@ function resolvePath(url) {
return null;
}
const candidate = fileIfReadable(resolve(root, `.${requested}`));
const candidate = fileIfReadable(root, resolve(root, `.${requested}`));
if (candidate) return candidate;
const publicCandidate = fileIfReadable(resolve(publicRoot, `.${requested}`));
if (publicCandidate && isInsideRoot(publicRoot, publicCandidate)) return publicCandidate;
const publicCandidate = fileIfReadable(publicRoot, resolve(publicRoot, `.${requested}`));
if (publicCandidate) return publicCandidate;
return extname(requested) ? null : join(root, "index.html");
}
const server = createServer((req, res) => {
const file = resolvePath(req.url || "/");
if (!file || !existsSync(file)) {
res.writeHead(404);
res.end("Not found");
return;
}
function isVersionedAsset(root, file) {
const relativePath = relative(root, file).replaceAll("\\", "/");
const fileName = relativePath.split("/").at(-1) || "";
return relativePath.startsWith("assets/") && /-[a-z0-9_-]{8,}\.[^.]+(?:\.map)?$/i.test(fileName);
}
function getCacheControl(root, file) {
const extension = extname(file);
const cacheControl = extension === ".html"
? "no-store"
: extension === ".json"
? "no-cache"
: "public, max-age=31536000, immutable";
res.writeHead(200, {
"Content-Type": types[extname(file)] || "application/octet-stream",
"Cache-Control": cacheControl
if (extension === ".html") return "no-store";
if (extension === ".json") return "no-cache";
if (isVersionedAsset(root, file)) return "public, max-age=31536000, immutable";
return "no-cache";
}
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot } = {}) {
return createServer((req, res) => {
const file = resolvePath(req.url || "/", root, publicRoot);
if (!file || !existsSync(file)) {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-store"
});
res.end("Not found");
return;
}
res.writeHead(200, {
"Content-Type": types[extname(file)] || "application/octet-stream",
"Cache-Control": getCacheControl(root, file)
});
createReadStream(file).pipe(res);
});
createReadStream(file).pipe(res);
});
}
server.on("error", (error) => {
if (error.code === "EADDRINUSE") {
console.error(`Port ${port} is already in use. Set PORT to another value.`);
export function startServer() {
loadProjectEnv();
const port = Number(process.env.PORT || 5173);
const server = createStaticServer();
server.on("error", (error) => {
if (error.code === "EADDRINUSE") {
console.error(`Port ${port} is already in use. Set PORT to another value.`);
process.exit(1);
}
console.error(error);
process.exit(1);
}
});
console.error(error);
process.exit(1);
});
server.listen(port, () => {
console.log(`Sokko G dev server running at http://localhost:${port}`);
});
return server;
}
server.listen(port, () => {
console.log(`Sokko G dev server running at http://localhost:${port}`);
});
if (process.argv[1] && resolve(process.argv[1]) === modulePath) startServer();

View file

@ -0,0 +1,67 @@
// Rôle : vérifie les en-têtes de cache du serveur Node sur des fichiers de production représentatifs.
import { mkdir, mkdtemp, 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");
});