Feat(site): rendu serveur PHP — paquets en SQLite, releases Gitea, build ISO

- Front controller page.php + inc/site.php : coquille et pages rendues
  en PHP (accueil, dl, paquets, paquets/N, equipe, contact, 404) ; les
  URLs ne changent pas et l'apparence est conservée.
- Paquets stockés dans la base SQLite partagée (table packages),
  éditables depuis l'onglet 📦 Paquets de /admin/bugs, avec bouton de
  synchronisation des releases depuis l'API Gitea du dépôt lié.
  Repli automatique sur packages.json si la base est vide.
- Releases ISO de la page Téléchargements récupérées côté serveur
  (Gitea FWS/ISO sinon GitHub) avec cache fichier 10 min ; note de
  release rendue en Markdown serveur (Voir plus / Voir moins).
- Suppression du routeur SPA et des chargeurs JS devenus inutiles
  (app.js, packages.js, downloads.js, creators-loader.js, index.html) ;
  restent nav.js, note-toggle.js et hero-carousel.js.
- Panneau admin : onglet Build ISO (git pull sur main, build.sh avec
  repli setup-aur.sh, terminal des logs en direct), durcissement UTF-8
  à l'écriture des paquets (json_encode ne casse plus sur des accents
  mal encodés), 404 réels et gardes d'accès direct sur les corps PHP.
This commit is contained in:
BlackAngelTV committed 2026-09-14 13:19:37 +02:00
1 parent 34b3f1cf3c
commit 1775adceaa
34 files changed
+2799 -1862

No files matched your search

+558
View File
@@ -0,0 +1,558 @@
<?php
/**
* FWS — Onglet « Build ISO » du panneau admin des signalements.
*
* URL : admin/bugs/build.php
*
* Réservé aux comptes autorisés (voir fws_bugs_can_build() dans
* api/bugs/db.php, par défaut : « admin »). Lance le pipeline
* admin/bugs/run-build.sh dans un process détaché (nohup) et expose un
* mini-terminal : les logs sont lus en direct par polling (act=tail) et les
* actions start / stop / clear sont protégées par CSRF comme le reste du
* panneau.
*/
declare(strict_types=1);
require_once __DIR__ . '/../../api/bugs/db.php';
session_set_cookie_params([
'httponly' => true,
'samesite' => 'Lax',
'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'),
]);
session_start();
function h_build(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
function current_user_build(): ?array
{
return isset($_SESSION['admin_user_id']) ? [
'id' => (int) $_SESSION['admin_user_id'],
'name' => (string) $_SESSION['admin_username'],
] : null;
}
function csrf_token_build(): string
{
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf'];
}
function csrf_ok_build(): bool
{
return hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '');
}
/** Lecture du token Gitea stocké localement (api/bugs/data/build/git-auth.env, jamais commité). */
function build_gitea_auth_build(): array
{
global $DATA;
$f = $DATA . '/git-auth.env';
$out = ['username' => '', 'token' => ''];
if (is_file($f)) {
$s = (string) file_get_contents($f);
if (preg_match("/^FWS_GIT_USER='([^']*)'$/m", $s, $m) === 1) {
$out['username'] = $m[1];
}
if (preg_match("/^FWS_GIT_TOKEN='([^']*)'$/m", $s, $m) === 1) {
$out['token'] = $m[1];
}
}
return $out;
}
/** Écriture du token Gitea (token vide → fichier retiré). */
function build_save_gitea_auth_build(string $username, string $token): void
{
global $DATA;
if (!is_dir($DATA)) {
@mkdir($DATA, 0775, true);
}
$f = $DATA . '/git-auth.env';
if ($token === '') {
@unlink($f);
return;
}
$sq = static fn(string $v): string => str_replace(["\\", "'"], ["\\\\", "\\'"], $v);
file_put_contents(
$f,
"FWS_GIT_USER='" . $sq($username !== '' ? $username : 'fws') . "'\n" .
"FWS_GIT_TOKEN='" . $sq($token) . "'\n",
LOCK_EX
);
@chmod($f, 0600);
}
/* ── Chemins (sous api/bugs/data/, jamais commité) ── */
$DATA = __DIR__ . '/../../api/bugs/data/build';
$LOG = $DATA . '/build.log';
$PIDF = $DATA . '/build.pid';
$RUN = __DIR__ . '/run-build.sh';
$user = current_user_build();
/** PID du process de build s'il tourne encore, sinon false. */
function build_running_build(): int|false
{
global $PIDF;
$pid = is_file($PIDF) ? trim((string) file_get_contents($PIDF)) : '';
if ($pid === '' || !ctype_digit($pid)) {
return false;
}
exec('kill -0 ' . (int) $pid . ' 2>/dev/null', $out, $rc);
return $rc === 0 ? (int) $pid : false;
}
/** Dernier code de sortie du pipeline lu dans le log (null si pas encore terminé). */
function build_last_rc_build(): ?int
{
global $LOG;
if (!is_file($LOG) || filesize($LOG) === 0) {
return null;
}
$tail = (string) file_get_contents($LOG, false, null, max(0, filesize($LOG) - 4096));
if (preg_match('/Fin du pipeline \(code (-?\d+)\)/', $tail, $m) === 1) {
return (int) $m[1];
}
return null;
}
/* ───────────────────────── API (act=…) ───────────────────────── */
$act = $_GET['act'] ?? $_POST['act'] ?? '';
$isApi = $act !== '';
if ($isApi) {
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
if ($user === null) {
http_response_code(401);
exit(json_encode(['ok' => false, 'error' => 'Non connecté.']));
}
if (!fws_bugs_can_build($user['name'])) {
http_response_code(403);
exit(json_encode(['ok' => false, 'error' => 'Ce compte n’est pas autorisé à lancer des builds.']));
}
$running = build_running_build();
if ($act === 'state') {
echo json_encode(['ok' => true, 'running' => $running !== false, 'pid' => $running]);
exit;
}
if ($act === 'auth_status') {
$a = build_gitea_auth_build();
echo json_encode(['ok' => true, 'configured' => $a['token'] !== '', 'username' => $a['username']]);
exit;
}
if ($act === 'tail') {
$pos = max(-1, (int) ($_GET['pos'] ?? 0));
$size = is_file($LOG) ? (int) filesize($LOG) : 0;
$start = 0;
if ($pos === -1) {
// Premier chargement : ne ramener que la fin d'un éventuel vieux log.
$start = max(0, $size - 150000);
} elseif ($pos > 0 && $pos <= $size) {
$start = $pos;
}
$text = '';
if ($size > $start) {
$fh = fopen($LOG, 'rb');
if ($fh !== false) {
if ($start > 0) {
fseek($fh, $start);
}
$raw = (string) stream_get_contents($fh);
fclose($fh);
// Nettoyage : codes ANSI retirés, octets invalides ignorés.
$text = (string) preg_replace('/\x1B\[[0-9;?]*[ -\/]*[@-~]/', '', $raw);
$text = (string) preg_replace('/\x1B\][^\x07\x1B]*(\x07|\x1B\\)/', '', $text);
$text = iconv('UTF-8', 'UTF-8//IGNORE', $text);
}
}
$running = build_running_build();
echo json_encode([
'ok' => true,
'running' => $running !== false,
'pos' => (int) $size,
'rc' => build_last_rc_build(),
'text' => $text,
]);
exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !csrf_ok_build()) {
http_response_code(403);
exit(json_encode(['ok' => false, 'error' => 'Jeton de sécurité invalide.']));
}
if ($act === 'start') {
if ($running !== false) {
http_response_code(409);
exit(json_encode(['ok' => false, 'error' => 'Un build est déjà en cours.']));
}
exec('timeout 8 docker info >/dev/null 2>&1', $out, $drc);
if ($drc !== 0) {
http_response_code(503);
exit(json_encode(['ok' => false, 'error' => 'Moteur Docker injoignable (Docker Desktop arrêté ?).']));
}
if (!is_dir($DATA) && !@mkdir($DATA, 0775, true)) {
http_response_code(500);
exit(json_encode(['ok' => false, 'error' => 'Impossible de créer ' . $DATA]));
}
@unlink($LOG);
@unlink($PIDF);
$cmd = 'nohup bash ' . escapeshellarg($RUN) . ' </dev/null >> ' . escapeshellarg($LOG) . ' 2>&1 & echo $!';
exec($cmd, $out2, $src);
$pid = (int) ($out2[0] ?? 0);
if ($pid > 0) {
file_put_contents($PIDF, (string) $pid);
}
echo json_encode(['ok' => $src === 0 && $pid > 0, 'pid' => $pid]);
exit;
}
if ($act === 'stop') {
exec('docker rm -f fws-iso-build >/dev/null 2>&1', $o1, $rc1);
$stopped = $running;
if ($running !== false) {
exec('kill ' . $running . ' 2>/dev/null');
@unlink($PIDF);
}
echo json_encode(['ok' => true, 'stopped' => $stopped !== false || $rc1 === 0]);
exit;
}
if ($act === 'clear') {
if ($running !== false) {
http_response_code(409);
exit(json_encode(['ok' => false, 'error' => 'Arrêtez d’abord le build en cours.']));
}
@unlink($LOG);
@unlink($PIDF);
echo json_encode(['ok' => true]);
exit;
}
if ($act === 'save_auth') {
build_save_gitea_auth_build(
trim((string) ($_POST['username'] ?? '')),
trim((string) ($_POST['token'] ?? ''))
);
$a = build_gitea_auth_build();
echo json_encode(['ok' => true, 'configured' => $a['token'] !== '', 'username' => $a['username']]);
exit;
}
http_response_code(400);
exit(json_encode(['ok' => false, 'error' => 'Action inconnue.']));
}
/* ───────────────────────── PAGES ───────────────────────── */
if ($user === null) {
header('Location: index.php');
exit;
}
$allowed = fws_bugs_can_build($user['name']);
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>Build ISO — FWS Linux</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0; font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
background: #0b1120; color: #e2e8f0; line-height: 1.5;
}
.wrap { max-width: 1000px; margin: 0 auto; padding: 24px 16px 80px; }
header.top {
display: flex; align-items: center; justify-content: space-between;
gap: 12px; padding: 14px 0; border-bottom: 1px solid #1e293b; margin-bottom: 20px;
}
header.top h1 { font-size: 1.15rem; margin: 0; }
header.top .sub { font-size: .8rem; color: #94a3b8; }
a { color: #38bdf8; text-decoration: none; }
a:hover { text-decoration: underline; }
.btn {
display: inline-block; border: 1px solid #334155; background: #1e293b; color: #e2e8f0;
padding: 6px 12px; border-radius: 8px; cursor: pointer; font-size: .85rem;
text-decoration: none; line-height: 1.4;
}
.btn:hover { background: #334155; text-decoration: none; }
.btn.primary { background: #0284c7; border-color: #0284c7; color: #fff; }
.btn.danger { background: transparent; border-color: #7f1d1d; color: #f87171; }
.btn.danger:hover { background: #7f1d1d; color: #fff; }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.card {
background: #111a2e; border: 1px solid #1e293b; border-radius: 12px;
padding: 16px; margin-bottom: 12px;
}
.card h3 { margin: 0 0 4px; font-size: 1rem; }
.card .meta { font-size: .78rem; color: #94a3b8; display: flex; flex-wrap: wrap; gap: 6px 14px; margin-bottom: 8px; }
.navtabs { display: flex; gap: 8px; margin: 0 0 16px; }
.navtabs a { border: 1px solid #334155; padding: 5px 14px; border-radius: 99px; font-size: .85rem; text-decoration: none; color: #cbd5e1; }
.navtabs a.active { background: #0284c7; border-color: #0284c7; color: #fff; }
.flash { padding: 10px 14px; border-radius: 10px; margin-bottom: 14px; font-size: .9rem; }
.flash.err { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
.status-line { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: #64748b; flex: none; }
.dot.run { background: #4ade80; animation: pulse 1.2s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: .25; } }
pre.term {
background: #020617; border: 1px solid #1e293b; border-radius: 8px;
padding: 12px; overflow: auto; max-height: 62vh; font-size: .76rem; line-height: 1.45;
white-space: pre-wrap; word-break: break-word; font-family: ui-monospace, Consolas, "Cascadia Mono", monospace;
color: #bae6fd;
}
.actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 12px; }
.hint { font-size: .78rem; color: #64748b; margin-top: 10px; }
.hint code { background: #0b1120; border: 1px solid #1e293b; padding: 1px 5px; border-radius: 6px; }
#authForm { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; margin-top: 6px; }
#authForm label { font-size: .78rem; color: #94a3b8; display: block; margin-bottom: 2px; }
#authForm input[type=text], #authForm input[type=password] {
width: 230px; padding: 7px 9px; background: #0b1120; border: 1px solid #334155;
border-radius: 8px; color: #e2e8f0; font-size: .9rem;
}
#authState { font-size: .8rem; }
</style>
</head>
<body>
<div class="wrap">
<header class="top">
<div>
<h1>🔨 Build ISO</h1>
<div class="sub">Connecté : <?= h_build($user['name']) ?> · dépôt : <code>D:\FWS-ISO</code> (branche main)</div>
</div>
<form method="post" action="index.php">
<input type="hidden" name="action" value="logout">
<input type="hidden" name="csrf" value="<?= h_build(csrf_token_build()) ?>">
<button class="btn" type="submit">Déconnexion</button>
</form>
</header>
<div class="navtabs">
<a href="index.php">🐞 Signalements</a>
<a href="index.php?view=invites">👥 Invitations &amp; comptes</a>
<a href="build.php" class="active">🔨 Build ISO</a>
</div>
<?php if (!$allowed): ?>
<div class="card">
<h3>Accès restreint</h3>
<p>Votre compte (<strong><?= h_build($user['name']) ?></strong>) n'est pas autorisé à lancer des builds.
Seul le compte <code>admin</code> le peut (voir <code>fws_bugs_can_build()</code> dans <code>api/bugs/db.php</code>).</p>
<a class="btn" href="index.php">← Retour aux signalements</a>
</div>
<?php else: ?>
<div class="card">
<h3>🔑 Accès Gitea (pour le git pull)</h3>
<p style="font-size:.82rem;color:#cbd5e1;margin:6px 0 2px">
Le dépôt <code>D:\FWS-ISO</code> est privé et le build tourne dans un conteneur sans tes identifiants
Windows : crée un token dans Gitea (<em>Settings → Applications → Generate New Token</em>, lecture du dépôt)
puis enregistre-le ici. Il n'est stocké que sur ce serveur — jamais commité, jamais affiché dans les logs.
</p>
<span id="authState">…</span>
<form id="authForm">
<div>
<label for="gUser">Utilisateur Gitea (défaut : fws)</label>
<input type="text" id="gUser" name="username" autocomplete="off">
</div>
<div>
<label for="gToken">Token</label>
<input type="password" id="gToken" name="token" autocomplete="off" placeholder="token de lecture">
</div>
<button class="btn primary" type="submit">Enregistrer</button>
<button class="btn danger" type="button" id="gClear">Retirer</button>
</form>
</div>
<div class="card">
<h3>🖥️ Terminal du build</h3>
<div class="meta">
<span id="stateLabel">État : inconnu…</span>
<span>· Git Bash lancerait ici : <code style="font-size:.95em">git checkout main &amp;&amp; git pull &amp;&amp; bash build.sh</code></span>
</div>
<pre class="term" id="term">Chargement du terminal…</pre>
<div class="actions">
<button class="btn primary" id="btnStart" type="button">▶ Lancer le build</button>
<button class="btn danger" id="btnStop" type="button">⏹ Arrêter</button>
<button class="btn" id="btnClear" type="button">🗑 Effacer le log</button>
<span id="rcLabel"></span>
</div>
<p class="hint">
Le build se déroule dans un conteneur <code>archlinux</code> jetable (via Docker Desktop, comme
<code>build.sh</code> à la main) : passage sur <code>main</code> → <code>git pull</code> → <code>bash build.sh</code> ;
en cas d'échec de build, <code>bash setup-aur.sh</code> est lancé puis <code>build.sh</code> est relancé.
Si le checkout de <code>main</code> est bloqué par des modifications locales non commitées dans
<code>D:\FWS-ISO</code>, le build s'arrête proprement sans rien toucher. L'ISO sort dans
<code>D:\FWS-ISO\out\</code>. Peut prendre 30 min et plus — laissez l'onglet ouvert, les logs défilent en direct.
</p>
</div>
<?php endif; ?>
</div>
<script>
(() => {
const allowed = <?= $allowed ? 'true' : 'false' ?>;
if (!allowed) return;
const CSRF = <?= json_encode(csrf_token_build()) ?>;
const term = document.getElementById('term');
const btnS = document.getElementById('btnStart');
const btnT = document.getElementById('btnStop');
const btnC = document.getElementById('btnClear');
const stateL = document.getElementById('stateLabel');
const rcL = document.getElementById('rcLabel');
const csrfP = new URLSearchParams();
csrfP.set('csrf', CSRF);
let pos = -1;
let running = null;
let finishedRc = null;
const authState = document.getElementById('authState');
const authForm = document.getElementById('authForm');
const gUser = document.getElementById('gUser');
const gToken = document.getElementById('gToken');
const gClear = document.getElementById('gClear');
async function refreshAuth() {
const r = await api('auth_status');
if (r.json && r.json.ok) {
authState.textContent = r.json.configured
? '✅ Token Gitea enregistré' + (r.json.username ? ' (compte : ' + r.json.username + ')' : '')
: '⚠️ Aucun token Gitea : le git pull échouera (dépôt privé).';
}
}
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
const p = new URLSearchParams(csrfP);
p.set('username', gUser.value.trim());
p.set('token', gToken.value);
const r = await api('save_auth', p);
if (r.json && r.json.ok) {
gUser.value = gToken.value = '';
await refreshAuth();
} else {
alert(r.json && r.json.error ? r.json.error : 'Erreur.');
}
});
gClear.addEventListener('click', async () => {
if (!confirm('Retirer le token Gitea enregistré ?')) return;
const p = new URLSearchParams(csrfP);
p.set('username', '');
p.set('token', '');
const r = await api('save_auth', p);
if (r.json && r.json.ok) await refreshAuth();
});
function stick() {
const near = term.scrollHeight - term.scrollTop - term.clientHeight < 90;
if (near || running !== false) term.scrollTop = term.scrollHeight;
}
function setUI() {
btnS.disabled = running === true;
btnT.disabled = running !== true;
btnC.disabled = running === true;
const dot = document.querySelector('.status-line .dot') ||
(() => { const d = document.createElement('span'); d.className = 'dot'; stateL.prepend(d); return d; })();
dot.className = 'dot' + (running ? ' run' : '');
if (running === true) {
stateL.textContent = 'État : build en cours… ';
} else if (running === false) {
stateL.textContent = 'État : inactif. ';
}
}
async function api(act, body) {
const opt = body
? { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body }
: { method: 'GET' };
const r = await fetch('build.php?act=' + encodeURIComponent(act), opt);
return { status: r.status, json: await r.json().catch(() => null) };
}
async function poll() {
try {
const r = await fetch('build.php?act=tail&pos=' + pos);
const j = await r.json();
if (!j || j.ok !== true) return;
if (j.text && j.text !== '') {
const wasEmpty = term.textContent === 'Chargement du terminal…';
if (wasEmpty) term.textContent = '';
const atEnd = term.scrollHeight - term.scrollTop - term.clientHeight < 90;
term.textContent += j.text;
if (running !== false || atEnd) term.scrollTop = term.scrollHeight;
}
pos = j.pos;
if (j.running !== running) {
running = j.running;
if (!running && j.rc !== null) {
finishedRc = j.rc;
rcL.textContent = 'Code de sortie : ' + j.rc + (j.rc === 0 ? ' ✅' : ' ❌');
}
if (running) { rcL.textContent = ''; finishedRc = null; }
setUI();
}
} catch (e) { /* requête interrompue (navigation…) : on réessaie au prochain tick */ }
}
btnS.addEventListener('click', async () => {
if (running === true) return;
if (!confirm('Lancer le build ISO ?\n\nPassage sur main → git pull → bash build.sh'
+ ' (repli setup-aur.sh en cas d' + '\u2019échec).\nLe dépôt D:\\FWS-ISO ne doit pas être utilisé ailleurs pendant le build.')) return;
const p = new URLSearchParams(csrfP); p.set('act', 'start');
const r = await api('start', p);
if (r.json && r.json.ok) { pos = -1; await poll(); } else { alert(r.json && r.json.error ? r.json.error : 'Erreur au démarrage.'); }
});
btnT.addEventListener('click', async () => {
if (running !== true) return;
if (!confirm('Arrêter le build en cours ?')) return;
const p = new URLSearchParams(csrfP); p.set('act', 'stop');
const r = await api('stop', p);
if (r.json && r.json.ok) { await poll(); } else { alert(r.json && r.json.error ? r.json.error : 'Erreur à l' + '\u2019arrêt.'); }
});
btnC.addEventListener('click', async () => {
if (running === true) return;
const p = new URLSearchParams(csrfP); p.set('act', 'clear');
const r = await api('clear', p);
if (r.json && r.json.ok) { term.textContent = ''; pos = -1; rcL.textContent = ''; } else { alert(r.json && r.json.error ? r.json.error : 'Erreur.'); }
});
setUI();
refreshAuth();
poll();
setInterval(poll, 1000);
})();
</script>
</body>
</html>