Compare commits
6
Commits
20ff701430
...
2083133c7a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2083133c7a
|
||
|
|
5481e79dc4
|
||
|
|
df89cc5893
|
||
|
|
9c6297e00e
|
||
|
|
ff15dfe92f
|
||
|
|
a0428e0549
|
No files matched your search
@@ -340,6 +340,8 @@ The site reuses the access levels of the slash commands, derived from the Discor
|
||||
|
||||
A **Simple / Advanced** switch hides or reveals the technical panels. It changes no permission: every call is checked again on the server.
|
||||
|
||||
The pages update on their own: the server pushes every change over a `text/event-stream`, and an indicator at the bottom of the sidebar says where the connection stands. Nothing reloads while a dialog is open or a field has focus, and a periodic refresh takes over when the stream cannot get through.
|
||||
|
||||
### 6.3 Configuration wizard
|
||||
|
||||
Every `.env` variable is described once, in `src/web/services/env-schema.js`: the form, the explanations, the validation and the generated file all derive from it.
|
||||
|
||||
@@ -342,6 +342,8 @@ Le site réutilise les niveaux d'accès des commandes slash, déduits des rôles
|
||||
|
||||
Un commutateur **Simple / Avancé** masque ou révèle les panneaux techniques. Il ne change aucun droit : chaque appel est revérifié côté serveur.
|
||||
|
||||
Les pages se mettent à jour toutes seules : le serveur pousse chaque changement sur un flux `text/event-stream`, et un indicateur en bas de la barre latérale dit où en est la connexion. Rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus, et un rafraîchissement périodique prend le relais si le flux ne passe pas.
|
||||
|
||||
### 6.3 Assistant de configuration
|
||||
|
||||
Chaque variable du `.env` est décrite une seule fois, dans `src/web/services/env-schema.js` : le formulaire, les explications, la validation et le fichier généré en découlent tous.
|
||||
|
||||
+27
-4
@@ -119,7 +119,30 @@ Vérifie la signature côté réception : `HMAC-SHA256(corps_brut, secret)` en h
|
||||
|
||||
Chaque tentative laisse une ligne dans l'historique avec son journal complet, réussie comme échouée, et une notification Discord (`releases` en cas de succès, `errors` en cas d'échec).
|
||||
|
||||
## 6. Jetons d'API
|
||||
## 6. Mise à jour automatique
|
||||
|
||||
Les pages suivent le bot en direct : aucun rafraîchissement manuel n'est nécessaire.
|
||||
|
||||
Le serveur tient un flux `text/event-stream` sur `GET /api/events`, un par onglet ouvert. Il y publie :
|
||||
|
||||
- **chaque écriture réussie** de l'API, étiquetée selon la page concernée (`deployments`, `gitea`, `discord`, `community`, `settings`) — une écriture rejetée ne déclenche rien ;
|
||||
- **l'avancement des déploiements**, au démarrage puis à l'arrivée du résultat ;
|
||||
- **les webhooks Gitea** reçus, dès qu'ils sont validés ;
|
||||
- un **tick** toutes les 15 secondes, et un battement de cœur toutes les 25 secondes qui empêche les proxys de fermer un flux inactif.
|
||||
|
||||
Côté navigateur, un seul `EventSource` sert tout le tableau de bord, et chaque page ne réagit qu'aux sujets qui la concernent. L'indicateur en bas de la barre latérale dit où en est la connexion.
|
||||
|
||||
Trois garde-fous, parce qu'un rafraîchissement qui tombe au mauvais moment est pire qu'une donnée un peu vieille :
|
||||
|
||||
- rien ne se recharge tant qu'une fenêtre modale est ouverte ou qu'un champ a le focus — le rafraîchissement est rejoué ensuite ;
|
||||
- une rafale d'écritures ne produit qu'un seul rechargement ;
|
||||
- l'onglet en arrière-plan ferme son flux et le rouvre au retour.
|
||||
|
||||
Si le flux ne s'établit pas — proxy qui met en tampon, réseau instable — un rafraîchissement périodique prend le relais automatiquement, et l'indicateur passe en orange. La page Serveur Discord est volontairement hors du tick : lister les membres appelle l'API Discord, elle ne se rafraîchit que sur un vrai changement.
|
||||
|
||||
Pour un reverse proxy, pense à désactiver la mise en tampon sur ce chemin. Le serveur envoie déjà `X-Accel-Buffering: no` et `Cache-Control: no-transform`, ce que nginx respecte.
|
||||
|
||||
## 7. Jetons d'API
|
||||
|
||||
Pour appeler l'API depuis une CI ou un script, sans compte Discord : **Paramètres → Jetons d'API**. Le jeton en clair n'est affiché qu'une fois ; seule son empreinte est stockée.
|
||||
|
||||
@@ -129,7 +152,7 @@ curl -H "Authorization: Bearer fws_…" https://bot.exemple.org/api/overview
|
||||
|
||||
Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personne qui le crée. Il est révocable à tout moment.
|
||||
|
||||
## 7. Sécurité
|
||||
## 8. Sécurité
|
||||
|
||||
- **Écoute locale par défaut.** `WEB_HOST=127.0.0.1` : place un reverse proxy HTTPS devant avant d'exposer le site.
|
||||
- **Sessions.** Cookie `HttpOnly`, `SameSite=Lax`, `Secure` dès que l'URL publique est en HTTPS. Seule l'empreinte du jeton est en base, poivrée avec `WEB_SESSION_SECRET`.
|
||||
@@ -140,7 +163,7 @@ Un jeton porte un niveau d'accès, qui ne peut pas dépasser celui de la personn
|
||||
- **Actions irréversibles.** Supprimer un dépôt ou redémarrer le bot demande de retaper le nom exact.
|
||||
- **Traçabilité.** Toute action d'écriture est consignée dans `event_logs` avec son auteur.
|
||||
|
||||
## 8. Fonctionnement interne
|
||||
## 9. Fonctionnement interne
|
||||
|
||||
```text
|
||||
src/web/
|
||||
@@ -184,7 +207,7 @@ Le serveur authentifie, vérifie l'origine, applique le niveau requis, lit le co
|
||||
|
||||
Si `WEBHOOK_PORT` vaut `WEB_PORT`, un seul serveur HTTP est démarré : il sert le site et la route des webhooks Gitea. Sinon, les deux serveurs écoutent chacun sur leur port.
|
||||
|
||||
## 9. Dépannage
|
||||
## 10. Dépannage
|
||||
|
||||
| Symptôme | Cause probable |
|
||||
| ---------------------------------------------- | ------------------------------------------------------------------------------- |
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { registerAuthRoutes } from '../auth/routes.js';
|
||||
import { openEventStream } from '../events.js';
|
||||
import { registerCommunityRoutes } from './community.js';
|
||||
import { registerConfigurationRoutes } from './configuration.js';
|
||||
import { registerDeploymentRoutes } from './deployments.js';
|
||||
@@ -30,6 +32,15 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
|
||||
registerAuthRoutes(router);
|
||||
registerConfigurationRoutes(router);
|
||||
|
||||
// Long-lived stream the pages listen to instead of polling (M16-T12).
|
||||
router.get(
|
||||
'/api/events',
|
||||
({ request, response, actor }) => {
|
||||
openEventStream(request, response, actor);
|
||||
},
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
|
||||
// In bootstrap mode the bot is not connected and the database may be empty:
|
||||
// only the wizard makes sense.
|
||||
if (setupOnly) return router;
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
/**
|
||||
* Server-sent events feeding the dashboard live (M16-T12).
|
||||
*
|
||||
* One long-lived GET per open tab, pushed to rather than polled: a browser that
|
||||
* nobody is looking at costs a heartbeat every 25 seconds, and a change shows up
|
||||
* as soon as it happens instead of on the next timer.
|
||||
*/
|
||||
|
||||
const log = createLogger('web:events');
|
||||
|
||||
const HEARTBEAT_MS = 25_000;
|
||||
const TICK_MS = 15_000;
|
||||
/** Past this, something is wrong: refuse rather than pile up dead sockets. */
|
||||
const MAX_SUBSCRIBERS = 64;
|
||||
|
||||
const subscribers = new Set();
|
||||
let heartbeat = null;
|
||||
let tick = null;
|
||||
|
||||
function write(subscriber, payload) {
|
||||
try {
|
||||
subscriber.response.write(payload);
|
||||
} catch (error) {
|
||||
log.debug('Dropping a closed event subscriber', error);
|
||||
remove(subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
function remove(subscriber) {
|
||||
if (!subscribers.delete(subscriber)) return;
|
||||
try {
|
||||
subscriber.response.end();
|
||||
} catch {
|
||||
// The socket is already gone, which is exactly why we are here.
|
||||
}
|
||||
if (subscribers.size === 0) stopTimers();
|
||||
}
|
||||
|
||||
function startTimers() {
|
||||
if (heartbeat) return;
|
||||
// Comment frames keep proxies from closing an idle stream.
|
||||
heartbeat = setInterval(() => {
|
||||
for (const subscriber of subscribers) write(subscriber, ': ping\n\n');
|
||||
}, HEARTBEAT_MS);
|
||||
tick = setInterval(() => broadcast('tick', { at: new Date().toISOString() }), TICK_MS);
|
||||
|
||||
// Timers must never be the reason the process stays alive.
|
||||
heartbeat.unref?.();
|
||||
tick.unref?.();
|
||||
}
|
||||
|
||||
function stopTimers() {
|
||||
clearInterval(heartbeat);
|
||||
clearInterval(tick);
|
||||
heartbeat = null;
|
||||
tick = null;
|
||||
}
|
||||
|
||||
/** Publishes an event to every open dashboard. Never throws. */
|
||||
export function broadcast(topic, payload = {}) {
|
||||
if (subscribers.size === 0) return 0;
|
||||
|
||||
const frame = `event: ${topic}\ndata: ${JSON.stringify({ topic, ...payload })}\n\n`;
|
||||
for (const subscriber of subscribers) write(subscriber, frame);
|
||||
return subscribers.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a subscriber and keeps the response open.
|
||||
* Returns nothing: the router must not try to serialise a body onto it.
|
||||
*/
|
||||
export function openEventStream(request, response, actor) {
|
||||
if (subscribers.size >= MAX_SUBSCRIBERS) {
|
||||
response.writeHead(503).end();
|
||||
return;
|
||||
}
|
||||
|
||||
response.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
// `no-transform` and the nginx hint both matter: a buffering proxy turns a
|
||||
// live stream into a stream that arrives all at once, much later.
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
'X-Accel-Buffering': 'no',
|
||||
Connection: 'keep-alive',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
});
|
||||
response.flushHeaders?.();
|
||||
|
||||
const subscriber = { response, userId: actor?.userId ?? null };
|
||||
subscribers.add(subscriber);
|
||||
startTimers();
|
||||
|
||||
write(subscriber, `retry: 5000\nevent: ready\ndata: ${JSON.stringify({ topic: 'ready' })}\n\n`);
|
||||
|
||||
request.on('close', () => remove(subscriber));
|
||||
request.on('error', () => remove(subscriber));
|
||||
log.debug('Event subscriber connected', { subscribers: subscribers.size });
|
||||
}
|
||||
|
||||
export function subscriberCount() {
|
||||
return subscribers.size;
|
||||
}
|
||||
|
||||
/** Closes every stream, so a shutdown does not hang on open sockets. */
|
||||
export function closeEventStreams() {
|
||||
for (const subscriber of [...subscribers]) remove(subscriber);
|
||||
stopTimers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns an API path into the topic a view can filter on, so a write made
|
||||
* anywhere refreshes the pages that care and only those.
|
||||
*/
|
||||
export function topicForPath(pathname) {
|
||||
const [, , section] = pathname.split('/');
|
||||
switch (section) {
|
||||
case 'deploy':
|
||||
case 'deployments':
|
||||
return 'deployments';
|
||||
case 'repositories':
|
||||
case 'organization':
|
||||
return 'gitea';
|
||||
case 'discord':
|
||||
return 'discord';
|
||||
case 'community':
|
||||
return 'community';
|
||||
case 'settings':
|
||||
case 'configuration':
|
||||
return 'settings';
|
||||
default:
|
||||
return 'mutation';
|
||||
}
|
||||
}
|
||||
+57
-3
@@ -1,5 +1,6 @@
|
||||
import { api } from './core/api.js';
|
||||
import { h, mount, qs } from './core/dom.js';
|
||||
import { onStatus, resetSubscriptions, startLive } from './core/live.js';
|
||||
import { ACCESS_LABELS, button, spinner, toast } from './core/ui.js';
|
||||
|
||||
/** Shell, navigation and hash routing of the dashboard (M16-T11). */
|
||||
@@ -132,9 +133,54 @@ const currentRoute = () => {
|
||||
return { segments, path };
|
||||
};
|
||||
|
||||
function sidebar() {
|
||||
/**
|
||||
* Marks the current entry in the sidebar and retitles the tab.
|
||||
*
|
||||
* Navigation only swaps the main area, so the highlight has to be refreshed on
|
||||
* its own — otherwise it keeps pointing at the page you arrived on.
|
||||
*/
|
||||
function highlightNav() {
|
||||
const { segments } = currentRoute();
|
||||
const active = segments[0] ?? '';
|
||||
const route = ROUTES.find((entry) => entry.path === active);
|
||||
|
||||
for (const link of document.querySelectorAll('.nav a')) {
|
||||
link.classList.toggle('active', link.getAttribute('href') === `#/${active}`);
|
||||
if (link.getAttribute('href') === `#/${active}`) link.setAttribute('aria-current', 'page');
|
||||
else link.removeAttribute('aria-current');
|
||||
}
|
||||
document.title = route ? `${route.label} · FWS-Bot` : 'FWS-Bot';
|
||||
}
|
||||
|
||||
const LIVE_LABELS = {
|
||||
live: 'À jour en direct',
|
||||
connecting: 'Connexion…',
|
||||
reconnecting: 'Reconnexion…',
|
||||
polling: 'Rafraîchissement périodique',
|
||||
paused: 'En pause (onglet en arrière-plan)',
|
||||
idle: 'Hors ligne',
|
||||
};
|
||||
|
||||
let stopWatchingStatus = null;
|
||||
|
||||
/** Small footer badge: says whether the page is following the bot live. */
|
||||
function liveIndicator() {
|
||||
const dot = h('span', { class: 'live-dot' });
|
||||
const label = h('span', { text: LIVE_LABELS.idle });
|
||||
const node = h('div', { class: 'live', title: 'État de la mise à jour automatique' }, dot, label);
|
||||
|
||||
stopWatchingStatus?.();
|
||||
stopWatchingStatus = onStatus(({ status, lastEventAt }) => {
|
||||
node.dataset.status = status;
|
||||
label.textContent = LIVE_LABELS[status] ?? status;
|
||||
if (lastEventAt) {
|
||||
node.title = `Dernière mise à jour à ${lastEventAt.toLocaleTimeString('fr-FR')}`;
|
||||
}
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
function sidebar() {
|
||||
const visible = ROUTES.filter(
|
||||
(route) => state.me.accessLevel >= route.level && (!route.advanced || state.mode === 'advanced'),
|
||||
);
|
||||
@@ -163,7 +209,7 @@ function sidebar() {
|
||||
group.routes.map((route) =>
|
||||
h(
|
||||
'a',
|
||||
{ href: `#/${route.path}`, class: route.path === active ? 'active' : '' },
|
||||
{ href: `#/${route.path}` },
|
||||
h('span', { class: 'nav-icon', text: route.icon }),
|
||||
h('span', { text: route.label }),
|
||||
),
|
||||
@@ -179,6 +225,7 @@ function sidebar() {
|
||||
button('Simple', () => setMode('simple'), {}),
|
||||
button('Avancé', () => setMode('advanced'), {}),
|
||||
),
|
||||
liveIndicator(),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'viewer' },
|
||||
@@ -226,6 +273,9 @@ function applyModeButtons(node) {
|
||||
async function renderView(host) {
|
||||
const { segments } = currentRoute();
|
||||
const route = ROUTES.find((entry) => entry.path === (segments[0] ?? ''));
|
||||
resetSubscriptions();
|
||||
highlightNav();
|
||||
host.scrollIntoView?.({ block: 'start' });
|
||||
|
||||
if (!route) {
|
||||
mount(host, h('div', { class: 'notice notice-warning' }, h('p', { text: 'Page inconnue.' })));
|
||||
@@ -284,8 +334,12 @@ async function boot() {
|
||||
state.me = me;
|
||||
state.config = config;
|
||||
|
||||
startLive();
|
||||
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (state.me?.authenticated && state.me.source !== 'setup') renderView(qs('.main'));
|
||||
const main = qs('.main');
|
||||
// Without the shell in place there is nothing to swap, so rebuild the page.
|
||||
if (main && state.me?.authenticated && state.me.source !== 'setup') renderView(main);
|
||||
else render();
|
||||
});
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Live updates (M16-T12).
|
||||
*
|
||||
* One `EventSource` for the whole dashboard; views declare what they want to
|
||||
* hear and get called back. When the stream cannot be established — a proxy
|
||||
* that buffers, a network that drops it — a timer takes over so the pages still
|
||||
* refresh, just less promptly.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A single slot rather than a list: exactly one view is on screen, and a view
|
||||
* that re-renders itself on refresh would otherwise register a second listener
|
||||
* each time, doubling the work on every event.
|
||||
*/
|
||||
let viewRefresher = null;
|
||||
const STATUS_LISTENERS = new Set();
|
||||
const FALLBACK_MS = 30_000;
|
||||
/** Backoff between reconnection attempts, capped so it always keeps trying. */
|
||||
const RETRY_MS = [2000, 5000, 15_000, 30_000];
|
||||
|
||||
let source = null;
|
||||
let fallbackTimer = null;
|
||||
let attempts = 0;
|
||||
let status = 'idle';
|
||||
let lastEventAt = null;
|
||||
|
||||
function setStatus(next) {
|
||||
if (status === next) return;
|
||||
status = next;
|
||||
for (const listener of STATUS_LISTENERS) listener({ status, lastEventAt });
|
||||
}
|
||||
|
||||
function emit(event) {
|
||||
lastEventAt = new Date();
|
||||
try {
|
||||
viewRefresher?.(event);
|
||||
} catch {
|
||||
// A failing view must not take the stream down with it.
|
||||
}
|
||||
setStatus(fallbackTimer ? 'polling' : 'live');
|
||||
}
|
||||
|
||||
function startFallback() {
|
||||
if (fallbackTimer) return;
|
||||
fallbackTimer = setInterval(() => emit({ topic: 'tick', fallback: true }), FALLBACK_MS);
|
||||
setStatus('polling');
|
||||
}
|
||||
|
||||
function stopFallback() {
|
||||
clearInterval(fallbackTimer);
|
||||
fallbackTimer = null;
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (source || document.hidden) return;
|
||||
|
||||
setStatus(attempts === 0 ? 'connecting' : 'reconnecting');
|
||||
source = new EventSource('/api/events', { withCredentials: true });
|
||||
|
||||
source.addEventListener('open', () => {
|
||||
attempts = 0;
|
||||
stopFallback();
|
||||
setStatus('live');
|
||||
});
|
||||
|
||||
for (const topic of [
|
||||
'ready',
|
||||
'tick',
|
||||
'mutation',
|
||||
'deployments',
|
||||
'gitea',
|
||||
'discord',
|
||||
'community',
|
||||
'settings',
|
||||
]) {
|
||||
source.addEventListener(topic, (event) => {
|
||||
let payload = { topic };
|
||||
try {
|
||||
payload = { ...JSON.parse(event.data), topic };
|
||||
} catch {
|
||||
// A frame we cannot read is still a signal that something moved.
|
||||
}
|
||||
emit(payload);
|
||||
});
|
||||
}
|
||||
|
||||
source.addEventListener('error', () => {
|
||||
source?.close();
|
||||
source = null;
|
||||
|
||||
// The browser reconnects on its own, but only while the page stays open and
|
||||
// the server keeps answering; the timer covers the rest.
|
||||
startFallback();
|
||||
const delay = RETRY_MS[Math.min(attempts, RETRY_MS.length - 1)];
|
||||
attempts += 1;
|
||||
setTimeout(connect, delay);
|
||||
});
|
||||
}
|
||||
|
||||
/** Stops the stream while the tab is in the background, resumes on return. */
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
source?.close();
|
||||
source = null;
|
||||
stopFallback();
|
||||
setStatus('paused');
|
||||
} else {
|
||||
connect();
|
||||
// Coming back to the tab, the page is stale by definition.
|
||||
emit({ topic: 'tick', resumed: true });
|
||||
}
|
||||
});
|
||||
|
||||
export function startLive() {
|
||||
connect();
|
||||
}
|
||||
|
||||
export function onStatus(listener) {
|
||||
STATUS_LISTENERS.add(listener);
|
||||
listener({ status, lastEventAt });
|
||||
return () => STATUS_LISTENERS.delete(listener);
|
||||
}
|
||||
|
||||
export const liveStatus = () => ({ status, lastEventAt });
|
||||
|
||||
/** Drops the current view subscription, called when navigating elsewhere. */
|
||||
export function resetSubscriptions() {
|
||||
viewRefresher = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-runs `refresh` when a relevant event arrives.
|
||||
*
|
||||
* Refreshing under someone's fingers is worse than showing slightly old data,
|
||||
* so a refresh is skipped while a dialog is open or a field has focus, and
|
||||
* replayed once the way is clear.
|
||||
*/
|
||||
export function autoRefresh(refresh, { topics = ['tick'], minIntervalMs = 5000 } = {}) {
|
||||
const wanted = new Set(topics);
|
||||
let lastRun = Date.now();
|
||||
let pending = false;
|
||||
|
||||
const busy = () =>
|
||||
document.querySelector('.overlay') !== null ||
|
||||
['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName);
|
||||
|
||||
const run = () => {
|
||||
if (busy()) {
|
||||
pending = true;
|
||||
return;
|
||||
}
|
||||
pending = false;
|
||||
lastRun = Date.now();
|
||||
refresh();
|
||||
};
|
||||
|
||||
const listener = (event) => {
|
||||
if (!wanted.has(event.topic) && !pending) return;
|
||||
// A burst of writes must not turn into a burst of reloads.
|
||||
if (Date.now() - lastRun < minIntervalMs && !pending) return;
|
||||
run();
|
||||
};
|
||||
|
||||
viewRefresher = listener;
|
||||
return () => {
|
||||
if (viewRefresher === listener) viewRefresher = null;
|
||||
};
|
||||
}
|
||||
@@ -192,6 +192,11 @@ pre code {
|
||||
background: color-mix(in srgb, var(--blue) 18%, transparent);
|
||||
color: var(--blue-soft);
|
||||
font-weight: 600;
|
||||
/* Inset rather than a border: a real border would shift the label. */
|
||||
box-shadow: inset 3px 0 0 var(--blue);
|
||||
}
|
||||
.nav a.active .nav-icon {
|
||||
opacity: 1;
|
||||
}
|
||||
.nav-icon {
|
||||
width: 1.15rem;
|
||||
@@ -685,6 +690,63 @@ pre code {
|
||||
padding-left: 1.2rem;
|
||||
}
|
||||
|
||||
.live {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
padding: 0 0.2rem;
|
||||
}
|
||||
.live-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-muted);
|
||||
flex: none;
|
||||
}
|
||||
.live[data-status='live'] .live-dot {
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--green) 25%, transparent);
|
||||
}
|
||||
.live[data-status='polling'] .live-dot {
|
||||
background: var(--amber);
|
||||
}
|
||||
.live[data-status='connecting'] .live-dot,
|
||||
.live[data-status='reconnecting'] .live-dot {
|
||||
background: var(--blue);
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
.live[data-status='paused'] .live-dot {
|
||||
background: var(--border);
|
||||
}
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.25;
|
||||
}
|
||||
}
|
||||
|
||||
details summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
padding: 0.35rem 0;
|
||||
list-style-position: outside;
|
||||
}
|
||||
details summary:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
details[open] summary {
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
details > *:not(summary) {
|
||||
margin-bottom: 0.6rem;
|
||||
}
|
||||
details > *:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* --- Simple / advanced mode ---------------------------------------------- */
|
||||
|
||||
body[data-mode='simple'] .advanced-only {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import { formatRelative, h } from '../core/dom.js';
|
||||
import {
|
||||
badge,
|
||||
@@ -346,6 +347,8 @@ export function render(host, { state }) {
|
||||
const level = state.me.accessLevel;
|
||||
const reload = () => render(host, { state });
|
||||
|
||||
autoRefresh(reload, { topics: ['community', 'discord', 'tick'] });
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
async () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import { formatRelative, h, mount } from '../core/dom.js';
|
||||
import {
|
||||
badge,
|
||||
@@ -45,10 +46,17 @@ const KIND_HELP = {
|
||||
|
||||
async function editTarget(existing, repositories, commandsAllowed, level, reload) {
|
||||
const name = input({ value: existing?.name ?? '', placeholder: 'production-web' });
|
||||
const repository = select(
|
||||
repositories.map((item) => ({ value: item.fullName, label: item.fullName })),
|
||||
{ value: existing?.repository ?? repositories[0]?.fullName },
|
||||
);
|
||||
|
||||
// A webhook or a shell command needs no Gitea at all, so an unreachable forge
|
||||
// must not stand between the user and a deploy target: the repository then
|
||||
// falls back to a free-text field.
|
||||
const repository =
|
||||
repositories.length > 0
|
||||
? select(
|
||||
repositories.map((item) => ({ value: item.fullName, label: item.fullName })),
|
||||
{ value: existing?.repository ?? repositories[0]?.fullName },
|
||||
)
|
||||
: input({ value: existing?.repository ?? '', placeholder: 'FWS/FWS-Arch' });
|
||||
const environment = input({ value: existing?.environment ?? 'production' });
|
||||
const kindOptions = KINDS.filter(
|
||||
(kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER),
|
||||
@@ -104,7 +112,12 @@ async function editTarget(existing, repositories, commandsAllowed, level, reload
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
field('Nom', name),
|
||||
field('Dépôt', repository),
|
||||
field('Dépôt', repository, {
|
||||
help:
|
||||
repositories.length > 0
|
||||
? undefined
|
||||
: 'Format `organisation/depot`. La liste est vide : Gitea est injoignable ou non configuré.',
|
||||
}),
|
||||
field('Environnement', environment, { help: 'production, staging, preview…' }),
|
||||
field('Type', kind),
|
||||
help,
|
||||
@@ -116,7 +129,7 @@ async function editTarget(existing, repositories, commandsAllowed, level, reload
|
||||
),
|
||||
toggle(enabled, (checked) => (enabled = checked), 'Cible active'),
|
||||
),
|
||||
submit: () => name.value.trim() !== '',
|
||||
submit: () => name.value.trim() !== '' && repository.value.trim() !== '',
|
||||
}),
|
||||
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
|
||||
);
|
||||
@@ -208,18 +221,24 @@ export function render(host, { state }) {
|
||||
const level = state.me.accessLevel;
|
||||
const reload = () => render(host, { state });
|
||||
|
||||
// A running deployment reports itself, so the log lands without a reload.
|
||||
autoRefresh(reload, { topics: ['deployments', 'tick'], minIntervalMs: 2000 });
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
async () => {
|
||||
// The repository list is a convenience, not a prerequisite: a Gitea that
|
||||
// answers 403 must not take the whole deployment page down with it.
|
||||
const [targets, deployments, repositories] = await Promise.all([
|
||||
api.get('/api/deploy/targets'),
|
||||
api.get('/api/deployments', { limit: 40 }),
|
||||
api.get('/api/repositories'),
|
||||
api.get('/api/repositories').catch((error) => ({ repositories: [], error: error.message })),
|
||||
]);
|
||||
return {
|
||||
...targets,
|
||||
deployments: deployments.deployments,
|
||||
repositories: repositories.repositories ?? [],
|
||||
repositoriesError: repositories.error ?? null,
|
||||
};
|
||||
},
|
||||
(data) =>
|
||||
@@ -239,7 +258,6 @@ export function render(host, { state }) {
|
||||
}),
|
||||
),
|
||||
level >= LEVELS.DEV &&
|
||||
data.repositories.length > 0 &&
|
||||
button(
|
||||
'Nouvelle cible',
|
||||
() => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload),
|
||||
@@ -247,6 +265,12 @@ export function render(host, { state }) {
|
||||
),
|
||||
),
|
||||
|
||||
data.repositoriesError &&
|
||||
notice(
|
||||
`Liste des dépôts indisponible (${data.repositoriesError}). Tu peux quand même créer une cible en saisissant le dépôt à la main ; seules les cibles Gitea Actions ont réellement besoin de la forge.`,
|
||||
'warning',
|
||||
),
|
||||
|
||||
!data.commandDeploysAllowed &&
|
||||
notice(
|
||||
'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.',
|
||||
|
||||
@@ -67,16 +67,26 @@ export function render(host, { state }) {
|
||||
}),
|
||||
),
|
||||
|
||||
config.setupAvailable &&
|
||||
h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
h('hr', { style: { border: 'none', borderTop: '1px solid var(--border)', width: '100%' } }),
|
||||
field('Jeton d’amorçage', tokenInput, {
|
||||
help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration.',
|
||||
}),
|
||||
button('Ouvrir l’assistant de configuration', submitSetupToken, { tone: 'ghost' }),
|
||||
),
|
||||
// Always reachable: when Discord sign-in is broken or not set up yet,
|
||||
// this is the only way back into the configuration, and hiding it left
|
||||
// no visible way out.
|
||||
h(
|
||||
'details',
|
||||
{ class: 'stack', style: { textAlign: 'left', width: '100%' }, open: !config.oauthConfigured },
|
||||
h('summary', { text: 'Se connecter avec un jeton de configuration' }),
|
||||
field('Jeton d’amorçage', tokenInput, {
|
||||
help: 'Affiché par `npm run setup`, ou défini dans `WEB_SETUP_TOKEN`. Il ne donne accès qu’à la configuration, jamais au reste du site.',
|
||||
}),
|
||||
!config.setupAvailable &&
|
||||
notice(
|
||||
'Aucun jeton n’est configuré pour l’instant. Renseigne `WEB_SETUP_TOKEN` dans le .env puis redémarre le bot, ou lance `npm run setup` pour en obtenir un temporaire.',
|
||||
'info',
|
||||
),
|
||||
button('Ouvrir l’assistant de configuration', submitSetupToken, {
|
||||
tone: 'ghost',
|
||||
disabled: !config.setupAvailable,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import { formatBytes, formatRelative, h } from '../core/dom.js';
|
||||
import {
|
||||
badge,
|
||||
@@ -104,6 +105,8 @@ export function render(host, { state }) {
|
||||
const level = state.me.accessLevel;
|
||||
const refresh = () => render(host, { state });
|
||||
|
||||
autoRefresh(refresh, { topics: ['gitea'] });
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
() => api.get('/api/organization'),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import { formatBytes, formatDuration, formatRelative, h } from '../core/dom.js';
|
||||
import { badge, card, grid, renderAsync, stat, table } from '../core/ui.js';
|
||||
|
||||
@@ -162,6 +163,10 @@ function systemCard(database, features) {
|
||||
}
|
||||
|
||||
export function render(host, { state }) {
|
||||
autoRefresh(() => render(host, { state }), {
|
||||
topics: ['tick', 'mutation', 'deployments', 'gitea', 'discord', 'community'],
|
||||
});
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
() => api.get('/api/overview'),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { api } from '../core/api.js';
|
||||
import { autoRefresh } from '../core/live.js';
|
||||
import { formatDate, formatRelative, h } from '../core/dom.js';
|
||||
import {
|
||||
badge,
|
||||
@@ -436,6 +437,8 @@ export function render(host, { state }) {
|
||||
const level = state.me.accessLevel;
|
||||
const reload = () => render(host, { state });
|
||||
|
||||
autoRefresh(reload, { topics: ['settings'] });
|
||||
|
||||
return renderAsync(
|
||||
host,
|
||||
() => api.get('/api/settings'),
|
||||
|
||||
+11
-1
@@ -8,6 +8,7 @@ import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js';
|
||||
import { registerApiRoutes } from './api/index.js';
|
||||
import { authenticate, assertSameOrigin } from './auth/session.js';
|
||||
import { authorize } from './auth/guard.js';
|
||||
import { broadcast, closeEventStreams, topicForPath } from './events.js';
|
||||
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
|
||||
import { createRouter } from './router.js';
|
||||
|
||||
@@ -102,8 +103,15 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
|
||||
context,
|
||||
});
|
||||
|
||||
// A handler that wrote the response itself (a redirect) returns nothing.
|
||||
// A handler that wrote the response itself (a redirect, an event stream)
|
||||
// returns nothing.
|
||||
if (!response.headersSent) sendJson(response, 200, result ?? { ok: true });
|
||||
|
||||
// Announce the change only once it has gone through, so a dashboard never
|
||||
// refreshes on a write that was rejected.
|
||||
if (request.method !== 'GET') {
|
||||
broadcast(topicForPath(pathname), { path: pathname, method: request.method });
|
||||
}
|
||||
} catch (error) {
|
||||
const status = statusOf(error);
|
||||
if (status >= 500) log.error(`${request.method} ${pathname} failed`, error);
|
||||
@@ -127,6 +135,8 @@ export function startWebServer({ client = null, setupOnly = false } = {}) {
|
||||
log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly });
|
||||
});
|
||||
server.on('error', (error) => log.error('Dashboard server error', error));
|
||||
// Open event streams would otherwise keep the server from closing.
|
||||
server.on('close', closeEventStreams);
|
||||
return server;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||
import { notify } from '../../services/notifications/notification-service.js';
|
||||
import { splitRepository, repos } from '../../services/gitea/gitea-admin.js';
|
||||
import { broadcast } from '../events.js';
|
||||
import { HttpError, badRequest, forbidden } from '../http.js';
|
||||
|
||||
/** Runs a deployment for a target and records its outcome (M16-T07). */
|
||||
@@ -156,6 +157,7 @@ export async function runDeployment(
|
||||
triggeredBy,
|
||||
});
|
||||
markRunning(deployment.id);
|
||||
broadcast('deployments', { id: deployment.id, status: 'running', target: target.name });
|
||||
|
||||
const payload = {
|
||||
deploymentId: deployment.id,
|
||||
@@ -177,12 +179,14 @@ export async function runDeployment(
|
||||
else output = await runGiteaAction(target, payload);
|
||||
|
||||
finishDeployment(deployment.id, { status: 'success', log: output });
|
||||
broadcast('deployments', { id: deployment.id, status: 'success', target: target.name });
|
||||
logEvent({ guildId, type: 'deploy.success', actorId: triggeredBy, payload });
|
||||
await announce(client, { ...payload, status: 'success' });
|
||||
return { ...deployment, status: 'success', log: output };
|
||||
} catch (error) {
|
||||
const details = error.details ?? error.message;
|
||||
finishDeployment(deployment.id, { status: 'failed', log: details, error: error.message });
|
||||
broadcast('deployments', { id: deployment.id, status: 'failed', target: target.name });
|
||||
log.error('Deployment failed', error);
|
||||
logEvent({ guildId, type: 'deploy.failed', actorId: triggeredBy, payload });
|
||||
await announce(client, { ...payload, status: 'failed', error: error.message });
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getDatabase } from '../database/index.js';
|
||||
import { logEvent } from '../database/repositories/event-log-repository.js';
|
||||
import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js';
|
||||
import { notify } from '../services/notifications/notification-service.js';
|
||||
import { broadcast } from '../web/events.js';
|
||||
|
||||
const log = createLogger('webhooks');
|
||||
|
||||
@@ -60,6 +61,8 @@ export async function handleGiteaWebhook(client, headers, rawBody) {
|
||||
payload: { deliveryId, type: notification.type },
|
||||
});
|
||||
|
||||
broadcast('gitea', { event, repository: payload.repository?.full_name ?? null });
|
||||
|
||||
await notify(client, notification.type, {
|
||||
embeds: [notification.embed],
|
||||
content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||
import { createApiToken } from '../src/database/repositories/web-session-repository.js';
|
||||
import { ACCESS_LEVELS } from '../src/config/constants.js';
|
||||
import { hashToken } from '../src/web/auth/session.js';
|
||||
import { broadcast, closeEventStreams, subscriberCount, topicForPath } from '../src/web/events.js';
|
||||
import { createHandler } from '../src/web/server.js';
|
||||
|
||||
/** Live updates pushed over server-sent events (M16-T12). */
|
||||
|
||||
const TOKEN = 'fws_events-test-token';
|
||||
|
||||
/** Reads SSE frames off the socket until `stop()` is called. */
|
||||
function openStream(url) {
|
||||
const controller = new AbortController();
|
||||
const frames = [];
|
||||
let resolveReady;
|
||||
const ready = new Promise((resolve) => (resolveReady = resolve));
|
||||
|
||||
const done = fetch(url, {
|
||||
headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'text/event-stream' },
|
||||
signal: controller.signal,
|
||||
}).then(async (response) => {
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-type'), /text\/event-stream/);
|
||||
resolveReady(response);
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
try {
|
||||
for await (const chunk of response.body) frames.push(decoder.decode(chunk, { stream: true }));
|
||||
} catch {
|
||||
// Aborting the request is how the test ends the stream.
|
||||
}
|
||||
});
|
||||
|
||||
return { ready, frames, stop: () => controller.abort(), done };
|
||||
}
|
||||
|
||||
/** Events land asynchronously; give the socket a moment to deliver. */
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 120));
|
||||
|
||||
describe('event topics', () => {
|
||||
it('routes a write to the pages that care about it', () => {
|
||||
assert.equal(topicForPath('/api/deploy/targets/3/run'), 'deployments');
|
||||
assert.equal(topicForPath('/api/deployments'), 'deployments');
|
||||
assert.equal(topicForPath('/api/repositories/FWS/Arch/issues'), 'gitea');
|
||||
assert.equal(topicForPath('/api/organization'), 'gitea');
|
||||
assert.equal(topicForPath('/api/discord/announce'), 'discord');
|
||||
assert.equal(topicForPath('/api/community/tickets/1/close'), 'community');
|
||||
assert.equal(topicForPath('/api/settings/values/x'), 'settings');
|
||||
assert.equal(topicForPath('/api/auth/logout'), 'mutation');
|
||||
});
|
||||
|
||||
it('does nothing when nobody is listening', () => {
|
||||
assert.equal(broadcast('tick', {}), 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('event stream', () => {
|
||||
let server;
|
||||
let base;
|
||||
|
||||
before(async () => {
|
||||
initDatabase(':memory:');
|
||||
createApiToken({
|
||||
name: 'events',
|
||||
tokenHash: hashToken(TOKEN),
|
||||
prefix: TOKEN.slice(0, 12),
|
||||
accessLevel: ACCESS_LEVELS.OWNER,
|
||||
});
|
||||
|
||||
server = createServer(createHandler({ client: null, setupOnly: false }));
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
base = `http://127.0.0.1:${server.address().port}`;
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
closeEventStreams();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'));
|
||||
|
||||
it('refuses an anonymous listener', async () => {
|
||||
const response = await fetch(`${base}/api/events`);
|
||||
assert.equal(response.status, 401);
|
||||
});
|
||||
|
||||
it('greets a subscriber and counts it', async () => {
|
||||
const stream = openStream(`${base}/api/events`);
|
||||
await stream.ready;
|
||||
await settle();
|
||||
|
||||
assert.equal(subscriberCount(), 1);
|
||||
assert.match(stream.frames.join(''), /event: ready/);
|
||||
assert.match(stream.frames.join(''), /retry: 5000/);
|
||||
|
||||
stream.stop();
|
||||
await settle();
|
||||
assert.equal(subscriberCount(), 0);
|
||||
});
|
||||
|
||||
it('pushes a broadcast to the open streams', async () => {
|
||||
const stream = openStream(`${base}/api/events`);
|
||||
await stream.ready;
|
||||
await settle();
|
||||
|
||||
assert.equal(broadcast('deployments', { id: 7, status: 'running' }), 1);
|
||||
await settle();
|
||||
|
||||
const received = stream.frames.join('');
|
||||
assert.match(received, /event: deployments/);
|
||||
assert.match(received, /"id":7/);
|
||||
assert.match(received, /"topic":"deployments"/);
|
||||
|
||||
stream.stop();
|
||||
await settle();
|
||||
});
|
||||
|
||||
it('announces a successful write, and only once it succeeded', async () => {
|
||||
const stream = openStream(`${base}/api/events`);
|
||||
await stream.ready;
|
||||
await settle();
|
||||
|
||||
const write = (body) =>
|
||||
fetch(`${base}/api/deploy/targets`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const rejected = await write({ name: '', repository: 'nope', kind: 'webhook' });
|
||||
assert.equal(rejected.status, 400);
|
||||
await settle();
|
||||
assert.doesNotMatch(stream.frames.join(''), /event: deployments/);
|
||||
|
||||
const accepted = await write({
|
||||
name: 'production',
|
||||
repository: 'FWS/FWS-Arch',
|
||||
kind: 'webhook',
|
||||
config: { url: 'https://deploy.example/hook' },
|
||||
});
|
||||
assert.equal(accepted.status, 200);
|
||||
await settle();
|
||||
|
||||
const received = stream.frames.join('');
|
||||
assert.match(received, /event: deployments/);
|
||||
assert.match(received, /"method":"POST"/);
|
||||
|
||||
stream.stop();
|
||||
await settle();
|
||||
});
|
||||
|
||||
it('stays silent on a read', async () => {
|
||||
const stream = openStream(`${base}/api/events`);
|
||||
await stream.ready;
|
||||
await settle();
|
||||
|
||||
await fetch(`${base}/api/deployments`, { headers: { Authorization: `Bearer ${TOKEN}` } });
|
||||
await settle();
|
||||
assert.doesNotMatch(stream.frames.join(''), /event: deployments/);
|
||||
|
||||
stream.stop();
|
||||
await settle();
|
||||
});
|
||||
|
||||
it('serves several dashboards at once', async () => {
|
||||
const first = openStream(`${base}/api/events`);
|
||||
const second = openStream(`${base}/api/events`);
|
||||
await Promise.all([first.ready, second.ready]);
|
||||
await settle();
|
||||
|
||||
assert.equal(broadcast('gitea', { event: 'push' }), 2);
|
||||
await settle();
|
||||
|
||||
assert.match(first.frames.join(''), /event: gitea/);
|
||||
assert.match(second.frames.join(''), /event: gitea/);
|
||||
|
||||
first.stop();
|
||||
second.stop();
|
||||
await settle();
|
||||
assert.equal(subscriberCount(), 0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user