desktop install: stop the running app by exact path, check the installed exe's real version, verify it opened

This commit is contained in:
CRTkafa 2026-10-23 15:57:31 +07:00
parent a01c78aa20
commit 8f69a27709
6 changed files with 249 additions and 9 deletions

View file

@ -21,7 +21,8 @@ import type { Args } from './lib/args';
import { CONFIG_NAMES } from './lib/config';
import { DECLINED_EXIT } from './lib/ctx';
import { BUNDLE_ID, DOWNLOAD_LABEL, type Download, type DownloadKey, downloadsDir, downloadsFor, findInstalled, type Installed, MANIFEST, type Manifest, manifestProblems, openCommand, openFolderLink, PAGE, PUBLIC_KEY, versionManifest } from './lib/desktop-dist';
import { consent, type Decision, decide, installPlan, isRunning, type Plan, question, runningCheck } from './lib/desktop-install';
import { consent, type Decision, decide, installPlan, type Plan, question } from './lib/desktop-install';
import { appExe, listCommand, logDir, matchByPath, mismatchMessage, notOpenedMessage, parseProcs, peVersion, type Proc, startedHidden, stopCommand, versionMatches } from './lib/desktop-proc';
import { verify } from './lib/minisign';
import { parsePlist } from './lib/plist';
import { addFolder } from './lib/registry';
@ -105,9 +106,11 @@ async function readBody(r: Response, d: Download, stallMs: number, say: (s: stri
const VERSION_RE = /\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\b/;
/** The version of an installed app: Info.plist on macOS, `storebound-desktop --version` elsewhere (15 s at most). */
/** The version of an installed app, read from its own files: Info.plist on macOS, the PE version resource of the exe
* on Windows (never the uninstall registry entry, never by starting the GUI exe), `--version` on Linux (15 s at most). */
export function appVersion(platform: NodeJS.Platform, app: string): string | null {
try {
if (platform === 'win32') return peVersion(readFileSync(app));
if (platform === 'darwin') {
const p = parsePlist(readFileSync(join(app, 'Contents', 'Info.plist'))) as Record<string, unknown>;
return typeof p.CFBundleShortVersionString === 'string' ? p.CFBundleShortVersionString : null;
@ -139,7 +142,8 @@ export function runPlan(plan: Plan, platform: NodeJS.Platform, say: (s: string)
else if ('write' in s) { writeFileSync(s.write.path, s.write.content); if (s.write.mode) chmodSync(s.write.path, s.write.mode); }
else if ('expectVersion' in s) {
const v = appVersion(platform, s.expectVersion.app);
if (v && v !== s.expectVersion.version) throw new Error(`the installed app is ${v}, expected ${s.expectVersion.version}`);
const win = platform === 'win32';
if ((v && !versionMatches(v, s.expectVersion.version, win)) || (!v && win)) throw new Error(mismatchMessage(v, s.expectVersion.version, s.expectVersion.app));
if (!v) say(` (could not read the new app's version; going on)`);
}
if (!always) say(` ${s.what}`);
@ -162,6 +166,37 @@ async function askYes(text: string): Promise<boolean> {
return line !== null && !/^n(o)?$/i.test(line.trim());
}
/** Processes of the installed app, matched by its exact executable path; [] when they cannot be listed. */
function appProcs(platform: NodeJS.Platform, exe: string): Proc[] {
try {
const r = rt.spawnSync(listCommand(platform), { timeout: 15_000 });
return r.success ? matchByPath(platform, parseProcs(platform, r.stdout.toString()), exe) : [];
} catch { return []; }
}
/** Stops the running app (only processes started from `exe`): a graceful close, then by PID after `graceMs`. */
async function stopApp(platform: NodeJS.Platform, exe: string, say: (s: string) => void, graceMs = 10_000): Promise<void> {
let procs = appProcs(platform, exe);
if (!procs.length) return;
say(` stopping the running storebound desktop (PID ${procs.map(p => p.pid).join(', ')})`);
for (const p of procs) try { rt.spawnSync(stopCommand(platform, p.pid, false), { timeout: 10_000 }); } catch { /* forced below */ }
for (const end = Date.now() + graceMs; Date.now() < end && procs.length; ) { await rt.sleep(500); procs = appProcs(platform, exe); }
for (const p of procs) try { rt.spawnSync(stopCommand(platform, p.pid, true), { timeout: 10_000 }); } catch { /* checked below */ }
for (const end = Date.now() + 5_000; Date.now() < end && procs.length; ) { await rt.sleep(500); procs = appProcs(platform, exe); }
if (procs.length) throw new Error(`storebound desktop is still running from ${exe} (PID ${procs.map(p => p.pid).join(', ')}): close it (also in the tray), then run this again`);
}
/** Waits until a visible (not --hidden) process runs from `exe`. */
async function waitOpened(platform: NodeJS.Platform, exe: string, timeoutMs = 15_000): Promise<'ok' | 'none' | 'hidden'> {
let last: 'none' | 'hidden' = 'none';
for (const end = Date.now() + timeoutMs; Date.now() < end; await rt.sleep(500)) {
const procs = appProcs(platform, exe);
if (procs.some(p => !startedHidden(p))) return 'ok';
if (procs.length) last = 'hidden';
}
return last;
}
const tilde = (p: string) => (p.startsWith(homedir()) ? '~' + p.slice(homedir().length) : p);
export async function run(args: Args): Promise<void> {
@ -233,12 +268,6 @@ export async function run(args: Args): Promise<void> {
console.log('nothing changed.');
return;
}
if (installed) {
const chk = runningCheck(platform);
let running = false;
try { const r = rt.spawnSync(chk, { timeout: 10_000 }); running = isRunning(platform, r.exitCode, r.stdout.toString()); } catch { /* no pgrep / tasklist: go on */ }
if (running) throw new Error(`storebound desktop ${decision.from} is running: quit it first, then run this again (or update it from the app: Settings > Updates)`);
}
const how = consent(args.has('yes'), stdinIsTTY());
if (how !== 'yes') {
if (how === 'declined') {
@ -260,6 +289,8 @@ export async function run(args: Args): Promise<void> {
console.log(`downloading ${d.file} (${(d.size / 1e6).toFixed(1)} MB)`);
await download(d, tmp);
console.log(' size, SHA-256 and signature checked');
// a running app keeps its files locked (Windows) or keeps running the old code: stop it, our install path only
await stopApp(platform, appExe(platform, installed?.path ?? plan!.target), s => console.log(s));
runPlan(plan!, platform, s => console.log(s));
} finally { rmSync(tmp, { recursive: true, force: true }); }
installed = findInstalled(platform) ?? { path: plan!.target, how: platform === 'darwin' ? 'bundle' : platform === 'win32' ? 'exe' : 'appimage' };
@ -278,5 +309,11 @@ export async function run(args: Args): Promise<void> {
const code = await Promise.race([p.exited, rt.sleep(30_000).then(() => -1)]);
if (code !== 0) throw new Error(`${fresh ? 'open -a' : `open -b ${BUNDLE_ID}`} failed${code === -1 ? ' (no answer in 30 s)' : `: ${(await new Response(p.stderr).text()).trim()}`}`);
} else p.unref();
const exe = appExe(platform, installed!.path);
const opened = await waitOpened(platform, exe);
if (opened !== 'ok') {
// an already running visible copy counts as opened (single-instance hands it the request)
throw new Error(notOpenedMessage(opened, exe, join(logDir(platform, process.env, homedir()), 'host.log')));
}
console.log(link ? `storebound desktop: opening ${tilde(dir)}` : 'storebound desktop: opened');
}