feat(saves): add save archives and copy transfers

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:55:23 +08:00
1 parent 073a907617
commit d0a767e692
19 files changed
+660 -25

No files matched your search

@@ -4,12 +4,14 @@ import { createServer } from 'node:net';
import { isAbsolute, join, relative } from 'node:path';
import { promisify } from 'node:util';
import { BrowserWindow, shell } from 'electron';
import { AccountStore } from '@wto/server';
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 { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
@@ -123,6 +125,12 @@ async function launch(job: LaunchJob): Promise<void> {
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
if (games) throw new AppError('launch_game_running');
await checkPort(lab.port);
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port: lab.port });
await buildCopy({
@@ -1,14 +1,16 @@
import { join } from 'node:path';
import { utilityProcess } from 'electron';
import { dialog, utilityProcess, type BrowserWindow } from 'electron';
import { compareVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { CurrencyEdits, SaveDetails, SaveList, SaveRegistration } from '@shared/schemas/saves.ts';
import type { CurrencyEdits, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { forwardProcessOutput } from '../launch/process-output.ts';
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
let writing = false;
@@ -61,6 +63,103 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
});
}
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : result.filePaths[0] ?? null };
}
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
try {
await writeArchive(result.filePath, await captureSave(copy, userId));
} catch (error) {
if (error instanceof AppError) throw error;
console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed');
}
return { path: result.filePath };
}
export async function transferSave({ source, copyId, login, password, nick }: SaveTransfer): Promise<SaveList> {
return write(async () => {
const target = await requireCopy(copyId);
let archive: SaveArchive;
if (source.kind === 'file') {
archive = await readArchive(source.path);
} else {
const parent = await requireCopy(source.copyId);
await getSaveDetails(parent.id, source.userId);
archive = await captureSave(parent, source.userId);
}
await validateProfile(archive, target);
const { userId } = await run({ operation: 'create', ...location(target), login, password, nick }) as { userId: string };
try {
await restoreDirectory(target, userId, archive);
} catch (error) {
await run({ operation: 'remove', ...location(target), userId }).catch((failure) =>
console.error('[saves] could not remove the unfinished registration:', failure));
throw error;
}
await updateCopyRecord(copyId, (record) => ({ ...record, currentSaveId: userId }));
return getSaveList(copyId);
});
}
export async function removeSave(copyId: string, userId: string): Promise<SaveList> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
await changeSaveFolder(copy, userId, () => run({ operation: 'remove', ...location(copy), userId }));
if (copy.currentSaveId === userId) {
await updateCopyRecord(copyId, (record) => {
if (record.currentSaveId !== userId) return record;
const { currentSaveId: _removed, ...rest } = record;
return rest;
});
}
return getSaveList(copyId);
});
}
export async function listSaveBackups(copyId: string, userId: string): Promise<SaveBackup[]> {
const copy = await requireCopy(copyId);
return backupList(copy, userId);
}
export async function takeSaveBackup(copyId: string, userId: string): Promise<SaveBackup[]> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
await saveBackup(copy, userId, 'manual');
return backupList(copy, userId);
});
}
export async function restoreSaveBackup(copyId: string, userId: string, name: string): Promise<SaveDetails> {
return write(async () => {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const archive = await archivedBackup(copy, userId, name);
await validateProfile(archive, copy);
await saveBackup(copy, userId, 'restore');
await restoreDirectory(copy, userId, archive);
return getSaveDetails(copyId, userId);
});
}
async function validateProfile(archive: SaveArchive, copy: InstallRecord): Promise<void> {
const profile = archive.files['profile.blk'];
if (!profile) return;
const filter = archive.gameVersion === null || copy.gameVersion === null ||
compareVersions(archive.gameVersion, copy.gameVersion) > 0;
archive.files['profile.blk'] = await run({ operation: 'filter', ...location(copy), profile, filter }) as Uint8Array;
}
async function write<T>(operation: () => Promise<T>): Promise<T> {
if (writing || launchInProgress() || maintenanceInProgress()) throw new AppError('save_read_only');
writing = true;
@@ -69,6 +168,10 @@ async function write<T>(operation: () => Promise<T>): Promise<T> {
throw new AppError('save_read_only');
}
return await operation();
} catch (error) {
if (error instanceof AppError) throw error;
console.error('[saves] could not write the save:', error);
throw new AppError('save_operation_failed');
} finally {
writing = false;
}
@@ -0,0 +1,194 @@
import { randomUUID } from 'node:crypto';
import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { unzipSync, zipSync } from 'fflate';
import { z } from 'zod';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { SaveBackupNameSchema, type SaveBackup } from '@shared/schemas/saves.ts';
import { fileInfo } from '../copies/change-copy-files.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
const MANIFEST = 'wto-save.json';
const FILES = [
'save.json', 'profile.blk',
'cloud-settings/meta.json',
'cloud-settings/GBT_GENERAL_SETTINGS.blk',
'cloud-settings/GBT_GENERAL_MACHINE_SETTINGS.blk',
'cloud-settings/GBT_GENERAL_STORAGE.blk',
] as const;
const LIMIT = 256 * 1024 * 1024;
const Manifest = z.object({ version: z.literal(1), gameVersion: z.string().nullable() });
const SavedInfo = z.object({ formatVersion: z.number().int().positive(), created: z.string(), updated: z.string() });
export interface SaveArchive {
readonly gameVersion: string | null;
readonly files: Record<string, Uint8Array>;
}
function saveFolder(copy: InstallRecord, userId: string): string {
if (!/^\d+$/.test(userId)) throw new AppError('save_not_found');
return join(copy.dataPath, 'saves', userId);
}
async function checkedSaveFolder(copy: InstallRecord, userId: string): Promise<string> {
const root = await canonicalCopyPath(copy.dataPath);
const folder = await canonicalCopyPath(saveFolder(copy, userId));
if (relative(join(root, 'saves', userId), folder) !== '') throw new AppError('save_archive_invalid');
return folder;
}
async function readFileIfRegular(file: string, root: string): Promise<Buffer | undefined> {
const stats = await fileInfo(file);
if (!stats) return undefined;
if (!stats.isFile() || !copyPathContains(root, await canonicalCopyPath(dirname(file)))) {
throw new AppError('save_archive_invalid');
}
if (stats.size > LIMIT) throw new AppError('save_archive_invalid');
return readFile(file);
}
export async function captureSave(copy: InstallRecord, userId: string): Promise<SaveArchive> {
const source = await checkedSaveFolder(copy, userId);
const files: SaveArchive['files'] = {};
for (const name of FILES) {
const data = await readFileIfRegular(join(source, name), source);
if (data) files[name] = data;
}
const archive = { gameVersion: copy.gameVersion, files };
validateSave(archive);
return archive;
}
export function encodeSave(archive: SaveArchive): Uint8Array {
const manifest = JSON.stringify({ version: 1, gameVersion: archive.gameVersion });
return zipSync({ ...archive.files, [MANIFEST]: Buffer.from(manifest, 'utf8') });
}
export async function readArchive(path: string): Promise<SaveArchive> {
try {
const raw = await readFileIfRegular(path, await canonicalCopyPath(dirname(path)));
if (!raw) throw new Error('Save archive missing.');
let expandedSize = 0;
const files = unzipSync(raw, { filter(file) {
expandedSize += file.originalSize;
if (expandedSize > LIMIT || (file.name !== MANIFEST && !(FILES as readonly string[]).includes(file.name))) {
throw new Error('Unexpected contents in a save archive.');
}
return true;
} });
const manifest = files[MANIFEST];
if (!manifest) throw new Error('Save manifest missing.');
const { gameVersion } = Manifest.parse(JSON.parse(Buffer.from(manifest).toString('utf8')));
delete files[MANIFEST];
const archive = { gameVersion, files };
validateSave(archive);
return archive;
} catch (error) {
console.warn('[saves] could not open a save archive:', error);
throw new AppError('save_archive_invalid');
}
}
function validateSave(archive: SaveArchive): void {
const { files } = archive;
if (!!files['save.json'] !== !!files['profile.blk']) throw new AppError('save_archive_invalid');
if (files['save.json']) SavedInfo.parse(JSON.parse(Buffer.from(files['save.json']).toString('utf8')));
}
/** A save file is either replaced completely or the previous file remains available. */
export async function writeArchive(path: string, archive: SaveArchive): Promise<void> {
const temporary = path + '.' + randomUUID() + '.tmp';
try {
await writeFile(temporary, encodeSave(archive), { flag: 'wx' });
await rename(temporary, path);
} catch (error) {
await rm(temporary, { force: true }).catch(() => {});
throw error;
}
}
/** Keep the original directory beside the save until its replacement or account edit succeeds. */
export async function changeSaveFolder<T>(copy: InstallRecord, userId: string, operation: (folder: string, work: string) => Promise<T>): Promise<T> {
const folder = await checkedSaveFolder(copy, userId);
const parent = dirname(folder);
await mkdir(parent, { recursive: true });
const work = await mkdtemp(join(parent, '.wto-save-'));
const original = join(work, 'original');
let moved = false;
let keepOriginal = false;
try {
if (await fileInfo(folder)) {
await rename(folder, original);
moved = true;
}
return await operation(folder, work);
} catch (error) {
if (moved) {
try {
await rename(original, folder);
} catch (failure) {
keepOriginal = true;
console.error('[saves] could not restore the save directory. The original is at', original, failure);
}
}
throw error;
} finally {
if (!keepOriginal && relative(parent, dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[saves] clearing temporary files failed:', work, error));
}
}
}
export async function restoreDirectory(copy: InstallRecord, userId: string, archive: SaveArchive): Promise<void> {
await changeSaveFolder(copy, userId, async (folder, work) => {
const staging = join(work, 'incoming');
await mkdir(staging);
for (const name of FILES) {
const bytes = archive.files[name];
if (!bytes) continue;
const path = join(staging, name);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, bytes, { flag: 'wx' });
}
await rename(staging, folder);
});
}
async function backupFolder(copy: InstallRecord, userId: string): Promise<string> {
if (!/^\d+$/.test(userId)) throw new AppError('save_not_found');
const root = await canonicalCopyPath(copy.dataPath);
const directory = join(root, 'save-backups', userId);
if (relative(directory, await canonicalCopyPath(directory)) !== '') throw new AppError('save_archive_invalid');
return directory;
}
export async function backupList(copy: InstallRecord, userId: string): Promise<SaveBackup[]> {
const path = await backupFolder(copy, userId);
if (!(await fileInfo(path))?.isDirectory()) return [];
const backups: SaveBackup[] = [];
for (const entry of (await readdir(path, { withFileTypes: true })).sort((a, b) => b.name.localeCompare(a.name))) {
if (!entry.isFile() || !SaveBackupNameSchema.safeParse(entry.name).success) continue;
const stats = await fileInfo(join(path, entry.name));
if (stats) backups.push({
name: entry.name, createdAt: stats.mtime.toISOString(),
type: entry.name.split('.')[1] as SaveBackup['type'], size: stats.size,
});
}
return backups;
}
export async function saveBackup(copy: InstallRecord, userId: string, type: SaveBackup['type']): Promise<void> {
const root = await backupFolder(copy, userId);
await mkdir(root, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
await writeArchive(join(root, `${stamp}.${type}.${randomUUID()}.zip`), await captureSave(copy, userId));
if (type === 'launch') {
const older = (await backupList(copy, userId)).filter((backup) => backup.type === 'launch').slice(10);
for (const backup of older) await rm(join(root, backup.name), { force: true });
}
}
export async function archivedBackup(copy: InstallRecord, userId: string, name: string): Promise<SaveArchive> {
return readArchive(join(await backupFolder(copy, userId), SaveBackupNameSchema.parse(name)));
}