feat(cms): optimistic locking against stale-tab overwrites
CI Pipeline with Test Management / 🧪 Run Tests & Generate Reports (push) Waiting to run
CI Pipeline with Test Management / 🐳 Docker Integration Tests (push) Blocked by required conditions
CI Pipeline with Test Management / 🏗️ Build Docker Image (push) Blocked by required conditions
CI Pipeline with Test Management / 📊 Generate Test Summary (push) Blocked by required conditions
Test Reporting & Gherkin Analysis / 🧪 Run Tests & Generate Reports (push) Waiting to run
Test Reporting & Gherkin Analysis / 📊 Analyze Test Coverage (push) Blocked by required conditions
Test Reporting & Gherkin Analysis / 🔄 Sync with Linear (push) Blocked by required conditions
Test Reporting & Gherkin Analysis / ⚡ Performance Monitoring (push) Blocked by required conditions

A Content Editor tab left open across a deploy (or a save from another tab)
held the pre-deploy content; one Save would silently overwrite the newer
file. The editor page now embeds a SHA-256 fingerprint of the file content
at load time, /save requires it back in X-Content-Hash and compares against
the current file: mismatch (or a missing header) answers 409 with an
explanatory message and writes nothing. The client offers a reload on 409.

Integration test covers: matching hash saves, stale hash rejected with the
file untouched, missing hash rejected, retry with the fresh hash succeeds.

Closes MITHOME-61
This commit is contained in:
Do Siki
2026-08-18 20:57:08 +02:00
parent bdf9aac4d0
commit 3818859cc5
6 changed files with 157 additions and 4 deletions
+7 -1
View File
@@ -233,10 +233,16 @@ async function save() {
const data = collect();
const res = await fetch('/save?file=' + FILE, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': CSRF_TOKEN },
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': CSRF_TOKEN, 'X-Content-Hash': CONTENT_HASH },
body: JSON.stringify(data, null, 2)
});
if (res.status === 401) { location.href = '/login'; return; }
if (res.status === 409) {
if (confirm('A tartalom megváltozott, mióta ez a lap megnyílt (pl. deploy vagy másik fül mentett).\n\nOK = lap frissítése az új tartalommal (a szerkesztésed elvész)\nMégse = maradsz ezen a lapon, a mentés nem történt meg.')) {
location.reload();
}
return;
}
const json = await res.json();
const status = document.getElementById('saveStatus');
if (json.ok) {
+2 -1
View File
@@ -4,7 +4,7 @@
const isStaging = () => process.env.CMS_DEPLOY_ENV === 'staging';
// FILE_LABELS is injected to avoid a circular dependency with the main file.
const HTML = (activeFile, jsonData, message, csrfToken, fileLabels, clientJs) => `<!DOCTYPE html>
const HTML = (activeFile, jsonData, message, csrfToken, fileLabels, clientJs, contentHash) => `<!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-8">
@@ -120,6 +120,7 @@ ${message ? `<div class="toast ${message.type === 'ok' ? 'ok' : 'err'}">${messag
const DATA = JSON.parse(document.getElementById('page-data').textContent);
const FILE = "${activeFile}";
const CSRF_TOKEN = "${csrfToken}";
const CONTENT_HASH = "${contentHash}";
${clientJs}
</script>
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env node
/**
* Integration test for optimistic locking on CMS save (MITHOME-61):
* 1. save with the correct X-Content-Hash → 200
* 2. save with a stale hash (file changed on disk meanwhile) → 409, file untouched
* 3. save without any hash header → 409 (strict: must always send the fingerprint)
* 4. a follow-up save with the NEW hash succeeds → the editor can continue after refresh
*/
const assert = require('assert/strict');
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const ROOT = path.join(__dirname, '..');
const PORT = 4128;
const BASE = `http://127.0.0.1:${PORT}`;
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cms-conflict-'));
const auditFile = path.join(tmp, 'audit.jsonl');
const child = spawn('node', ['content-editor.js'], {
cwd: ROOT,
env: {
...process.env,
CONTENT_EDITOR_PORT: String(PORT),
CONTENT_EDITOR_AUDIT_FILE: auditFile,
CMS_USER: 'conflict-test-user',
CMS_PASS: 'conflict-test-pass',
CMS_DEPLOY_ENV: 'staging',
},
stdio: 'ignore',
});
async function waitForServer(timeoutMs = 10000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
await fetch(`${BASE}/logout`);
return;
} catch {
await new Promise(r => setTimeout(r, 200));
}
}
throw new Error('server did not start');
}
const hashOf = s => crypto.createHash('sha256').update(s.trim()).digest('hex');
async function call(method, pathName, { body, headers } = {}) {
const login = await fetch(`${BASE}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user: 'conflict-test-user', pass: 'conflict-test-pass' }),
});
const cookie = (login.headers.get('set-cookie') || '').split(';')[0];
if (method === 'GET') {
return fetch(`${BASE}${pathName}`, { headers: { Cookie: cookie, ...headers } });
}
const page = await (await fetch(`${BASE}${pathName.split('?')[0] || '/'}?file=contact`, { headers: { Cookie: cookie } })).text();
const csrf = page.match(/CSRF_TOKEN = "([a-f0-9]+)"/)[1];
return fetch(`${BASE}${pathName}`, { method, headers: { Cookie: cookie, 'X-CSRF-Token': csrf, ...headers }, body });
}
async function main() {
await waitForServer();
const contentFile = path.join(ROOT, 'proto', 'src', 'content', 'pages', 'contact.json');
// Baseline: read the page and capture the served fingerprint
const page = await (await call('GET', '/?file=contact')).text();
const servedHash = page.match(/const CONTENT_HASH = "([a-f0-9]+)"/)[1];
const diskBefore = fs.readFileSync(contentFile, 'utf8');
assert.equal(servedHash, hashOf(diskBefore), 'served fingerprint matches the file on disk');
const payload = diskBefore; // unchanged content is still a valid save payload
const jsonHeaders = { 'Content-Type': 'application/json' };
// 1. correct hash → 200
const ok = await call('POST', '/save?file=contact', {
headers: { ...jsonHeaders, 'X-Content-Hash': servedHash },
body: payload,
});
assert.equal(ok.status, 200);
// 2. stale hash: simulate the file changing on disk (deploy/other tab)
const savedContact = fs.readFileSync(contentFile, 'utf8'); // keep the exact bytes
try {
fs.writeFileSync(contentFile, diskBefore.replace('"responseTime"', '"responseTime" /*changed*/'));
const stale = await call('POST', '/save?file=contact', {
headers: { ...jsonHeaders, 'X-Content-Hash': servedHash },
body: payload,
});
assert.equal(stale.status, 409);
const body = await stale.json();
assert.match(body.error, /megváltozott/);
// file untouched by the rejected save (still the "changed" variant)
assert.ok(fs.readFileSync(contentFile, 'utf8').includes('/*changed*/'));
} finally {
fs.writeFileSync(contentFile, savedContact); // restore
}
// 3. missing hash → 409 (strict)
const noHash = await call('POST', '/save?file=contact', {
headers: jsonHeaders,
body: payload,
});
assert.equal(noHash.status, 409);
// 4. save with the fresh hash of the restored file succeeds
const freshHash = hashOf(fs.readFileSync(contentFile, 'utf8'));
const retry = await call('POST', '/save?file=contact', {
headers: { ...jsonHeaders, 'X-Content-Hash': freshHash },
body: payload,
});
assert.equal(retry.status, 200);
console.log('Content Editor optimistic-lock test: OK');
}
main()
.catch(err => { console.error('❌', err.message); process.exitCode = 1; })
.finally(() => {
child.kill('SIGTERM');
try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ }
});
+2 -1
View File
@@ -25,7 +25,8 @@ const fixture = {
sections: [{ id: 'first', items: ['egy', 'kettő'], settings: { visible: false, weight: 1 } }],
};
const clientJs = fs.readFileSync('scripts/cms-editor-client.js', 'utf8');
const html = serverContext.globalThis.renderContentEditor('home', JSON.stringify(fixture), null, 'csrf-test-token', { common: '⚙️ Közös' }, clientJs);
const html = serverContext.globalThis.renderContentEditor('home', JSON.stringify(fixture), null, 'csrf-test-token', { common: '⚙️ Közös' }, clientJs, 'hash-test-value');
assert.ok(html.includes('const CONTENT_HASH = "hash-test-value"'));
const browserSource = [...html.matchAll(/<script(?: [^>]*)?>([\s\S]*?)<\/script>/g)].at(-1)[1]
.replace("render(DATA, document.getElementById('editor'));", '')
.replace("const toast = document.querySelector('.toast');", 'const toast = null;');