Skip to content

Commit f59c533

Browse files
Add version tracking and one-click admin self-update
The deployment is a git checkout, so the version is the checked-out commit SHA. New admin tooling: - API: services/version.ts reads the local SHA (git), compares it to the tracked GitHub branch (latest commit + 'behind by N' via the compare API), exposes GET /admin/version (with opt-in ?check=1 remote lookup) and POST /admin/update. - scripts/self-update.sh: spawned detached by the update route — git reset to the branch, deploy.sh (rebuild + migrate), then pm2 reload. Survives the restart it triggers and writes progress to .update-status.json (read back by the API). - Web: admin 'Version & mises à jour' panel showing the current build, a Check button, an update-available banner with commit count, and a one-click Update button. Polling tolerates the mid-update API restart. - Config: GITHUB_REPO / UPDATE_BRANCH / GITHUB_TOKEN / SELF_UPDATE_ENABLED.
1 parent 5f2cb34 commit f59c533

8 files changed

Lines changed: 544 additions & 0 deletions

File tree

‎.env.example‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,13 @@ CLAMAV_PORT=3310
7878
# ── VirusTotal — optional ────────────────────────────────────────────────────
7979
# Leave empty to disable. With a key, files can be checked by hash on demand.
8080
VIRUSTOTAL_API_KEY=
81+
82+
# ── Version tracking & self-update ───────────────────────────────────────────
83+
# The admin panel reads the deployed git SHA, compares it to this GitHub repo/branch,
84+
# and can trigger an in-place update (git reset + rebuild + PM2 reload).
85+
GITHUB_REPO=softpython2884/OpenCoperLock
86+
UPDATE_BRANCH=main
87+
# Optional read-only token to raise GitHub's API rate limit for update checks.
88+
GITHUB_TOKEN=
89+
# Set to false where updates are managed externally; disables the one-click update button.
90+
SELF_UPDATE_ENABLED=true

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,5 @@ test-results/
5151
.vscode/*
5252
!.vscode/extensions.json
5353
Thumbs.db
54+
/.update-status.json
55+
/.update.log

‎apps/api/src/env.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ const envSchema = z.object({
5555
CLAMAV_PORT: z.coerce.number().int().positive().default(3310),
5656

5757
VIRUSTOTAL_API_KEY: z.string().optional().default(''),
58+
59+
// ── Version tracking & self-update ──────────────────────────────────────────
60+
// The GitHub repo to check for new versions, and the branch we track.
61+
GITHUB_REPO: z.string().default('softpython2884/OpenCoperLock'),
62+
UPDATE_BRANCH: z.string().default('main'),
63+
// Optional token to raise GitHub's unauthenticated rate limit (read-only is enough).
64+
GITHUB_TOKEN: z.string().optional().default(''),
65+
// Gate the one-click admin self-update. Disable on hosts where updates are managed
66+
// externally (e.g. CI/CD) so the button can't trigger an in-place rebuild.
67+
SELF_UPDATE_ENABLED: z
68+
.enum(['true', 'false'])
69+
.default('true')
70+
.transform((v) => v === 'true'),
5871
});
5972

6073
export type Env = z.infer<typeof envSchema> & { masterKey: Buffer };

‎apps/api/src/routes/admin.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ import { toPublicQuickCode, toPublicUser } from '../lib/serialize.js';
1313
import { getGlobalCapBytes, getGlobalUsedBytes } from '../services/quota.js';
1414
import { ensureFastUploadFolder } from '../services/systemFolders.js';
1515
import { runMaintenance } from '../services/maintenance.js';
16+
import {
17+
commitsBehind,
18+
getLocalVersion,
19+
getRemoteVersion,
20+
readUpdateStatus,
21+
startUpdate,
22+
} from '../services/version.js';
1623
import { audit } from '../services/audit.js';
1724

1825
const GLOBAL_SETTING_ID = 'global';
@@ -141,6 +148,38 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
141148
return { warnings, infectedCount };
142149
});
143150

151+
// ── Version & self-update ────────────────────────────────────────────────--
152+
// GET /admin/version — current build, last update attempt, and (with ?check=1) the
153+
// latest version available on GitHub. The remote check is opt-in to avoid hitting the
154+
// GitHub rate limit on every admin page load.
155+
app.get('/version', async (req) => {
156+
const { check } = req.query as { check?: string };
157+
const local = await getLocalVersion();
158+
const status = readUpdateStatus();
159+
const base = {
160+
current: local,
161+
status,
162+
selfUpdateEnabled: app.ctx.env.SELF_UPDATE_ENABLED,
163+
repo: app.ctx.env.GITHUB_REPO,
164+
branch: app.ctx.env.UPDATE_BRANCH,
165+
};
166+
if (check !== '1') return { ...base, checked: false };
167+
168+
const remote = await getRemoteVersion(app.ctx.env);
169+
if (!remote) return { ...base, checked: true, remote: null, updateAvailable: false, behindBy: null };
170+
const updateAvailable = local.sha !== null && local.sha !== remote.sha;
171+
const behindBy = local.sha ? await commitsBehind(app.ctx.env, local.sha, remote.sha) : null;
172+
return { ...base, checked: true, remote, updateAvailable, behindBy };
173+
});
174+
175+
// POST /admin/update — trigger an in-place update (git reset + rebuild + PM2 reload).
176+
app.post('/update', async (req, reply) => {
177+
const result = startUpdate(app.ctx.env);
178+
if (!result.ok) return reply.code(409).send({ error: result.error });
179+
await audit(req, 'admin.update.start');
180+
return reply.code(202).send({ ok: true });
181+
});
182+
144183
// ── Maintenance (manual trigger) ─────────────────────────────────────────--
145184
app.post('/maintenance', async (req) => {
146185
const summary = await runMaintenance(app.ctx, req.log);

‎apps/api/src/services/version.ts‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/**
2+
* Version tracking & one-click self-update.
3+
*
4+
* The deployment is a plain git checkout, so the "version" is simply the checked-out commit
5+
* SHA. We read it at runtime, compare it against the tracked branch on GitHub, and — for
6+
* admins — kick off an in-place update (git reset + rebuild + PM2 reload) by spawning a
7+
* detached script that survives the API restart.
8+
*/
9+
import { execFile } from 'node:child_process';
10+
import { promisify } from 'node:util';
11+
import { spawn } from 'node:child_process';
12+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
13+
import { dirname, join, resolve } from 'node:path';
14+
import type { Env } from '../env.js';
15+
16+
const exec = promisify(execFile);
17+
18+
export interface LocalVersion {
19+
sha: string | null;
20+
shortSha: string | null;
21+
subject: string | null;
22+
committedAt: string | null;
23+
branch: string | null;
24+
/** True when the checkout is a real git repo we can read/update. */
25+
isGit: boolean;
26+
}
27+
28+
export interface RemoteVersion {
29+
sha: string;
30+
shortSha: string;
31+
subject: string;
32+
committedAt: string | null;
33+
htmlUrl: string;
34+
}
35+
36+
export interface UpdateStatus {
37+
state: 'idle' | 'running' | 'success' | 'failed';
38+
startedAt: string | null;
39+
finishedAt: string | null;
40+
message: string | null;
41+
}
42+
43+
/** Walk up from the API's working directory to the repository root (the dir holding .git). */
44+
function findRepoRoot(): string | null {
45+
let dir = process.cwd();
46+
for (let i = 0; i < 8; i += 1) {
47+
if (existsSync(join(dir, '.git'))) return dir;
48+
const parent = dirname(dir);
49+
if (parent === dir) break;
50+
dir = parent;
51+
}
52+
return null;
53+
}
54+
55+
const repoRoot = findRepoRoot();
56+
let cachedLocal: LocalVersion | null = null;
57+
58+
export async function getLocalVersion(): Promise<LocalVersion> {
59+
if (cachedLocal) return cachedLocal;
60+
if (!repoRoot) {
61+
cachedLocal = { sha: null, shortSha: null, subject: null, committedAt: null, branch: null, isGit: false };
62+
return cachedLocal;
63+
}
64+
try {
65+
const { stdout } = await exec('git', ['log', '-1', '--format=%H%x1f%h%x1f%cI%x1f%s'], { cwd: repoRoot });
66+
const [sha, shortSha, committedAt, subject] = stdout.trim().split('\x1f');
67+
let branch: string | null = null;
68+
try {
69+
const b = await exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoRoot });
70+
branch = b.stdout.trim();
71+
} catch {
72+
/* detached HEAD or no branch — leave null */
73+
}
74+
cachedLocal = {
75+
sha: sha ?? null,
76+
shortSha: shortSha ?? null,
77+
committedAt: committedAt ?? null,
78+
subject: subject ?? null,
79+
branch,
80+
isGit: true,
81+
};
82+
} catch {
83+
cachedLocal = { sha: null, shortSha: null, subject: null, committedAt: null, branch: null, isGit: false };
84+
}
85+
return cachedLocal;
86+
}
87+
88+
interface GithubCommit {
89+
sha: string;
90+
html_url: string;
91+
commit: { message: string; committer?: { date?: string } };
92+
}
93+
94+
/** Fetch the latest commit of the tracked branch from GitHub. Returns null on any failure. */
95+
export async function getRemoteVersion(env: Env): Promise<RemoteVersion | null> {
96+
const headers: Record<string, string> = {
97+
Accept: 'application/vnd.github+json',
98+
'User-Agent': 'OpenCoperLock',
99+
'X-GitHub-Api-Version': '2022-11-28',
100+
};
101+
if (env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`;
102+
try {
103+
const res = await fetch(
104+
`https://api.github.com/repos/${env.GITHUB_REPO}/commits/${encodeURIComponent(env.UPDATE_BRANCH)}`,
105+
{ headers, signal: AbortSignal.timeout(8000) },
106+
);
107+
if (!res.ok) return null;
108+
const c = (await res.json()) as GithubCommit;
109+
return {
110+
sha: c.sha,
111+
shortSha: c.sha.slice(0, 7),
112+
subject: c.commit.message.split('\n')[0] ?? '',
113+
committedAt: c.commit.committer?.date ?? null,
114+
htmlUrl: c.html_url,
115+
};
116+
} catch {
117+
return null;
118+
}
119+
}
120+
121+
/** How many commits the local checkout is behind `head`, via the GitHub compare API. */
122+
export async function commitsBehind(env: Env, base: string, head: string): Promise<number | null> {
123+
if (base === head) return 0;
124+
const headers: Record<string, string> = {
125+
Accept: 'application/vnd.github+json',
126+
'User-Agent': 'OpenCoperLock',
127+
};
128+
if (env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`;
129+
try {
130+
const res = await fetch(
131+
`https://api.github.com/repos/${env.GITHUB_REPO}/compare/${base}...${head}`,
132+
{ headers, signal: AbortSignal.timeout(8000) },
133+
);
134+
if (!res.ok) return null;
135+
const data = (await res.json()) as { ahead_by?: number };
136+
return typeof data.ahead_by === 'number' ? data.ahead_by : null;
137+
} catch {
138+
return null;
139+
}
140+
}
141+
142+
const STATUS_FILE = repoRoot ? resolve(repoRoot, '.update-status.json') : null;
143+
144+
export function readUpdateStatus(): UpdateStatus {
145+
const idle: UpdateStatus = { state: 'idle', startedAt: null, finishedAt: null, message: null };
146+
if (!STATUS_FILE || !existsSync(STATUS_FILE)) return idle;
147+
try {
148+
const raw = JSON.parse(readFileSync(STATUS_FILE, 'utf8')) as Partial<UpdateStatus>;
149+
return {
150+
state: raw.state ?? 'idle',
151+
startedAt: raw.startedAt ?? null,
152+
finishedAt: raw.finishedAt ?? null,
153+
message: raw.message ?? null,
154+
};
155+
} catch {
156+
return idle;
157+
}
158+
}
159+
160+
export interface StartUpdateResult {
161+
ok: boolean;
162+
error?: string;
163+
}
164+
165+
/** Spawn the detached self-update script. It survives the PM2 reload it triggers. */
166+
export function startUpdate(env: Env): StartUpdateResult {
167+
if (!env.SELF_UPDATE_ENABLED) return { ok: false, error: 'Self-update is disabled on this instance.' };
168+
if (!repoRoot) return { ok: false, error: 'This deployment is not a git checkout; update it manually.' };
169+
if (readUpdateStatus().state === 'running') return { ok: false, error: 'An update is already running.' };
170+
171+
const script = join(repoRoot, 'scripts', 'self-update.sh');
172+
if (!existsSync(script)) return { ok: false, error: 'Update script not found (scripts/self-update.sh).' };
173+
174+
// Mark running immediately so the UI reflects it before the script writes its own status.
175+
if (STATUS_FILE) {
176+
try {
177+
writeFileSync(
178+
STATUS_FILE,
179+
JSON.stringify({ state: 'running', startedAt: new Date().toISOString(), finishedAt: null, message: 'Démarrage…' }),
180+
);
181+
} catch {
182+
/* best effort */
183+
}
184+
}
185+
186+
const child = spawn('bash', [script], {
187+
cwd: repoRoot,
188+
detached: true,
189+
stdio: 'ignore',
190+
env: { ...process.env, UPDATE_BRANCH: env.UPDATE_BRANCH },
191+
});
192+
child.unref();
193+
return { ok: true };
194+
}

0 commit comments

Comments
 (0)