Runner: index.html-Rueckfall wie bisheriger Deploy (Kandidat/Platzhalter/Unterordner)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Sonnet 5.5 committed 2026-09-30 22:15:27 +00:00
1 parent 54f307d12a
commit 8a028ce75a
7 files changed
+294 -10

No files matched your search

+2 -1
View File
@@ -50,7 +50,8 @@ export function detectProject(files, { mode, index, previewJson } = {}) {
const devPort = Number.isInteger(pj.devPort) && pj.devPort >= 1024 && pj.devPort <= 65535 ? pj.devPort : DEFAULT_PORT;
const outputDirs = safeRel(pj.output) ? [pj.output] : [...DEFAULT_OUTPUTS];
const indexFile = [index, pj.index].find(safeRel) || 'index.html';
const hasIndex = files.has(indexFile);
// index darf Datei ODER (wie im bisherigen Deploy) Unterordner mit index.html sein
const hasIndex = files.has(indexFile) || files.has(`${indexFile.replace(/\/+$/, '')}/index.html`);
const hasBuild = hasScript(scripts, 'build');
const hasDev = hasScript(scripts, 'dev');
const m = mode === 'build' || mode === 'dev' ? mode : 'auto';
+98 -6
View File
@@ -23,11 +23,12 @@ async function chownR(p) {
}
// Kopiert nur Verzeichnisse und reguläre Dateien (keine Symlinks, nie .git), Rechte 755/644 (R7).
async function copyTree(fs, src, dst, { skipGit = false } = {}) {
async function copyTree(fs, src, dst, { skipGit = false, skipNodeModules = false } = {}) {
await fs.mkdir(dst, { recursive: true });
await fs.chmod(dst, 0o755);
for (const e of await fs.readdir(src, { withFileTypes: true })) {
if (skipGit && e.name === '.git') continue;
if (skipNodeModules && e.name === 'node_modules') continue;
const s = join(src, e.name);
const d = join(dst, e.name);
if (e.isDirectory()) await copyTree(fs, s, d);
@@ -43,6 +44,76 @@ async function dirSize(fs, p) {
return sum;
}
// ---- index.html-Rückfall (1:1 aus server/services/previewDeploy.js, Runner kann Portalcode nicht importieren) ----
function placeholderHtml(displayName) {
const name = String(displayName || 'Diese Website')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
return `<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>${name} – wird vorbereitet</title>
<style>
html,body{height:100%;margin:0}
body{display:flex;align-items:center;justify-content:center;
font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
background:#0f172a;color:#e2e8f0}
.box{max-width:32rem;padding:2rem;text-align:center}
h1{font-size:1.4rem;margin:0 0 .75rem}
p{margin:0;color:#94a3b8;line-height:1.5}
</style>
</head>
<body>
<div class="box">
<h1>${name}</h1>
<p>Diese Seite wird gerade vorbereitet oder aktualisiert.<br>Bitte in Kürze erneut laden.</p>
</div>
</body>
</html>
`;
}
async function findIndexCandidate(fs, dir) {
let entries = [];
try { entries = await fs.readdir(dir, { withFileTypes: true }); } catch { return null; }
const htmlFiles = entries
.filter((e) => e.isFile() && /\.html?$/i.test(e.name) && !e.name.startsWith('.'))
.map((e) => e.name)
.filter((name) => name.toLowerCase() !== 'index.html');
if (!htmlFiles.length) return null;
const preferred = ['index.htm', 'home.html', 'homepage.html', 'main.html', 'start.html', 'app.html'];
for (const want of preferred) {
const hit = htmlFiles.find((name) => name.toLowerCase() === want);
if (hit) return hit;
}
if (htmlFiles.length === 1) return htmlFiles[0];
const sized = await Promise.all(htmlFiles.map(async (name) => {
try { return { name, size: (await fs.stat(join(dir, name))).size }; } catch { return { name, size: 0 }; }
}));
sized.sort((a, b) => b.size - a.size);
return sized[0].name;
}
// Stellt sicher, dass dir/index.html existiert: Kandidat (Kopie) oder Platzhalter; vorhandene index.html bleibt unberührt.
async function ensureIndexHtml(fs, dir, displayName, onLine) {
const indexPath = join(dir, 'index.html');
try { await fs.access(indexPath); return; } catch { /* keine index.html */ }
const candidate = await findIndexCandidate(fs, dir);
if (candidate) {
await fs.copyFile(join(dir, candidate), indexPath);
await fs.chmod(indexPath, 0o644);
onLine?.(`keine index.html – "${candidate}" als Startseite übernommen`);
return;
}
await fs.writeFile(indexPath, placeholderHtml(displayName), 'utf8');
await fs.chmod(indexPath, 0o644);
onLine?.('keine HTML-Datei gefunden – Platzhalter-Startseite geschrieben');
}
const defaultFs = { ...nodeFs, chownR, copyTree, dirSize: (p) => dirSize(nodeFs, p) };
// ---- git (R11) ----
@@ -167,7 +238,7 @@ export function createJobs({ config, docker, fs: fsOver = {}, git, mem = readMem
}
// ---- Atomare Veröffentlichung (R11) ----
async function publish(job, srcDir, { skipGit, onLine }) {
async function publish(job, srcDir, { skipGit, onLine, skipNodeModules = false }) {
const target = join(config.previewsRoot, job.sub);
const fresh = `${target}.new`;
const old = `${target}.old`;
@@ -179,7 +250,8 @@ export function createJobs({ config, docker, fs: fsOver = {}, git, mem = readMem
let hadOld = true;
try {
await fs.mkdir(config.previewsRoot, { recursive: true });
await fs.copyTree(fs, srcDir, fresh, { skipGit });
await fs.copyTree(fs, srcDir, fresh, { skipGit, skipNodeModules });
await ensureIndexHtml(fs, fresh, job.displayName || job.sub, onLine);
try { await fs.rename(target, old); } catch (e) { if (e.code !== 'ENOENT') throw e; hadOld = false; }
try { await fs.rename(fresh, target); } catch (e) {
if (hadOld) await fs.rename(old, target).catch((e2) => onLine?.(`Rollback fehlgeschlagen: ${e2.message}`));
@@ -202,12 +274,26 @@ export function createJobs({ config, docker, fs: fsOver = {}, git, mem = readMem
if (!st.isDirectory()) continue;
const real = await fs.realpath(p);
if (real === realWork || !real.startsWith(realWork + sep)) continue;
await fs.access(join(p, 'index.html')); // wie bisher: nur Ausgabeordner mit index.html zählen
return p;
} catch { /* nicht vorhanden */ }
} catch { /* nicht vorhanden / ohne index.html */ }
}
return null;
}
// Webroot der statischen Seite: index-Unterordner (wie bisher), sonst Repo-Wurzel; fehlender/unsicherer Ordner ⇒ Wurzel.
async function webrootOf(workDir, sub) {
if (!sub) return workDir;
try {
const p = join(workDir, sub);
if (!(await fs.lstat(p)).isDirectory()) return workDir;
const real = await fs.realpath(p);
const realWork = await fs.realpath(workDir);
if (real === realWork || !real.startsWith(realWork + sep)) return workDir;
return p;
} catch { return workDir; }
}
// ---- Ablauf eines Build-Laufs ----
const execute = (run, job) => holdCache(job.repo, () => executeRun(run, job));
async function executeRun(run, job) {
@@ -224,7 +310,7 @@ export function createJobs({ config, docker, fs: fsOver = {}, git, mem = readMem
if (prep.error) throw new Error(prep.error);
if (d.kind === 'static') {
if (d.hint) onLine(d.hint);
await publish(job, workDir, { skipGit: true, onLine });
await publish(job, await webrootOf(workDir, job.index || ''), { skipGit: true, onLine });
run.result = 'static';
} else if (d.kind === 'dev') {
run.result = 'dev';
@@ -240,7 +326,13 @@ export function createJobs({ config, docker, fs: fsOver = {}, git, mem = readMem
}
if (problem) {
if (job.mode === 'auto' && d.devCmd) { onLine(`${problem} – Dev-Server wird verwendet`); run.result = 'dev'; }
else throw new Error(problem);
else if (!out && !r.code && job.mode !== 'build') {
// Build lief, erzeugte aber keinen Ausgabeordner mit index.html: wie bisher den Quellstand statisch
// veröffentlichen (index-Unterordner, Kandidat/Platzhalter) statt die Subdomain zu verlieren.
onLine(`${problem} – Quellstand wird statisch veröffentlicht`);
await publish(job, await webrootOf(workDir, job.index || ''), { skipGit: true, skipNodeModules: true, onLine });
run.result = 'static';
} else throw new Error(problem);
} else {
await publish(job, out, { skipGit: false, onLine });
run.result = 'build';
+8
View File
@@ -26,6 +26,13 @@ export function validateJob(body) {
}
index = i;
}
let displayName;
if (body.displayName !== undefined && body.displayName !== '') {
const d = body.displayName;
// eslint-disable-next-line no-control-regex
if (typeof d !== 'string' || d.length > 100 || /[\x00-\x1f\x7f]/.test(d)) return { ok: false, error: 'Ungültiger Anzeigename' };
displayName = d;
}
const env = {};
if (body.env !== undefined) {
if (!body.env || typeof body.env !== 'object' || Array.isArray(body.env)) return { ok: false, error: 'Ungültige Variablen' };
@@ -41,5 +48,6 @@ export function validateJob(body) {
// Whitelist: keine ungeprüften Client-Felder im Job
const job = { sub, repo, sha, branch, mode, env };
if (index !== undefined) job.index = index;
if (displayName !== undefined) job.displayName = displayName;
return { ok: true, job };
}
+107
View File
@@ -0,0 +1,107 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createJobs } from '../src/jobs.js';
import { validateJob } from '../src/validate.js';
function setup({ files, dockerImpl }) {
const root = mkdtempSync(join(tmpdir(), 'idx-'));
const config = { giteaUrl: 'https://git.x', giteaToken: 'tok_SECRET_123456', previewsRoot: join(root, 'previews'), workRoot: join(root, 'work'), cacheRoot: join(root, 'cache'), minFreeBytes: 1000, buildTimeoutMs: 900000 };
const git = async ({ dir }) => { for (const [f, c] of Object.entries(files)) { mkdirSync(join(dir, f, '..'), { recursive: true }); writeFileSync(join(dir, f), c); } mkdirSync(join(dir, '.git'), { recursive: true }); writeFileSync(join(dir, '.git', 'config'), 'x'); };
const docker = { run: async (args) => (dockerImpl ? dockerImpl(args) : { code: 0 }) };
const jobs = createJobs({ config, docker, git, mem: () => 1e10, fs: { chownR: async () => {} }, setTimer: () => {} });
return { config, jobs, out: join(config.previewsRoot, 'demo') };
}
const job = (o = {}) => ({ sub: 'demo', repo: 'own/rep', sha: 'abcdef1', branch: 'main', mode: 'auto', env: {}, ...o });
const wait = async (jobs, id) => { for (let i = 0; i < 400; i++) { const r = jobs.get(id); if (r.state === 'done' || r.state === 'failed') return r; await new Promise((r2) => setTimeout(r2, 5)); } throw new Error('timeout'); };
const workOf = (args) => args.find((a) => a.endsWith(':/work')).split(':')[0];
test('Doener-Fall: nur Doener_Nation_Website.html ⇒ index.html ist Byte-Kopie, Original bleibt', async () => {
const html = Buffer.from('<!doctype html><title>Döner</title>äö\n');
const s = setup({ files: { 'Doener_Nation_Website.html': html, '.webklar-preview.json': '{}' } });
const r = await wait(s.jobs, s.jobs.submit(job()));
assert.equal(r.state, 'done');
assert.deepEqual(readFileSync(join(s.out, 'index.html')), html);
assert.deepEqual(readFileSync(join(s.out, 'Doener_Nation_Website.html')), html);
assert.equal(statSync(join(s.out, 'index.html')).mode & 0o777, 0o644);
});
test('vorhandene index.html bleibt unberührt', async () => {
const s = setup({ files: { 'index.html': 'ORIG', 'home.html': 'HOME' } });
await wait(s.jobs, s.jobs.submit(job()));
assert.equal(readFileSync(join(s.out, 'index.html'), 'utf8'), 'ORIG');
});
test('bevorzugter Name gewinnt, sonst größte Datei', async () => {
let s = setup({ files: { 'a.html': 'aaaa', 'Main.html': 'm', 'zz.html': 'zzzzzzzz' } });
await wait(s.jobs, s.jobs.submit(job()));
assert.equal(readFileSync(join(s.out, 'index.html'), 'utf8'), 'm');
s = setup({ files: { 'a.html': 'aaaa', 'b.htm': 'bbbbbbbbb', 'c.html': 'c' } });
await wait(s.jobs, s.jobs.submit(job()));
assert.equal(readFileSync(join(s.out, 'index.html'), 'utf8'), 'bbbbbbbbb');
});
test('index-Unterordner wird Webroot; fehlender Ordner ⇒ Repo-Wurzel', async () => {
let s = setup({ files: { 'public/index.html': 'PUB', 'x.html': 'root' } });
let r = await wait(s.jobs, s.jobs.submit(job({ index: 'public' })));
assert.equal(r.state, 'done');
assert.deepEqual(readdirSync(s.out), ['index.html']);
s = setup({ files: { 'x.html': 'root' } });
await wait(s.jobs, s.jobs.submit(job({ index: 'gibtsnicht' })));
assert.equal(readFileSync(join(s.out, 'index.html'), 'utf8'), 'root');
});
test('kein HTML ⇒ Platzhalter mit Anzeigename (maskiert)', async () => {
const s = setup({ files: { 'readme.txt': 'x' } });
await wait(s.jobs, s.jobs.submit(job({ displayName: 'A & <B>' })));
const h = readFileSync(join(s.out, 'index.html'), 'utf8');
assert.match(h, /<h1>A &amp; &lt;B&gt;<\/h1>/);
assert.match(h, /<title>A &amp; &lt;B&gt; – wird vorbereitet<\/title>/);
const s2 = setup({ files: { 'readme.txt': 'x' } });
await wait(s2.jobs, s2.jobs.submit(job()));
assert.match(readFileSync(join(s2.out, 'index.html'), 'utf8'), /<h1>demo<\/h1>/);
});
test('Build ohne index.html im Ausgabeordner ⇒ Quellstand statisch + Kandidat/Platzhalter', async () => {
const s = setup({
files: { 'package.json': JSON.stringify({ scripts: { build: 'x' } }), 'seite.html': 'SEITE' },
dockerImpl: (args) => { if (args.includes('build')) { mkdirSync(join(workOf(args), 'dist'), { recursive: true }); writeFileSync(join(workOf(args), 'dist', 'app.js'), 'x'); mkdirSync(join(workOf(args), 'node_modules'), { recursive: true }); writeFileSync(join(workOf(args), 'node_modules', 'm.js'), 'x'); } return { code: 0 }; },
});
const r = await wait(s.jobs, s.jobs.submit(job()));
assert.equal(r.state, 'done'); assert.equal(r.result, 'static');
assert.equal(readFileSync(join(s.out, 'index.html'), 'utf8'), 'SEITE');
assert.ok(!existsSync(join(s.out, 'node_modules')));
const s2 = setup({
files: { 'package.json': JSON.stringify({ scripts: { build: 'x' } }) },
dockerImpl: (args) => { if (args.includes('build')) mkdirSync(join(workOf(args), 'dist'), { recursive: true }); return { code: 0 }; },
});
await wait(s2.jobs, s2.jobs.submit(job({ displayName: 'Shop' })));
assert.match(readFileSync(join(s2.out, 'index.html'), 'utf8'), /<h1>Shop<\/h1>/);
});
test('Build-Ausgabe mit index.html wird unverändert veröffentlicht', async () => {
const s = setup({
files: { 'package.json': JSON.stringify({ scripts: { build: 'x' } }) },
dockerImpl: (args) => { if (args.includes('build')) { mkdirSync(join(workOf(args), 'dist'), { recursive: true }); writeFileSync(join(workOf(args), 'dist', 'index.html'), 'B'); writeFileSync(join(workOf(args), 'dist', 'o.html'), 'O'); } return { code: 0 }; },
});
const r = await wait(s.jobs, s.jobs.submit(job()));
assert.equal(r.result, 'build');
assert.deepEqual(readdirSync(s.out).sort(), ['index.html', 'o.html']);
});
test('fehlgeschlagener Build bleibt ein Fehler (alter Stand bleibt)', async () => {
const s = setup({ files: { 'package.json': JSON.stringify({ scripts: { build: 'x' } }) }, dockerImpl: (args) => ({ code: args.includes('build') ? 1 : 0 }) });
const r = await wait(s.jobs, s.jobs.submit(job()));
assert.equal(r.state, 'failed');
});
test('validateJob: displayName optional, ≤100 Zeichen, keine Steuerzeichen', () => {
const good = { sub: 'a', repo: 'o/r', sha: 'abcdef1', branch: 'main' };
assert.equal(validateJob({ ...good, displayName: 'Döner Nation' }).job.displayName, 'Döner Nation');
assert.equal('displayName' in validateJob(good).job, false);
assert.equal(validateJob({ ...good, displayName: 'x'.repeat(101) }).ok, false);
assert.equal(validateJob({ ...good, displayName: 'a\nb' }).ok, false);
assert.equal(validateJob({ ...good, displayName: 5 }).ok, false);
});