feat(launcher): launch the game through the guarded lab
This commit is contained in:
1 parent
d633280e23
commit
e41b73aaa3
25 files changed
+920
-23
No files matched your search
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
||||
import { app, dialog, shell, type BrowserWindow } from 'electron';
|
||||
import { zipSync } from 'fflate';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { readInstallRecord } from '../install/install-record.ts';
|
||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||
|
||||
@@ -41,8 +42,9 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
||||
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
|
||||
}
|
||||
}
|
||||
const record = await readInstallRecord();
|
||||
if (record) await addServerLogs(files, record.dataPath);
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||
if (dataPath) await addServerLogs(files, dataPath);
|
||||
|
||||
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { join } from 'node:path';
|
||||
import { utilityProcess } from 'electron';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { BuildReply, BuildRequest } from '../../workers/build-protocol.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
export async function buildCopy(
|
||||
request: BuildRequest,
|
||||
signal: AbortSignal,
|
||||
progress: (written: number, total: number, file?: string) => void,
|
||||
): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
const worker = utilityProcess.fork(join(import.meta.dirname, 'build-worker.js'), [], {
|
||||
serviceName: 'WTOffline game build',
|
||||
stdio: 'pipe',
|
||||
});
|
||||
forwardProcessOutput(worker.stdout, 'build', 'info');
|
||||
forwardProcessOutput(worker.stderr, 'build', 'error');
|
||||
let writing = false;
|
||||
const abort = (): void => {
|
||||
// Once writes begin, finish the generation before accepting a retry.
|
||||
if (!writing) worker.kill();
|
||||
};
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
worker.once('exit', (code) => {
|
||||
console.warn('[build] utility process exited:', code);
|
||||
reject(signal.aborted ? signal.reason : new AppError('launch_build_failed'));
|
||||
});
|
||||
worker.on('message', (reply: BuildReply) => {
|
||||
switch (reply.kind) {
|
||||
case 'prepared':
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason);
|
||||
break;
|
||||
}
|
||||
progress(0, reply.total);
|
||||
writing = true;
|
||||
worker.postMessage({ kind: 'write' });
|
||||
break;
|
||||
case 'progress':
|
||||
progress(reply.written, reply.total, reply.file);
|
||||
break;
|
||||
case 'written':
|
||||
resolve();
|
||||
break;
|
||||
case 'failed':
|
||||
reject(new AppError(reply.error));
|
||||
break;
|
||||
}
|
||||
});
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
worker.postMessage(request);
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort);
|
||||
worker.removeAllListeners('exit');
|
||||
worker.kill();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
|
||||
import { isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { z } from 'zod';
|
||||
import { HEALTH_PATH } from '@wto/server';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
const Configuration = z.object({
|
||||
lab: z.string().min(1),
|
||||
copy: z.string().min(1),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
labUser: z.literal('wto-lab'),
|
||||
});
|
||||
const Status = z.object({
|
||||
state: z.string(),
|
||||
message: z.string(),
|
||||
guardExitCode: z.number().nullable().optional(),
|
||||
});
|
||||
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
|
||||
|
||||
export interface Lab {
|
||||
readonly installPath: string;
|
||||
readonly copyPath: string;
|
||||
readonly controlPath: string;
|
||||
readonly port: number;
|
||||
}
|
||||
|
||||
export async function readInstalledLab(): Promise<Lab> {
|
||||
if (app.isPackaged || process.platform !== 'win32') throw new AppError('launch_lab_required');
|
||||
const programData = process.env['ProgramData'];
|
||||
if (!programData) throw new AppError('launch_lab_missing');
|
||||
const installPath = join(programData, 'WTOffline-lab');
|
||||
try {
|
||||
const config = Configuration.parse(JSON.parse(await readFile(join(installPath, 'lab.json'), 'utf8')));
|
||||
const root = await realpath(config.lab);
|
||||
const copyPath = await realpath(resolve(root, config.copy));
|
||||
const relation = relative(root, copyPath);
|
||||
if (!isAbsolute(config.lab) || !relation || relation.startsWith('..') || isAbsolute(relation)) {
|
||||
throw new Error('The game copy is outside the lab.');
|
||||
}
|
||||
const executableFolder = await realpath(join(copyPath, 'win64'));
|
||||
if (relative(copyPath, executableFolder).toLowerCase() !== 'win64') {
|
||||
throw new Error('The lab executable folder points outside the copy.');
|
||||
}
|
||||
const controlPath = await realpath(join(root, 'automation'));
|
||||
if (relative(root, controlPath).toLowerCase() !== 'automation') {
|
||||
throw new Error('The lab control folder points outside the lab.');
|
||||
}
|
||||
for (const name of ['Run-GuardedGame.ps1', 'WtoNetworkGuard.exe']) {
|
||||
if (!(await lstat(join(installPath, name))).isFile()) throw new Error(`Missing lab file: ${name}`);
|
||||
}
|
||||
return { installPath, copyPath, controlPath, port: config.port };
|
||||
} catch (error) {
|
||||
console.warn('[lab] the installed automation is unavailable:', error);
|
||||
throw new AppError('launch_lab_missing');
|
||||
}
|
||||
}
|
||||
|
||||
export function labStatusUrl(port: number): string {
|
||||
return `http://127.0.0.1:${port}${HEALTH_PATH}`;
|
||||
}
|
||||
|
||||
async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
|
||||
try {
|
||||
return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8')));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function isReady(port: number, pid: number): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) });
|
||||
return response.ok && Health.parse(await response.json()).pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopGame(lab: Lab): Promise<void> {
|
||||
await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
});
|
||||
}
|
||||
|
||||
type LabPhase = 'starting-server' | 'starting-game' | 'running' | 'server-exited';
|
||||
|
||||
/** The installed guard owns the game process and observes the stop request. */
|
||||
export async function runLab(
|
||||
lab: Lab,
|
||||
stockPath: string,
|
||||
dataPath: string,
|
||||
signal: AbortSignal,
|
||||
publish: (phase: LabPhase) => void,
|
||||
): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
const repository = resolve(app.getAppPath(), '..', '..');
|
||||
const child = spawn('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', join(repository, 'tools', 'lab', 'Start-LabTest.ps1'),
|
||||
'-SkipBuild', '-Stock', stockPath, '-Data', dataPath, '-Install', lab.installPath,
|
||||
], { cwd: repository, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
|
||||
let serverPid: number | null = null;
|
||||
let running = false;
|
||||
let processClosed = false;
|
||||
let serverExited = false;
|
||||
let occupied = false;
|
||||
let failures = 0;
|
||||
let checking = false;
|
||||
let stopSent = false;
|
||||
|
||||
const requestStop = (): void => {
|
||||
if (!running || stopSent || processClosed) return;
|
||||
stopSent = true;
|
||||
void stopGame(lab).catch((error: unknown) => {
|
||||
stopSent = false;
|
||||
console.error('[lab] could not request a guarded stop:', error);
|
||||
});
|
||||
};
|
||||
const observe = (line: string): void => {
|
||||
if (/Port \d+ is already in use\./.test(line)) occupied = true;
|
||||
const ready = /^\[WTO lab test\] Local server pid (\d+) listening/.exec(line);
|
||||
if (ready) {
|
||||
serverPid = Number(ready[1]);
|
||||
publish('starting-game');
|
||||
}
|
||||
if (line.startsWith('[WTO lab test] Game running (pid ')) {
|
||||
running = true;
|
||||
publish('running');
|
||||
if (signal.aborted) requestStop();
|
||||
}
|
||||
if (line.startsWith('[WTO lab test] Run ')) running = false;
|
||||
};
|
||||
forwardProcessOutput(child.stdout, 'lab', 'info', observe);
|
||||
forwardProcessOutput(child.stderr, 'lab', 'error', observe);
|
||||
publish('starting-server');
|
||||
signal.addEventListener('abort', requestStop, { once: true });
|
||||
const interval = setInterval(() => {
|
||||
if (!running || !serverPid || processClosed || checking) return;
|
||||
if (signal.aborted || serverExited) {
|
||||
requestStop();
|
||||
return;
|
||||
}
|
||||
checking = true;
|
||||
void isReady(lab.port, serverPid).then((ready) => {
|
||||
if (!running || processClosed) return;
|
||||
failures = ready ? 0 : failures + 1;
|
||||
if (failures < 3) return;
|
||||
serverExited = true;
|
||||
publish('server-exited');
|
||||
requestStop();
|
||||
}).finally(() => { checking = false; });
|
||||
}, 1000);
|
||||
|
||||
try {
|
||||
const code = await new Promise<number | null>((done, fail) => {
|
||||
child.once('error', fail);
|
||||
child.once('close', done);
|
||||
});
|
||||
processClosed = true;
|
||||
if (signal.aborted) return;
|
||||
if (occupied) throw new AppError('launch_port_busy');
|
||||
if (serverExited) throw new AppError('launch_server_exited');
|
||||
const status = serverPid === null ? null : await readStatus(lab);
|
||||
if (code !== 0 || status?.state !== 'finished' || (status.guardExitCode ?? 0) !== 0 ||
|
||||
status.message.startsWith('EXTERNAL TCP CONNECTION')) {
|
||||
throw new AppError('launch_lab_failed');
|
||||
}
|
||||
} finally {
|
||||
processClosed = true;
|
||||
clearInterval(interval);
|
||||
signal.removeEventListener('abort', requestStop);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { BrowserWindow, shell } from 'electron';
|
||||
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { readInstallRecord } from '../install/install-record.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
import { buildCopy } from './build-copy.ts';
|
||||
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
interface LaunchJob {
|
||||
readonly stop: AbortController;
|
||||
readonly report: (state: LaunchState) => void;
|
||||
done: Promise<void>;
|
||||
}
|
||||
|
||||
let active: LaunchJob | null = null;
|
||||
let state: LaunchState = { phase: 'ready' };
|
||||
|
||||
export function getLaunchState(): LaunchState {
|
||||
return state;
|
||||
}
|
||||
|
||||
export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
if (active) throw new AppError('launch_busy');
|
||||
const job = { stop: new AbortController(), report, done: Promise.resolve() };
|
||||
active = job;
|
||||
update(job, { phase: 'checking' });
|
||||
job.done = launch(job).catch((error: unknown) => {
|
||||
const port = state.port;
|
||||
const context = port === undefined ? {} : { port };
|
||||
if (job.stop.signal.aborted) {
|
||||
update(job, { phase: 'ready' });
|
||||
return;
|
||||
}
|
||||
console.error('[launch] launch failed:', error);
|
||||
const code = error instanceof AppError ? error.code : 'launch_lab_failed';
|
||||
switch (code) {
|
||||
case 'launch_port_busy':
|
||||
update(job, { phase: 'port-busy', ...context });
|
||||
break;
|
||||
case 'launch_server_exited':
|
||||
update(job, { phase: 'server-exited', ...context });
|
||||
break;
|
||||
default:
|
||||
update(job, { phase: 'failed', error: code, ...context });
|
||||
break;
|
||||
}
|
||||
}).finally(() => {
|
||||
active = null;
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
export function stopLaunch(): Promise<void> | null {
|
||||
const job = active;
|
||||
if (!job) return null;
|
||||
if (!job.stop.signal.aborted) {
|
||||
update(job, { ...state, phase: 'stopping' });
|
||||
job.stop.abort();
|
||||
}
|
||||
return job.done;
|
||||
}
|
||||
|
||||
export async function openServerStatus(): Promise<void> {
|
||||
if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited');
|
||||
await shell.openExternal(labStatusUrl(state.port));
|
||||
}
|
||||
|
||||
function update(job: LaunchJob, next: LaunchState): void {
|
||||
state = next;
|
||||
job.report(next);
|
||||
}
|
||||
|
||||
async function launch(job: LaunchJob): Promise<void> {
|
||||
const signal = job.stop.signal;
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
if (!record) throw new AppError('launch_no_copy');
|
||||
if (!settings.developerMode) throw new AppError('launch_lab_required');
|
||||
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
|
||||
const currentVersion = await readVersion(record.copyPath, signal);
|
||||
if (!currentVersion || currentVersion !== record.gameVersion) {
|
||||
update(job, { phase: 'version-changed', actualVersion: currentVersion });
|
||||
return;
|
||||
}
|
||||
|
||||
const lab = await readInstalledLab();
|
||||
const stockPath = settings.labStockPath ?? record.stockBackupPath;
|
||||
const dataPath = settings.labDataPath ?? record.dataPath;
|
||||
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
|
||||
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
|
||||
}
|
||||
const relativeData = relative(stockPath, dataPath);
|
||||
if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) {
|
||||
throw new AppError('launch_copy_in_steam');
|
||||
}
|
||||
update(job, { phase: 'checking', port: lab.port });
|
||||
const [labVersion, stockVersion, games] = await Promise.all([
|
||||
readVersion(lab.copyPath, signal),
|
||||
readVersion(stockPath, signal),
|
||||
execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }),
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
|
||||
if (/^"aces\.exe",/im.test(games.stdout)) throw new AppError('launch_game_running');
|
||||
await checkPort(lab.port);
|
||||
signal.throwIfAborted();
|
||||
update(job, { phase: 'building', port: lab.port });
|
||||
await buildCopy({
|
||||
kind: 'build',
|
||||
stockPath,
|
||||
copyPath: lab.copyPath,
|
||||
dataPath,
|
||||
port: lab.port,
|
||||
...resourcePaths(),
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
if (!signal.aborted) update(job, {
|
||||
phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
});
|
||||
});
|
||||
|
||||
await runLab(lab, stockPath, dataPath, signal, (phase) => {
|
||||
if (!signal.aborted) update(job, { phase, port: lab.port });
|
||||
if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') {
|
||||
for (const window of BrowserWindow.getAllWindows()) window.minimize();
|
||||
}
|
||||
});
|
||||
update(job, { phase: 'ready' });
|
||||
}
|
||||
|
||||
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
|
||||
try {
|
||||
return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal }));
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
console.warn('[launch] reading the game version failed:', folder, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPort(port: number): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const listener = createServer();
|
||||
listener.once('error', (error: NodeJS.ErrnoException) => reject(
|
||||
error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error,
|
||||
));
|
||||
listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve()));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createInterface } from 'node:readline';
|
||||
|
||||
/** Preserve complete lines when a process splits or combines them across writes. */
|
||||
export function forwardProcessOutput(
|
||||
stream: NodeJS.ReadableStream | null,
|
||||
prefix: string,
|
||||
level: 'info' | 'error',
|
||||
onLine?: (line: string) => void,
|
||||
): void {
|
||||
if (!stream) return;
|
||||
const reader = createInterface({ input: stream, crlfDelay: Infinity, terminal: false });
|
||||
reader.on('line', (line) => {
|
||||
console[level](`[${prefix}] ${line}`);
|
||||
onLine?.(line);
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { join } from 'node:path';
|
||||
import { BrowserWindow, shell } from 'electron';
|
||||
import { app, BrowserWindow, Menu, shell, Tray } from 'electron';
|
||||
import { getSettings } from './config/settings-store.ts';
|
||||
|
||||
/**
|
||||
* The launcher's single window: a fixed size without the system frame, like the game's own
|
||||
@@ -13,6 +14,24 @@ const CONTENT_HEIGHT = 720;
|
||||
const BACKGROUND = '#13191b';
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let tray: Tray | null = null;
|
||||
let quitting = false;
|
||||
|
||||
export function beginWindowQuit(): void {
|
||||
quitting = true;
|
||||
tray?.destroy();
|
||||
tray = null;
|
||||
}
|
||||
|
||||
async function hideToTray(window: BrowserWindow): Promise<void> {
|
||||
if (!tray) {
|
||||
tray = new Tray(await app.getFileIcon(process.execPath, { size: 'small' }));
|
||||
tray.setToolTip(app.getName());
|
||||
tray.setContextMenu(Menu.buildFromTemplate([{ role: 'quit' }]));
|
||||
tray.on('click', () => showMainWindow());
|
||||
}
|
||||
if (!window.isDestroyed()) window.hide();
|
||||
}
|
||||
|
||||
export function createMainWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
@@ -39,6 +58,20 @@ export function createMainWindow(): BrowserWindow {
|
||||
return { action: 'deny' };
|
||||
});
|
||||
window.webContents.on('will-navigate', (event) => event.preventDefault());
|
||||
let handlingClose = false;
|
||||
window.on('close', (event) => {
|
||||
if (quitting) return;
|
||||
event.preventDefault();
|
||||
if (handlingClose) return;
|
||||
handlingClose = true;
|
||||
void getSettings().then(async (settings) => {
|
||||
if (settings.windowClose === 'tray') await hideToTray(window);
|
||||
else app.quit();
|
||||
}).catch((error: unknown) => {
|
||||
console.warn('[window] the close action failed:', error);
|
||||
app.quit();
|
||||
}).finally(() => { handlingClose = false; });
|
||||
});
|
||||
window.on('closed', () => {
|
||||
if (mainWindow === window) mainWindow = null;
|
||||
});
|
||||
@@ -54,5 +87,6 @@ export function createMainWindow(): BrowserWindow {
|
||||
export function showMainWindow(): void {
|
||||
const window = mainWindow ?? createMainWindow();
|
||||
if (window.isMinimized()) window.restore();
|
||||
if (!window.isVisible()) window.show();
|
||||
window.focus();
|
||||
}
|
||||
Reference in new issue
Block a user