updater.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // Self-update of the packaged game (readme §2). Looks at the builds published in the git
  2. // repository, downloads the newest one into userData/game/<version>/ and points
  3. // userData/game/current.json at it. boot.ts runs it on the next launch; the Electron runtime
  4. // that came with the installer stays as is.
  5. import { createHash } from 'node:crypto';
  6. import { join } from 'node:path';
  7. import { net } from 'electron';
  8. // original-fs: plain fs, without Electron's asar handling (we write files named app.asar).
  9. import * as fs from 'original-fs';
  10. import type { UpdateStatus } from '../preload/api';
  11. import { CURRENT_FILE, MANIFEST_FILE, newestBuild, parseAdvertisedRefs, parseManifest, rawFileUrl, sameElectronMajor, type ManifestFile } from './updates';
  12. export interface UpdaterOptions {
  13. repoUrl: string;
  14. /** Version of the game running now. */
  15. current: string;
  16. /** userData/game: one folder per downloaded version. */
  17. gamesDir: string;
  18. /** Folder of the running game (app.asar, assets/...): files that did not change are copied from it. */
  19. runningRoot: string;
  20. onStatus(status: UpdateStatus): void;
  21. }
  22. async function fetchOk(url: string): Promise<Response> {
  23. const res = await net.fetch(url, { headers: { 'Cache-Control': 'no-cache' } });
  24. if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
  25. return res;
  26. }
  27. function sha256(data: Uint8Array): string {
  28. return createHash('sha256').update(data).digest('hex');
  29. }
  30. /** The file of the running game when it is byte-identical to the one wanted, else null. */
  31. function reusable(runningRoot: string, file: ManifestFile): Buffer | null {
  32. try {
  33. const path = join(runningRoot, ...file.path.split('/'));
  34. if (fs.statSync(path).size !== file.size) return null;
  35. const data = fs.readFileSync(path);
  36. return sha256(data) === file.sha256 ? data : null;
  37. } catch {
  38. return null;
  39. }
  40. }
  41. /** Checks for a newer build and downloads it. Never throws: failures are reported as a status. */
  42. export async function checkForUpdate(opts: UpdaterOptions): Promise<void> {
  43. try {
  44. fs.mkdirSync(opts.gamesDir, { recursive: true });
  45. const refs = parseAdvertisedRefs(await (await fetchOk(`${opts.repoUrl}.git/info/refs?service=git-upload-pack`)).text());
  46. const build = newestBuild(refs, opts.current);
  47. if (!build) return;
  48. const target = join(opts.gamesDir, build.version);
  49. if (fs.existsSync(join(target, MANIFEST_FILE))) {
  50. // Already downloaded by an earlier launch.
  51. writeCurrent(opts.gamesDir, build.version);
  52. opts.onStatus({ state: 'ready', version: build.version });
  53. return;
  54. }
  55. const manifest = parseManifest(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, MANIFEST_FILE))).json(), build.version);
  56. if (!sameElectronMajor(manifest.electron, process.versions.electron)) {
  57. opts.onStatus({ state: 'manual', version: build.version });
  58. return;
  59. }
  60. const partial = `${target}.part`;
  61. fs.rmSync(partial, { recursive: true, force: true });
  62. const total = manifest.files.reduce((sum, f) => sum + f.size, 0) || 1;
  63. let done = 0;
  64. opts.onStatus({ state: 'downloading', version: build.version, progress: 0 });
  65. for (const file of manifest.files) {
  66. let data = reusable(opts.runningRoot, file);
  67. if (!data) {
  68. data = Buffer.from(await (await fetchOk(rawFileUrl(opts.repoUrl, build.sha, file.path))).arrayBuffer());
  69. if (data.length !== file.size || sha256(data) !== file.sha256) throw new Error(`${file.path} is corrupted`);
  70. }
  71. const path = join(partial, ...file.path.split('/'));
  72. fs.mkdirSync(join(path, '..'), { recursive: true });
  73. fs.writeFileSync(path, data);
  74. done += file.size;
  75. opts.onStatus({ state: 'downloading', version: build.version, progress: done / total });
  76. }
  77. // The manifest goes last: its presence marks a complete download.
  78. fs.writeFileSync(join(partial, MANIFEST_FILE), JSON.stringify(manifest));
  79. fs.rmSync(target, { recursive: true, force: true });
  80. fs.renameSync(partial, target);
  81. writeCurrent(opts.gamesDir, build.version);
  82. removeOldVersions(opts.gamesDir, [build.version, opts.current]);
  83. opts.onStatus({ state: 'ready', version: build.version });
  84. } catch (err) {
  85. console.error('[update]', err);
  86. opts.onStatus({ state: 'error', message: err instanceof Error ? err.message : String(err) });
  87. }
  88. }
  89. function writeCurrent(gamesDir: string, version: string): void {
  90. fs.writeFileSync(join(gamesDir, CURRENT_FILE), JSON.stringify({ version }));
  91. }
  92. /** Deletes downloaded versions other than `keep` (the running one may be in use). */
  93. function removeOldVersions(gamesDir: string, keep: string[]): void {
  94. for (const entry of fs.readdirSync(gamesDir, { withFileTypes: true })) {
  95. if (!entry.isDirectory() || keep.includes(entry.name)) continue;
  96. try {
  97. fs.rmSync(join(gamesDir, entry.name), { recursive: true, force: true });
  98. } catch {
  99. // A folder still locked by another running instance: removed on a later update.
  100. }
  101. }
  102. }