#!/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'); const original = fs.readFileSync(contentFile, 'utf8'); 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]; const csrfPage = await (await fetch(`${BASE}/?file=contact`, { headers: { Cookie: cookie } })).text(); const csrf = csrfPage.match(/CSRF_TOKEN = "([a-f0-9]+)"/)[1]; // Baseline: read the page and capture the served fingerprint const page = await (await call('GET', '/?file=contact')).text(); const servedHash = page.match(/let 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' }; // MITHOME-68: the save response returns the new content hash; a tab that // adopts it can save again — only a genuinely external change may 409. const v3 = JSON.parse(original); v3.hero.subtitle = 'Hash frissítés teszt ' + Date.now(); const first = await fetch(`${BASE}/save?file=contact`, { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-CSRF-Token': csrf, 'X-Content-Hash': hashOf(fs.readFileSync(contentFile, 'utf8')), }, body: JSON.stringify(v3, null, 2), }); assert.equal(first.status, 200); const firstBody = await first.json(); assert.match(firstBody.contentHash, /^[a-f0-9]{64}$/, 'save must return the new content hash'); // same tab continues with the returned hash → 200 const again = await fetch(`${BASE}/save?file=contact`, { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-CSRF-Token': csrf, 'X-Content-Hash': firstBody.contentHash, }, body: JSON.stringify(v3, null, 2), }); assert.equal(again.status, 200, 'save with the refreshed hash must succeed'); // a stale (pre-save) hash still 409s const stale = await fetch(`${BASE}/save?file=contact`, { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-CSRF-Token': csrf, 'X-Content-Hash': hashOf(original), }, body: JSON.stringify(v3, null, 2), }); assert.equal(stale.status, 409, 'stale hash must still be rejected'); // leave the disk as the following sections expect it fs.writeFileSync(contentFile, original); // 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 */ } });