BlueGit

timfa filemanager

feat: show Restart/Restart & Update in admin panel when running under systemd

Detection: INVOCATION_ID env var is set by systemd for every managed service.

Backend:
- GET /api/admin/update-status — checks INVOCATION_ID, runs git fetch +
  git log HEAD..origin/HEAD --oneline, returns { underSystemd, commitsAhead[] }
- No changes to POST /api/admin/shutdown — start.sh already does git pull +
  npm install on every boot, so systemd restart handles updates automatically

Frontend (public/app.js):
- showConfirm() extended with { html, okLabel } options; adds escHtml() helper
- refreshAdminUpdateStatus() fetches update-status and sets button label to
  'Shut down server' / 'Restart Server' / 'Restart & Update'
- openAdminModal() fires refreshAdminUpdateStatus() in parallel (non-blocking)
- Shutdown button adapts confirm dialog text and toast message to context

Tests: 4 new tests in admin.routes.test.js (142 total, all passing)
Docs: technical-reference.md and tests.md updated

timfa Tim Falken · pushed by timfa

Authored 2026-05-10 · 6 months ago

Hash
2c97d091cb1ad8d623a67564d60d3f3a7d3f9b5e
Parent
2984b2dc
5 files changed +210 −7
.github/technical-reference.md +3 −1
@@ -41,6 +41,7 @@
41 41 ## server/routes/admin.js
42 42 - POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
43 43 - normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
44 - GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
44 45
45 46 ## server/routes/files.js
46 47 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -108,7 +109,8 @@
108 109 - api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
109 110 - performLogout() - Explicit logout path that revokes server session and clears local session state.
110 111 - initAuth() - Restores prior session when valid and auto-logins without credential prompt.
111 - showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
112 - showConfirm(title, message, { html, okLabel }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data). `okLabel` overrides the OK button text. Use instead of window.confirm().
113 - escHtml(s) - HTML-escapes a string (& < > ") for safe use with innerHTML in confirm messages.
112 114 - showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
113 115 - showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
114 116 - splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
@@ -41,6 +41,7 @@
41## server/routes/admin.js
41## server/routes/admin.js
42- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
42- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
43- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
43- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
44- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
44
45
45## server/routes/files.js
46## server/routes/files.js
46- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
47- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -108,7 +109,8 @@
108- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
109- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
109- performLogout() - Explicit logout path that revokes server session and clears local session state.
110- performLogout() - Explicit logout path that revokes server session and clears local session state.
110- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
111- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
111- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
112- showConfirm(title, message, { html, okLabel }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data). `okLabel` overrides the OK button text. Use instead of window.confirm().
113- escHtml(s) - HTML-escapes a string (& < > ") for safe use with innerHTML in confirm messages.
112- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
114- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
113- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
115- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
114- splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
116- splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
.github/tests.md +1 −0
@@ -13,6 +13,7 @@
13 13 - `GET /api/admin/config`
14 14 - `PUT /api/admin/config`
15 15 - `POST /api/admin/shutdown`
16 - `GET /api/admin/update-status`
16 17
17 18 ---
18 19
@@ -13,6 +13,7 @@
13- `GET /api/admin/config`
13- `GET /api/admin/config`
14- `PUT /api/admin/config`
14- `PUT /api/admin/config`
15- `POST /api/admin/shutdown`
15- `POST /api/admin/shutdown`
16- `GET /api/admin/update-status`
16
17
17---
18---
18
19
public/app.js +84 −6
@@ -770,21 +770,27 @@ function toast (msg, type = '')
770 770 * @param {string} message
771 771 * @returns {Promise<boolean>} true = OK, false = Cancel
772 772 */
773 function showConfirm (title, message)
773 function showConfirm (title, message, { html = false, okLabel = null } = {})
774 774 {
775 775 return new Promise((resolve) =>
776 776 {
777 777 const overlay = document.getElementById('confirm-modal');
778 778 document.getElementById('confirm-modal-title').textContent = title;
779 document.getElementById('confirm-modal-message').textContent = message;
779 const msgEl = document.getElementById('confirm-modal-message');
780 if (html) msgEl.innerHTML = message;
781 else msgEl.textContent = message;
780 782 overlay.classList.remove('hidden');
781 783
782 784 const ok = document.getElementById('confirm-modal-ok');
785 const prevOkLabel = ok.textContent;
786 if (okLabel != null) ok.textContent = okLabel;
787
783 788 const cancel = document.getElementById('confirm-modal-cancel');
784 789
785 790 function finish (result)
786 791 {
787 792 overlay.classList.add('hidden');
793 ok.textContent = prevOkLabel;
788 794 ok.removeEventListener('click', onOk);
789 795 cancel.removeEventListener('click', onCancel);
790 796 resolve(result);
@@ -798,6 +804,15 @@ function showConfirm (title, message)
798 804 });
799 805 }
800 806
807 function escHtml (s)
808 {
809 return String(s || '')
810 .replace(/&/g, '&amp;')
811 .replace(/</g, '&lt;')
812 .replace(/>/g, '&gt;')
813 .replace(/"/g, '&quot;');
814 }
815
801 816 /**
802 817 * Show a text-input dialog.
803 818 * @param {string} title
@@ -3529,11 +3544,14 @@ async function deleteItem (item)
3529 3544 // ADMIN PANEL
3530 3545 // ───────────────────────────────────────────────────────────────────────────
3531 3546
3547 let _adminUpdateStatus = null;
3548
3532 3549 async function openAdminModal ()
3533 3550 {
3534 3551 document.getElementById('admin-modal').classList.remove('hidden');
3535 3552 await refreshAdminConfig();
3536 3553 await refreshAdminUsers();
3554 void refreshAdminUpdateStatus();
3537 3555 }
3538 3556
3539 3557 async function refreshAdminConfig ()
@@ -3593,6 +3611,37 @@ async function refreshAdminUsers ()
3593 3611 }
3594 3612 }
3595 3613
3614 async function refreshAdminUpdateStatus ()
3615 {
3616 const btn = document.getElementById('admin-shutdown-btn');
3617 _adminUpdateStatus = null;
3618 btn.textContent = 'Shut down server';
3619
3620 try
3621 {
3622 const data = await api('GET', '/admin/update-status');
3623 if (!data) return;
3624 _adminUpdateStatus = data;
3625
3626 if (!data.underSystemd)
3627 {
3628 btn.textContent = 'Shut down server';
3629 }
3630 else if (data.commitsAhead.length === 0)
3631 {
3632 btn.textContent = 'Restart Server';
3633 }
3634 else
3635 {
3636 btn.textContent = 'Restart & Update';
3637 }
3638 }
3639 catch
3640 {
3641 // Not critical; button stays as "Shut down server".
3642 }
3643 }
3644
3596 3645 function openUserModal (user, paths)
3597 3646 {
3598 3647 const modal = document.getElementById('user-modal');
@@ -4357,19 +4406,48 @@ function wireEvents ()
4357 4406 } catch (err) { toast(err.message, 'err'); }
4358 4407 });
4359 4408
4360 // Shutdown server
4409 // Shutdown / restart server
4361 4410 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4362 4411 {
4363 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4412 const status = _adminUpdateStatus;
4413
4414 if (!status || !status.underSystemd)
4415 {
4416 // Not running under systemd — plain shutdown (manual restart required).
4417 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4418 }
4419 else if (status.commitsAhead.length === 0)
4420 {
4421 // Under systemd, no updates — restart only.
4422 if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return;
4423 }
4424 else
4425 {
4426 // Under systemd, updates available.
4427 const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>');
4428 const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`;
4429 if (!await showConfirm('Restart &amp; Update', msg, { html: true, okLabel: 'Update now' })) return;
4430 }
4431
4364 4432 try
4365 4433 {
4366 4434 await api('POST', '/admin/shutdown');
4367 toast('Server is shutting down…', 'ok');
4435 const toastMsg = (!status || !status.underSystemd)
4436 ? 'Server is shutting down\u2026'
4437 : status.commitsAhead.length > 0
4438 ? 'Server is updating and restarting\u2026'
4439 : 'Server is restarting\u2026';
4440 toast(toastMsg, 'ok');
4368 4441 document.getElementById('admin-modal').classList.add('hidden');
4369 4442 } catch
4370 4443 {
4371 4444 // Fetch may throw because the connection closes before a response arrives.
4372 toast('Server is shutting down…', 'ok');
4445 const toastMsg = (!status || !status.underSystemd)
4446 ? 'Server is shutting down\u2026'
4447 : status.commitsAhead.length > 0
4448 ? 'Server is updating and restarting\u2026'
4449 : 'Server is restarting\u2026';
4450 toast(toastMsg, 'ok');
4373 4451 document.getElementById('admin-modal').classList.add('hidden');
4374 4452 }
4375 4453 });
@@ -770,21 +770,27 @@ function toast (msg, type = '')
770 * @param {string} message
770 * @param {string} message
771 * @returns {Promise<boolean>} true = OK, false = Cancel
771 * @returns {Promise<boolean>} true = OK, false = Cancel
772 */
772 */
773function showConfirm (title, message)
773function showConfirm (title, message, { html = false, okLabel = null } = {})
774{
774{
775 return new Promise((resolve) =>
775 return new Promise((resolve) =>
776 {
776 {
777 const overlay = document.getElementById('confirm-modal');
777 const overlay = document.getElementById('confirm-modal');
778 document.getElementById('confirm-modal-title').textContent = title;
778 document.getElementById('confirm-modal-title').textContent = title;
779 document.getElementById('confirm-modal-message').textContent = message;
779 const msgEl = document.getElementById('confirm-modal-message');
780 if (html) msgEl.innerHTML = message;
781 else msgEl.textContent = message;
780 overlay.classList.remove('hidden');
782 overlay.classList.remove('hidden');
781
783
782 const ok = document.getElementById('confirm-modal-ok');
784 const ok = document.getElementById('confirm-modal-ok');
785 const prevOkLabel = ok.textContent;
786 if (okLabel != null) ok.textContent = okLabel;
787
783 const cancel = document.getElementById('confirm-modal-cancel');
788 const cancel = document.getElementById('confirm-modal-cancel');
784
789
785 function finish (result)
790 function finish (result)
786 {
791 {
787 overlay.classList.add('hidden');
792 overlay.classList.add('hidden');
793 ok.textContent = prevOkLabel;
788 ok.removeEventListener('click', onOk);
794 ok.removeEventListener('click', onOk);
789 cancel.removeEventListener('click', onCancel);
795 cancel.removeEventListener('click', onCancel);
790 resolve(result);
796 resolve(result);
@@ -798,6 +804,15 @@ function showConfirm (title, message)
798 });
804 });
799}
805}
800
806
807function escHtml (s)
808{
809 return String(s || '')
810 .replace(/&/g, '&amp;')
811 .replace(/</g, '&lt;')
812 .replace(/>/g, '&gt;')
813 .replace(/"/g, '&quot;');
814}
815
801/**
816/**
802 * Show a text-input dialog.
817 * Show a text-input dialog.
803 * @param {string} title
818 * @param {string} title
@@ -3529,11 +3544,14 @@ async function deleteItem (item)
3529// ADMIN PANEL
3544// ADMIN PANEL
3530// ───────────────────────────────────────────────────────────────────────────
3545// ───────────────────────────────────────────────────────────────────────────
3531
3546
3547let _adminUpdateStatus = null;
3548
3532async function openAdminModal ()
3549async function openAdminModal ()
3533{
3550{
3534 document.getElementById('admin-modal').classList.remove('hidden');
3551 document.getElementById('admin-modal').classList.remove('hidden');
3535 await refreshAdminConfig();
3552 await refreshAdminConfig();
3536 await refreshAdminUsers();
3553 await refreshAdminUsers();
3554 void refreshAdminUpdateStatus();
3537}
3555}
3538
3556
3539async function refreshAdminConfig ()
3557async function refreshAdminConfig ()
@@ -3593,6 +3611,37 @@ async function refreshAdminUsers ()
3593 }
3611 }
3594}
3612}
3595
3613
3614async function refreshAdminUpdateStatus ()
3615{
3616 const btn = document.getElementById('admin-shutdown-btn');
3617 _adminUpdateStatus = null;
3618 btn.textContent = 'Shut down server';
3619
3620 try
3621 {
3622 const data = await api('GET', '/admin/update-status');
3623 if (!data) return;
3624 _adminUpdateStatus = data;
3625
3626 if (!data.underSystemd)
3627 {
3628 btn.textContent = 'Shut down server';
3629 }
3630 else if (data.commitsAhead.length === 0)
3631 {
3632 btn.textContent = 'Restart Server';
3633 }
3634 else
3635 {
3636 btn.textContent = 'Restart & Update';
3637 }
3638 }
3639 catch
3640 {
3641 // Not critical; button stays as "Shut down server".
3642 }
3643}
3644
3596function openUserModal (user, paths)
3645function openUserModal (user, paths)
3597{
3646{
3598 const modal = document.getElementById('user-modal');
3647 const modal = document.getElementById('user-modal');
@@ -4357,19 +4406,48 @@ function wireEvents ()
4357 } catch (err) { toast(err.message, 'err'); }
4406 } catch (err) { toast(err.message, 'err'); }
4358 });
4407 });
4359
4408
4360 // Shutdown server
4409 // Shutdown / restart server
4361 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4410 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
4362 {
4411 {
4363 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4412 const status = _adminUpdateStatus;
4413
4414 if (!status || !status.underSystemd)
4415 {
4416 // Not running under systemd — plain shutdown (manual restart required).
4417 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
4418 }
4419 else if (status.commitsAhead.length === 0)
4420 {
4421 // Under systemd, no updates — restart only.
4422 if (!await showConfirm('Restart server', 'No update available. Would you like to restart?', { okLabel: 'Restart' })) return;
4423 }
4424 else
4425 {
4426 // Under systemd, updates available.
4427 const commitList = status.commitsAhead.map(c => escHtml(c)).join('<br/>');
4428 const msg = `Updates available:<br/><br/>${commitList}<br/><br/>Update now?`;
4429 if (!await showConfirm('Restart &amp; Update', msg, { html: true, okLabel: 'Update now' })) return;
4430 }
4431
4364 try
4432 try
4365 {
4433 {
4366 await api('POST', '/admin/shutdown');
4434 await api('POST', '/admin/shutdown');
4367 toast('Server is shutting down…', 'ok');
4435 const toastMsg = (!status || !status.underSystemd)
4436 ? 'Server is shutting down\u2026'
4437 : status.commitsAhead.length > 0
4438 ? 'Server is updating and restarting\u2026'
4439 : 'Server is restarting\u2026';
4440 toast(toastMsg, 'ok');
4368 document.getElementById('admin-modal').classList.add('hidden');
4441 document.getElementById('admin-modal').classList.add('hidden');
4369 } catch
4442 } catch
4370 {
4443 {
4371 // Fetch may throw because the connection closes before a response arrives.
4444 // Fetch may throw because the connection closes before a response arrives.
4372 toast('Server is shutting down…', 'ok');
4445 const toastMsg = (!status || !status.underSystemd)
4446 ? 'Server is shutting down\u2026'
4447 : status.commitsAhead.length > 0
4448 ? 'Server is updating and restarting\u2026'
4449 : 'Server is restarting\u2026';
4450 toast(toastMsg, 'ok');
4373 document.getElementById('admin-modal').classList.add('hidden');
4451 document.getElementById('admin-modal').classList.add('hidden');
4374 }
4452 }
4375 });
4453 });
server/routes/admin.js +33 −0
@@ -3,8 +3,13 @@
3 3 const express = require('express');
4 4 const bcrypt = require('bcrypt');
5 5 const path = require('path');
6 const { execFile } = require('child_process');
7 const { promisify } = require('util');
6 8 const router = express.Router();
7 9
10 const execFileAsync = promisify(execFile);
11 const PROJECT_ROOT = path.resolve(__dirname, '../../');
12
8 13 const { getDb } = require('../db');
9 14 const { requireAuth, requireAdmin } = require('../auth');
10 15 const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
@@ -188,6 +193,34 @@ router.put('/config', (req, res) =>
188 193 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
189 194 });
190 195
196 // ---------------------------------------------------------------------------
197 // GET /api/admin/update-status
198 // Returns whether the process is running under systemd and whether the git
199 // remote is ahead of the local checkout.
200 // ---------------------------------------------------------------------------
201 router.get('/update-status', async (req, res) =>
202 {
203 const underSystemd = !!process.env.INVOCATION_ID;
204 if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] });
205
206 let commitsAhead = [];
207 try
208 {
209 await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT });
210 const { stdout } = await execFileAsync(
211 'git', ['log', 'HEAD..origin/HEAD', '--oneline', '--no-decorate'],
212 { cwd: PROJECT_ROOT },
213 );
214 commitsAhead = stdout.trim().split('\n').filter(Boolean);
215 }
216 catch
217 {
218 // git may not be available or repo may not have a remote — return empty list.
219 }
220
221 res.json({ underSystemd: true, commitsAhead });
222 });
223
191 224 // ---------------------------------------------------------------------------
192 225 // POST /api/admin/shutdown
193 226 // Responds immediately then gracefully closes the server and DB.
@@ -3,8 +3,13 @@
3const express = require('express');
3const express = require('express');
4const bcrypt = require('bcrypt');
4const bcrypt = require('bcrypt');
5const path = require('path');
5const path = require('path');
6const { execFile } = require('child_process');
7const { promisify } = require('util');
6const router = express.Router();
8const router = express.Router();
7
9
10const execFileAsync = promisify(execFile);
11const PROJECT_ROOT = path.resolve(__dirname, '../../');
12
8const { getDb } = require('../db');
13const { getDb } = require('../db');
9const { requireAuth, requireAdmin } = require('../auth');
14const { requireAuth, requireAdmin } = require('../auth');
10const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
15const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
@@ -188,6 +193,34 @@ router.put('/config', (req, res) =>
188 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
193 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
189});
194});
190
195
196// ---------------------------------------------------------------------------
197// GET /api/admin/update-status
198// Returns whether the process is running under systemd and whether the git
199// remote is ahead of the local checkout.
200// ---------------------------------------------------------------------------
201router.get('/update-status', async (req, res) =>
202{
203 const underSystemd = !!process.env.INVOCATION_ID;
204 if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] });
205
206 let commitsAhead = [];
207 try
208 {
209 await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT });
210 const { stdout } = await execFileAsync(
211 'git', ['log', 'HEAD..origin/HEAD', '--oneline', '--no-decorate'],
212 { cwd: PROJECT_ROOT },
213 );
214 commitsAhead = stdout.trim().split('\n').filter(Boolean);
215 }
216 catch
217 {
218 // git may not be available or repo may not have a remote — return empty list.
219 }
220
221 res.json({ underSystemd: true, commitsAhead });
222});
223
191// ---------------------------------------------------------------------------
224// ---------------------------------------------------------------------------
192// POST /api/admin/shutdown
225// POST /api/admin/shutdown
193// Responds immediately then gracefully closes the server and DB.
226// Responds immediately then gracefully closes the server and DB.
tests/admin.routes.test.js +89 −0
@@ -9,6 +9,27 @@ const http = require('http');
9 9 const { once } = require('events');
10 10 const crypto = require('crypto');
11 11
12 // ── child_process mock — controlled per test ──────────────────────────────────
13 let mockExecFileImpl = null;
14 jest.mock('child_process', () =>
15 {
16 const real = jest.requireActual('child_process');
17 return {
18 ...real,
19 execFile: jest.fn((...args) =>
20 {
21 const cb = args[args.length - 1];
22 if (typeof mockExecFileImpl === 'function')
23 {
24 mockExecFileImpl(...args);
25 return;
26 }
27 // Default: simulate git not available.
28 cb(new Error('git not found'));
29 }),
30 };
31 });
32
12 33 // ── in-memory DB mock ───────────────────────────────────────────────────────
13 34 jest.mock('../server/db', () =>
14 35 {
@@ -312,3 +333,71 @@ describe('POST /api/admin/shutdown', () =>
312 333 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
313 334 });
314 335 });
336
337 describe('GET /api/admin/update-status', () =>
338 {
339 const origInvocationId = process.env.INVOCATION_ID;
340
341 afterEach(() =>
342 {
343 mockExecFileImpl = null;
344 if (origInvocationId === undefined)
345 delete process.env.INVOCATION_ID;
346 else
347 process.env.INVOCATION_ID = origInvocationId;
348 });
349
350 test('returns underSystemd=false when INVOCATION_ID is not set', async () =>
351 {
352 delete process.env.INVOCATION_ID;
353 const { status, body } = await req('GET', '/api/admin/update-status');
354 expect(status).toBe(200);
355 expect(body.underSystemd).toBe(false);
356 expect(body.commitsAhead).toEqual([]);
357 });
358
359 test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () =>
360 {
361 process.env.INVOCATION_ID = 'test-invocation-id';
362 // git fetch succeeds, then git log returns two commits.
363 let callCount = 0;
364 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
365 {
366 callCount++;
367 if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch
368 else cb(null, { stdout: 'abc1234 Fix bug\ndef5678 Add feature\n', stderr: '' }); // git log
369 };
370 const { status, body } = await req('GET', '/api/admin/update-status');
371 expect(status).toBe(200);
372 expect(body.underSystemd).toBe(true);
373 expect(body.commitsAhead).toEqual(['abc1234 Fix bug', 'def5678 Add feature']);
374 });
375
376 test('returns underSystemd=true and empty commitsAhead when git is up to date', async () =>
377 {
378 process.env.INVOCATION_ID = 'test-invocation-id';
379 let callCount = 0;
380 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
381 {
382 callCount++;
383 cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty
384 };
385 const { status, body } = await req('GET', '/api/admin/update-status');
386 expect(status).toBe(200);
387 expect(body.underSystemd).toBe(true);
388 expect(body.commitsAhead).toEqual([]);
389 });
390
391 test('returns underSystemd=true and empty commitsAhead when git fails', async () =>
392 {
393 process.env.INVOCATION_ID = 'test-invocation-id';
394 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
395 {
396 cb(new Error('git: not found'));
397 };
398 const { status, body } = await req('GET', '/api/admin/update-status');
399 expect(status).toBe(200);
400 expect(body.underSystemd).toBe(true);
401 expect(body.commitsAhead).toEqual([]);
402 });
403 });
@@ -9,6 +9,27 @@ const http = require('http');
9const { once } = require('events');
9const { once } = require('events');
10const crypto = require('crypto');
10const crypto = require('crypto');
11
11
12// ── child_process mock — controlled per test ──────────────────────────────────
13let mockExecFileImpl = null;
14jest.mock('child_process', () =>
15{
16 const real = jest.requireActual('child_process');
17 return {
18 ...real,
19 execFile: jest.fn((...args) =>
20 {
21 const cb = args[args.length - 1];
22 if (typeof mockExecFileImpl === 'function')
23 {
24 mockExecFileImpl(...args);
25 return;
26 }
27 // Default: simulate git not available.
28 cb(new Error('git not found'));
29 }),
30 };
31});
32
12// ── in-memory DB mock ───────────────────────────────────────────────────────
33// ── in-memory DB mock ───────────────────────────────────────────────────────
13jest.mock('../server/db', () =>
34jest.mock('../server/db', () =>
14{
35{
@@ -312,3 +333,71 @@ describe('POST /api/admin/shutdown', () =>
312 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
333 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
313 });
334 });
314});
335});
336
337describe('GET /api/admin/update-status', () =>
338{
339 const origInvocationId = process.env.INVOCATION_ID;
340
341 afterEach(() =>
342 {
343 mockExecFileImpl = null;
344 if (origInvocationId === undefined)
345 delete process.env.INVOCATION_ID;
346 else
347 process.env.INVOCATION_ID = origInvocationId;
348 });
349
350 test('returns underSystemd=false when INVOCATION_ID is not set', async () =>
351 {
352 delete process.env.INVOCATION_ID;
353 const { status, body } = await req('GET', '/api/admin/update-status');
354 expect(status).toBe(200);
355 expect(body.underSystemd).toBe(false);
356 expect(body.commitsAhead).toEqual([]);
357 });
358
359 test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () =>
360 {
361 process.env.INVOCATION_ID = 'test-invocation-id';
362 // git fetch succeeds, then git log returns two commits.
363 let callCount = 0;
364 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
365 {
366 callCount++;
367 if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch
368 else cb(null, { stdout: 'abc1234 Fix bug\ndef5678 Add feature\n', stderr: '' }); // git log
369 };
370 const { status, body } = await req('GET', '/api/admin/update-status');
371 expect(status).toBe(200);
372 expect(body.underSystemd).toBe(true);
373 expect(body.commitsAhead).toEqual(['abc1234 Fix bug', 'def5678 Add feature']);
374 });
375
376 test('returns underSystemd=true and empty commitsAhead when git is up to date', async () =>
377 {
378 process.env.INVOCATION_ID = 'test-invocation-id';
379 let callCount = 0;
380 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
381 {
382 callCount++;
383 cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty
384 };
385 const { status, body } = await req('GET', '/api/admin/update-status');
386 expect(status).toBe(200);
387 expect(body.underSystemd).toBe(true);
388 expect(body.commitsAhead).toEqual([]);
389 });
390
391 test('returns underSystemd=true and empty commitsAhead when git fails', async () =>
392 {
393 process.env.INVOCATION_ID = 'test-invocation-id';
394 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
395 {
396 cb(new Error('git: not found'));
397 };
398 const { status, body } = await req('GET', '/api/admin/update-status');
399 expect(status).toBe(200);
400 expect(body.underSystemd).toBe(true);
401 expect(body.commitsAhead).toEqual([]);
402 });
403});