Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a23629fe69 | ||
|
|
1535bd032b | ||
|
|
de9ba52b85 | ||
|
|
82ec1c47ff | ||
|
|
e284ea7ed6 | ||
|
|
ae1e5ec65b | ||
|
|
c55ec4ed57 | ||
|
|
f3d04d137f | ||
|
|
96077153c6 | ||
|
|
90bd5a315d | ||
|
|
1c6f5c9fc4 | ||
|
|
cab73f92f9 | ||
|
|
1c24adbd83 | ||
|
|
ec020d2848 | ||
|
|
6d232f14e6 | ||
|
|
d75c80c05a | ||
|
|
2661b4e783 | ||
|
|
152be6af0e | ||
|
|
ca9843c304 |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
## 简体中文
|
||||
|
||||
`v0.1.0` 是 WTOffline 启动器的首个公开版本。
|
||||
|
||||
### 主要功能
|
||||
|
||||
- **本地人机对局。** 在支持的陆战、空战和海战模式中与 AI 队友和对手交战。对局结束后可以查看结算和回放。
|
||||
- **离线机库与成长。** 组建编队、研发载具和改装件、训练乘员,并使用本地商店与交易所。
|
||||
- **客户端、存档和数值。** 管理多个离线客户端,备份、恢复和迁移存档,调整对局、收益和研发数值。
|
||||
- **内置更新检查。** 在「关于」检查启动器和适配包更新。启动器会验证下载的适配包签名,通过后启用。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
已在 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55` 上实机验证。补丁会根据客户端文件内容查找匹配位置,因此也可能适配之后的其他小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
`v0.1.0` is the first public release of the WTOffline Launcher.
|
||||
|
||||
### Highlights
|
||||
|
||||
- **Local battles with AI.** Play supported ground, air, and naval modes with AI teammates and opponents. View your results and replays after a battle.
|
||||
- **Offline hangar and progression.** Build lineups, research vehicles and modifications, train crews, and use the local store and marketplace.
|
||||
- **Clients, saves, and tuning.** Manage multiple offline clients, back up, restore, and transfer saves, and adjust battle, reward, and research settings.
|
||||
- **Built-in update checks.** Check for launcher and adaptation pack updates under **About**. The launcher verifies each downloaded pack's signature before enabling it.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Tested in-game with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55`. The patches match patterns in the client files, so they may also work with other later minor updates.
|
||||
@@ -0,0 +1,35 @@
|
||||
## 简体中文
|
||||
|
||||
> **重要升级提示:** 所有使用 **Gaijin 官方独立版客户端**,或者 **Steam 版但曾经通过官方启动器(更新器)启动过游戏** 的用户,**必须更新到 `v0.1.1` 启动器**(更新后请对已有离线副本重新执行一次「构建客户端」)。旧版启动器在存在官方清单 `content/warthunder.blk` 时会触发游戏拉起官方启动器并还原离线补丁,导致启动闪退、弹出官服更新或报原版备份不一致。
|
||||
|
||||
`v0.1.1` 是 WTOffline 启动器的重要维护更新,重点修复官方客户端/官方启动器用户无法正常启动的问题、修复对局中非本机载具受损提示串台,并增强启动稳定性与故障诊断能力。
|
||||
|
||||
### 修复与改进
|
||||
|
||||
- **解决官方独立版 / 官方启动器拉起官服更新的问题。** 启动参数新增 `-skip_pkg_validation`,跳过 `aces.exe` 启动时对官方 `content/warthunder.blk` 的文件体积校验;同时新增可执行文件隔离补丁,阻止游戏在异常情况下拉起官方 `launcher.exe -fullcheck` 联网覆盖离线文件,修复“启动数秒后以退出码 `1` 退出 → 弹出官服更新 → 离线文件被还原/报备份不一致”的死循环。
|
||||
- **局内受损提示与敌方部件归属。** 修复空战与现代陆战中 AI 载具航电、传感器、雷达、红外干扰和瞄准吊舱受损时错误向玩家弹出白字提示(及误退光电视角)的问题;过滤陆战与海战右侧敌方部件损毁列表及特殊命中反馈中的非本机攻击记录,保留本机在途弹药与观战视角显示。
|
||||
- **启动与写盘稳定性。** 游戏补丁文件写入改为临时文件原子替换并带短暂占用重试,降低安全软件实时扫描导致写入失败的风险;优化 `wto_ws.dll` 加载时的钩子批量启用流程,减少初始化期的线程冻结次数并记录详细错误码。
|
||||
- **原版备份检测与报错。** 修复旧版 `wtoffline\stock` 备份在客户端更新后遮蔽实际版本、无法自动刷新的问题;启动时区分「原版文件备份缺失/损坏」与「版本不一致」,并在日志中记录双方实际版本号。
|
||||
- **启动前检查与诊断导出。** 启动游戏前核对核心文件是否可读(提前提示可能被安全软件隔离);异常退出时在启动器日志记录现场文件状态与带十六进制的系统退出码;导出的诊断 ZIP 自动附带 `wto_ws.log`、最新一份游戏 `.clog` 日志和环境摘要(不含玩家存档)。
|
||||
|
||||
### 客户端兼容性
|
||||
|
||||
支持已核对版本 `2.61.0.37`、`2.61.0.43` 和 `2.61.0.55`(自带补丁集 `2026.12.02`),并支持按特征码自动尝试适配后续小版本更新。
|
||||
|
||||
## English
|
||||
|
||||
> **Important upgrade notice:** All users on the **standalone Gaijin client**, as well as **Steam users who have ever launched the game through the official Gaijin launcher/updater**, **must upgrade to `v0.1.1`** (and rebuild existing offline copies after updating). On earlier launcher versions, the presence of `content/warthunder.blk` causes `aces.exe` to spawn the official launcher and overwrite patched offline files, resulting in startup exit code `1`, official updater popups, or stock-backup version mismatches.
|
||||
|
||||
`v0.1.1` is an important maintenance release of the WTOffline Launcher that fixes startup failures on standalone/official-launcher clients, fixes cross-unit battle damage notices, improves launch reliability, and strengthens crash diagnostics.
|
||||
|
||||
### Fixes and improvements
|
||||
|
||||
- **Skip startup package validation and block official launcher spawns.** Added `-skip_pkg_validation` to offline launch arguments so `aces.exe` skips the startup `content/warthunder.blk` file-size integrity check, and added an executable isolation patch that blocks `aces.exe` from spawning the official `launcher.exe -fullcheck` updater. This eliminates the loop where the game exits with code `1`, opens the official launcher, and overwrites offline files back to the online build.
|
||||
- **In-battle damage notices and enemy parts feedback.** Fixed AI avionics, sensor, radar, RWR/countermeasures, and targeting-pod failures in air and modern ground battles incorrectly showing white damage notices (or forcing the player out of optic view). Filtered non-local AI-on-AI hits out of the ground/naval enemy damaged-parts list and special hit-camera events while preserving in-flight player munitions and spectator views.
|
||||
- **Launch and file-write reliability.** Rebuilt game files are now written via temporary files with atomic rename and brief retry on transient antivirus locks. Batched MinHook activation in `wto_ws.dll` into two passes to cut startup thread-freeze cycles and log detailed `MH_STATUS` diagnostics on failure.
|
||||
- **Stock backup detection and errors.** Fixed stale `wtoffline\stock` backups masking an externally updated client and blocking backup refresh. Launch checks now distinguish missing/unreadable backups from version mismatches and log the exact copy and backup versions.
|
||||
- **Pre-launch checks and richer diagnostics.** Verify core launch files before starting `aces.exe` (flagging possible antivirus quarantine early), log post-exit file snapshots and hex-annotated Windows exit codes, and include `wto_ws.log`, the latest `.clog`, and a metadata summary (without player saves) in exported diagnostic ZIPs.
|
||||
|
||||
### Client compatibility
|
||||
|
||||
Verified with client versions `2.61.0.37`, `2.61.0.43`, and `2.61.0.55` (bundled patch set `2026.12.02`), with pattern-based matching for later minor updates.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
|
||||
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
|
||||
# signed files (installer, manifest, signature); a release missing any of them breaks the check
|
||||
# for already-installed launchers. The workflow also packages and signs the portable zip with its
|
||||
# own manifest and signature so portable installations can update in place.
|
||||
#
|
||||
# Start it either way:
|
||||
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
||||
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
|
||||
# branch's latest commit.
|
||||
# The release note comes from .github/release-notes/v<version>.md. The signing key comes from the
|
||||
# repository secret PATCH_SIGNING_KEY (the same Ed25519 key used for adaptation packs).
|
||||
name: Launcher release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Launcher version, e.g. 0.1.0 (must match apps/launcher/package.json)'
|
||||
required: true
|
||||
type: string
|
||||
draft:
|
||||
description: 'Keep the release as a draft for editing before publication'
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Download the Electron runtime
|
||||
run: node node_modules/electron/install.js
|
||||
|
||||
- name: Resolve and verify the version
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ]; then
|
||||
VERSION="${{ inputs.version }}"
|
||||
else
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
fi
|
||||
PKG_VERSION=$(node -p "require('./apps/launcher/package.json').version")
|
||||
if [ "$VERSION" != "$PKG_VERSION" ]; then
|
||||
echo "Version $VERSION does not match apps/launcher/package.json ($PKG_VERSION)" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=$VERSION" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Typecheck
|
||||
run: |
|
||||
npm run typecheck
|
||||
npm run typecheck --workspace "@wto/launcher"
|
||||
|
||||
- name: Build and package the Windows installer and portable archive
|
||||
run: npm --workspace "@wto/launcher" run package:win
|
||||
|
||||
- name: Sign the release
|
||||
env:
|
||||
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
|
||||
run: node scripts/sign-launcher-release.ts
|
||||
|
||||
- name: Create the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
flags=(--draft)
|
||||
if [ "${{ github.event_name }}" = 'workflow_dispatch' ] && [ "${{ inputs.draft }}" = 'false' ]; then
|
||||
flags=()
|
||||
fi
|
||||
gh release create "v$VERSION" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.exe" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
|
||||
"${flags[@]}" \
|
||||
--title "WTOffline Launcher $VERSION" \
|
||||
--notes-file ".github/release-notes/v$VERSION.md" \
|
||||
--target "$GITHUB_SHA"
|
||||
@@ -73,7 +73,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
|
||||
- **服务地址**:`config/network.blk`(`char.vromfs.bin`)和 `config/settings.blk`(`aces.vromfs.bin`)中所有 Gaijin 地址改写为 `127.0.0.1:<端口>`。端口在构建时写入,因此服务器必须使用相同的端口。
|
||||
- **配置表**:开启离线需要的功能开关,放出隐藏载具,写入贴花索引,为本地商店的礼包登记 GUID。
|
||||
- **exe 补丁**:`patches/exe/` 下共 12 项,见下表。
|
||||
- **exe 补丁**:`patches/exe/` 下共 13 项,见下表。
|
||||
- **界面脚本补丁**:`patches/gui/` 下共 40 项,用于本地账号注册、本地对局的开局与结算、本地商店的购买回执,以及库存签名公钥等。
|
||||
- **网络钩子库**:exe 的导入表把 `WS2_32.dll` 改为同长度的 `wto_ws.dll`。该库转发系统 `ws2_32.dll` 的全部导出,并用 MinHook 挂钩域名解析(`getaddrinfo` 等)、连接(`connect`、`ConnectEx` 等)和 UDP 发送,把所有外部连接重定向到本地服务器端口。端口从 exe 旁的 `wto_ws.cfg` 读取。
|
||||
|
||||
@@ -84,6 +84,7 @@ AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不
|
||||
| `isolation/registry-key` | 注册表位置改为 `Software\WTOffline` |
|
||||
| `isolation/never-load-battleye` | 不加载 BattlEye |
|
||||
| `isolation/never-upload-crash-reports` | 不上传崩溃报告 |
|
||||
| `isolation/never-launch-official-launcher` | 不拉起官方启动器 `launcher.exe` |
|
||||
| `online/network-hook-library` | 加载 `wto_ws.dll` 代替 `WS2_32.dll` |
|
||||
| `online/accept-local-tls-certificate` | 让 libcurl 接受本地服务器的自签名证书 |
|
||||
| `online/matching-server-public-key` | 匹配服务器公钥替换为本地服务器的公钥,用于解出会话密钥 |
|
||||
@@ -333,7 +334,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
||||
|
||||
- **Service addresses**: every Gaijin address in `config/network.blk` (`char.vromfs.bin`) and `config/settings.blk` (`aces.vromfs.bin`) is rewritten to `127.0.0.1:<port>`. The port is written at build time, so the server must use the same port.
|
||||
- **Config tables**: enables feature flags the offline copy needs, reveals hidden vehicles, adds a decal index, and registers GUIDs for local store packs.
|
||||
- **exe patches**: 12 patches under `patches/exe/`, listed below.
|
||||
- **exe patches**: 13 patches under `patches/exe/`, listed below.
|
||||
- **UI script patches**: 40 patches under `patches/gui/`, covering local account registration, battle start and settlement, store purchase receipts, and the inventory signing key.
|
||||
- **Network hook library**: the import table entry `WS2_32.dll` is renamed to `wto_ws.dll`, which has the same length. The library forwards every export of the system `ws2_32.dll` and uses MinHook to hook name resolution (`getaddrinfo` and others), connections (`connect`, `ConnectEx`, and others), and UDP sends, redirecting every external connection to the local server port. The port is read from `wto_ws.cfg` next to the exe.
|
||||
|
||||
@@ -344,6 +345,7 @@ Static data such as vehicles, tech trees, prices, and reward factors is extracte
|
||||
| `isolation/registry-key` | Moves registry settings to `Software\WTOffline` |
|
||||
| `isolation/never-load-battleye` | Never loads BattlEye |
|
||||
| `isolation/never-upload-crash-reports` | Never uploads crash reports |
|
||||
| `isolation/never-launch-official-launcher` | Never launches the official `launcher.exe` |
|
||||
| `online/network-hook-library` | Loads `wto_ws.dll` instead of `WS2_32.dll` |
|
||||
| `online/accept-local-tls-certificate` | Makes libcurl accept the local server's self-signed certificate |
|
||||
| `online/matching-server-public-key` | Replaces the matching server public key with the local server's, so it can decrypt the session key |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@wto/launcher",
|
||||
"productName": "WTOffline Launcher",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"private": true,
|
||||
"description": "Installer and launcher of the War Thunder offline project.",
|
||||
"type": "module",
|
||||
|
||||
@@ -176,10 +176,10 @@ export function registerIpcHandlers(): void {
|
||||
|
||||
handle('patches:active', () => activePatchSet());
|
||||
handle('patches:check', () => checkPackUpdate());
|
||||
handle('patches:apply', async () => {
|
||||
handle('patches:apply', async ({ version }) => {
|
||||
// A build reads the patch set while it runs; switch only between builds.
|
||||
if (maintenanceInProgress()) throw new AppError('maintenance_busy');
|
||||
const result = await applyPackUpdate();
|
||||
const result = await applyPackUpdate(version);
|
||||
if (result.ok) broadcast('event:patch-set-changed', result.active);
|
||||
return result;
|
||||
});
|
||||
|
||||
@@ -11,16 +11,25 @@ import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuni
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import {
|
||||
LauncherReleaseManifest,
|
||||
PortableReleaseManifest,
|
||||
type AppUpdateCheck, type AppUpdateProgress,
|
||||
} from '@shared/schemas/app-update.ts';
|
||||
import { gameProcessRunning } from '../launch/game-process.ts';
|
||||
import { FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type LauncherRelease } from '../patch-pack/release-feed.ts';
|
||||
import { readGithubAsset, requestGithubAsset } from './github-assets.ts';
|
||||
import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts';
|
||||
import {
|
||||
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease,
|
||||
} from '../patch-pack/release-feed.ts';
|
||||
import {
|
||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
||||
} from '../patch-pack/release-assets.ts';
|
||||
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
||||
|
||||
type UpdateMode = 'installer' | 'portable';
|
||||
|
||||
interface OfferedUpdate {
|
||||
readonly mode: UpdateMode;
|
||||
readonly release: LauncherRelease;
|
||||
readonly manifest: LauncherReleaseManifest;
|
||||
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
|
||||
}
|
||||
|
||||
class ManifestSignatureError extends Error {}
|
||||
@@ -42,11 +51,15 @@ async function exclusively<T>(action: () => Promise<T>): Promise<T> {
|
||||
}
|
||||
}
|
||||
|
||||
function stagedInstaller(): string {
|
||||
return join(app.getPath('userData'), 'launcher-updates', 'installer.exe');
|
||||
function updatesRoot(): string {
|
||||
return join(app.getPath('userData'), 'launcher-updates');
|
||||
}
|
||||
|
||||
async function matchesInstaller(path: string, manifest: LauncherReleaseManifest): Promise<boolean> {
|
||||
function stagedArtifact(mode: UpdateMode): string {
|
||||
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
|
||||
}
|
||||
|
||||
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
|
||||
try {
|
||||
const digest = await installerDigest(path, manifest.size);
|
||||
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
|
||||
@@ -70,6 +83,32 @@ function selectedOffer(version: string): OfferedUpdate {
|
||||
return offered;
|
||||
}
|
||||
|
||||
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
if (isPortableLauncher(app.isPackaged) && release.portable) {
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
]);
|
||||
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The portable release manifest signature does not match.');
|
||||
}
|
||||
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
|
||||
return { mode: 'portable', release, manifest };
|
||||
}
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
]);
|
||||
if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The release manifest signature does not match.');
|
||||
}
|
||||
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
|
||||
return { mode: 'installer', release, manifest };
|
||||
}
|
||||
|
||||
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
offered = null;
|
||||
@@ -77,22 +116,14 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
const key = packSigningPublicKey();
|
||||
if (!key) return { status: 'failed', problem: 'no_signing_key' };
|
||||
const installedVersion = app.getVersion();
|
||||
const latest = await newestProjectRelease('launcher', installedVersion);
|
||||
if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return { status: 'current' };
|
||||
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readGithubAsset(latest.manifest, 64 * 1024, deadline),
|
||||
readGithubAsset(latest.signature, 1024, deadline),
|
||||
]);
|
||||
if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The release manifest signature does not match.');
|
||||
}
|
||||
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== latest.version) throw new Error('The signed manifest version does not match the release tag.');
|
||||
|
||||
offered = { release: latest, manifest };
|
||||
return offerResult(offered, await matchesInstaller(stagedInstaller(), manifest));
|
||||
const offer = await withReleaseSources(async (source) => {
|
||||
const latest = await newestProjectRelease('launcher', installedVersion, source);
|
||||
if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return null;
|
||||
return signedOffer(latest, key);
|
||||
});
|
||||
if (!offer) return { status: 'current' };
|
||||
offered = offer;
|
||||
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
|
||||
} catch (error) {
|
||||
console.warn('[app-update] checking the release failed:', error);
|
||||
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
|
||||
@@ -111,67 +142,89 @@ export function downloadAppUpdate(
|
||||
): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
const { manifest } = offer;
|
||||
const target = stagedInstaller();
|
||||
if (await matchesInstaller(target, manifest)) return offerResult(offer, true);
|
||||
const partial = `${target}.partial`;
|
||||
const deadline = AbortSignal.timeout(30 * 60_000);
|
||||
let size = 0;
|
||||
let reportedAt = 0;
|
||||
const hash = createHash('sha256');
|
||||
const target = stagedArtifact(offer.mode);
|
||||
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
|
||||
try {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
const response = await requestGithubAsset(offer.release.installer, deadline);
|
||||
const monitor = new Transform({
|
||||
transform(chunk: Buffer, _encoding, done) {
|
||||
size += chunk.length;
|
||||
if (size > manifest.size) {
|
||||
done(new Error('The download is larger than the signed installer size.'));
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
if (size === manifest.size || Date.now() - reportedAt >= 200) {
|
||||
reportedAt = Date.now();
|
||||
report({ received: size, total: manifest.size });
|
||||
}
|
||||
done(null, chunk);
|
||||
},
|
||||
});
|
||||
await pipeline(response, monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||
if (size !== manifest.size || hash.digest('hex') !== manifest.sha256) {
|
||||
throw new Error('The installer download does not match the signed release.');
|
||||
}
|
||||
await rename(partial, target);
|
||||
await withReleaseSources(async (source) => {
|
||||
const release = sameReleaseSource(source, offer.release.source)
|
||||
? offer.release : await projectReleaseVersion('launcher', version, source);
|
||||
const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer;
|
||||
if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`);
|
||||
await stageArtifact(assetUrl, release.source, offer.manifest, target, report);
|
||||
}, offer.release.source);
|
||||
return offerResult(offer, true);
|
||||
} catch (error) {
|
||||
console.warn('[app-update] preparing the installer failed:', error);
|
||||
console.warn('[app-update] preparing the update asset failed:', error);
|
||||
throw new AppError('app_update_download_failed');
|
||||
} finally {
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stageArtifact(
|
||||
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
|
||||
report: (progress: AppUpdateProgress) => void,
|
||||
): Promise<void> {
|
||||
const partial = `${target}.partial`;
|
||||
const deadline = AbortSignal.timeout(30 * 60_000);
|
||||
let size = 0;
|
||||
let reportedAt = 0;
|
||||
const hash = createHash('sha256');
|
||||
try {
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
const response = await requestReleaseAsset(assetUrl, deadline, source);
|
||||
const monitor = new Transform({
|
||||
transform(chunk: Buffer, _encoding, done) {
|
||||
size += chunk.length;
|
||||
if (size > manifest.size) {
|
||||
done(new Error('The download is larger than the signed release size.'));
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
if (size === manifest.size || Date.now() - reportedAt >= 200) {
|
||||
reportedAt = Date.now();
|
||||
report({ received: size, total: manifest.size });
|
||||
}
|
||||
done(null, chunk);
|
||||
},
|
||||
});
|
||||
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||
if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.');
|
||||
if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.');
|
||||
await rename(partial, target);
|
||||
} catch (error) {
|
||||
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
||||
throw error;
|
||||
} finally {
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise<void> {
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
const path = stagedInstaller();
|
||||
if (!await matchesInstaller(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||
const path = stagedArtifact(offer.mode);
|
||||
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||
const signal = AbortSignal.timeout(5000);
|
||||
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
try {
|
||||
if (offer.mode === 'portable') {
|
||||
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||
launchPortableUpdater(prepared);
|
||||
app.quit();
|
||||
return;
|
||||
}
|
||||
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
|
||||
await once(installer, 'spawn');
|
||||
installer.unref();
|
||||
app.quit();
|
||||
} catch (error) {
|
||||
console.warn('[app-update] starting the installer failed:', error);
|
||||
console.warn('[app-update] starting the update failed:', error);
|
||||
throw new AppError('app_update_install_failed');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import type { Readable } from 'node:stream';
|
||||
import { net, type IncomingMessage } from 'electron';
|
||||
import { FeedUnreachableError } from '../patch-pack/release-feed.ts';
|
||||
|
||||
const ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']);
|
||||
|
||||
function isGithubAsset(value: string): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === 'https:' && ASSET_HOSTS.has(url.hostname) && !url.port && !url.username && !url.password;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Request only GitHub assets, including every redirect, without sending session credentials. */
|
||||
export async function requestGithubAsset(url: URL, signal: AbortSignal): Promise<IncomingMessage & Readable> {
|
||||
signal.throwIfAborted();
|
||||
if (!isGithubAsset(url.href)) throw new FeedUnreachableError('The release asset is outside GitHub.');
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' });
|
||||
request.setHeader('User-Agent', 'WTOffline-Launcher');
|
||||
const abort = (): void => {
|
||||
cleanup();
|
||||
reject(signal.reason);
|
||||
request.abort();
|
||||
};
|
||||
const cleanup = (): void => signal.removeEventListener('abort', abort);
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
|
||||
request.once('error', (error) => {
|
||||
cleanup();
|
||||
reject(new FeedUnreachableError(error.message));
|
||||
});
|
||||
request.on('redirect', (_status, _method, destination) => {
|
||||
if (isGithubAsset(destination)) request.followRedirect();
|
||||
else {
|
||||
cleanup();
|
||||
reject(new FeedUnreachableError('The release asset redirected outside GitHub.'));
|
||||
request.abort();
|
||||
}
|
||||
});
|
||||
request.once('response', (response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
cleanup();
|
||||
reject(new FeedUnreachableError(`GitHub answered HTTP ${response.statusCode} for a release asset.`));
|
||||
request.abort();
|
||||
return;
|
||||
}
|
||||
// The request's writable side can close before the response arrives.
|
||||
const stream = response as IncomingMessage & Readable;
|
||||
stream.once('end', cleanup);
|
||||
stream.once('close', cleanup);
|
||||
resolve(stream);
|
||||
});
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
export async function readGithubAsset(url: URL, limit: number, signal: AbortSignal): Promise<Uint8Array> {
|
||||
const response = await requestGithubAsset(url, signal);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of response) {
|
||||
const bytes = chunk as Buffer;
|
||||
size += bytes.length;
|
||||
if (size > limit) throw new Error('Release metadata is larger than expected.');
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
@@ -3,11 +3,16 @@ import { createReadStream } from 'node:fs';
|
||||
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
||||
|
||||
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
||||
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
|
||||
|
||||
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
||||
const hash = createHash('sha256');
|
||||
let size = 0;
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
|
||||
*
|
||||
* Extraction and path validation happen while the launcher is still running so a bad archive or
|
||||
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
|
||||
* for this process to exit, overwrites only files listed in the new portable inventory, removes
|
||||
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||
* files in the same folder), and restarts the updated executable.
|
||||
*/
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { z } from 'zod';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||
|
||||
const PortableInventorySchema = z.object({
|
||||
format: z.literal(1),
|
||||
version: z.string().min(1),
|
||||
files: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
|
||||
export interface PreparedPortableUpdate {
|
||||
readonly scriptPath: string;
|
||||
readonly planPath: string;
|
||||
readonly stagingDir: string;
|
||||
}
|
||||
|
||||
export interface PortableUpdatePlan {
|
||||
readonly pid: number;
|
||||
readonly installDir: string;
|
||||
readonly stagingDir: string;
|
||||
readonly archivePath: string;
|
||||
readonly logPath: string;
|
||||
readonly executable: string;
|
||||
readonly newFiles: readonly string[];
|
||||
readonly staleFiles: readonly string[];
|
||||
}
|
||||
|
||||
export function isPortableLauncher(isPackaged: boolean): boolean {
|
||||
if (!isPackaged || process.platform !== 'win32') return false;
|
||||
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
|
||||
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
|
||||
}
|
||||
|
||||
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
|
||||
export function isSafePortableRelativePath(entry: string): boolean {
|
||||
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
|
||||
if (/[\0-\x1f]/.test(entry)) return false;
|
||||
const parts = entry.split('/');
|
||||
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
function resolveInside(root: string, relPosix: string): string {
|
||||
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
|
||||
const target = resolve(root, ...relPosix.split('/'));
|
||||
const rel = relative(root, target);
|
||||
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
|
||||
throw new Error(`Portable path escapes root: ${relPosix}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
|
||||
try {
|
||||
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
|
||||
return parsed.files.filter(isSafePortableRelativePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function assertWritableFolder(folder: string): Promise<void> {
|
||||
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
|
||||
await writeFile(probe, '', { flag: 'wx' });
|
||||
await rm(probe, { force: true });
|
||||
}
|
||||
|
||||
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
|
||||
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
|
||||
const script = [
|
||||
'param([string]$ZipPath, [string]$DestDir)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
|
||||
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
|
||||
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
|
||||
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
|
||||
'try {',
|
||||
' foreach ($entry in $zip.Entries) {',
|
||||
' $name = $entry.FullName',
|
||||
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
|
||||
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
|
||||
' throw "Unsafe zip entry: $name"',
|
||||
' }',
|
||||
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
|
||||
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
|
||||
' throw "Zip entry escapes destination: $name"',
|
||||
' }',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($target)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
|
||||
' }',
|
||||
'} finally {',
|
||||
' $zip.Dispose()',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||
try {
|
||||
await execute('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', extractScriptPath, zipPath, stagingDir,
|
||||
], { windowsHide: true, timeout: 180_000 });
|
||||
} finally {
|
||||
await rm(extractScriptPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPortableApplyScript(): string {
|
||||
return [
|
||||
'param([string]$PlanPath)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
|
||||
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
|
||||
'function Write-Log([string]$msg) {',
|
||||
' try {',
|
||||
' $line = "$(Get-Date -Format o) $msg`r`n"',
|
||||
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
|
||||
' } catch {}',
|
||||
'}',
|
||||
'try {',
|
||||
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
|
||||
' $deadline = (Get-Date).AddSeconds(30)',
|
||||
' while ((Get-Date) -lt $deadline) {',
|
||||
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
|
||||
' Start-Sleep -Milliseconds 200',
|
||||
' }',
|
||||
' Start-Sleep -Milliseconds 400',
|
||||
' foreach ($rel in $plan.newFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
|
||||
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' $copied = $false',
|
||||
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
|
||||
' try {',
|
||||
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
|
||||
' [System.IO.File]::Copy($src, $dst, $true)',
|
||||
' $copied = $true',
|
||||
' break',
|
||||
' } catch {',
|
||||
' if ($attempt -eq 20) { throw }',
|
||||
' Start-Sleep -Milliseconds 300',
|
||||
' }',
|
||||
' }',
|
||||
' if (-not $copied) { throw "Failed to copy $rel" }',
|
||||
' }',
|
||||
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
|
||||
' foreach ($rel in $plan.staleFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' if ([System.IO.File]::Exists($old)) {',
|
||||
' try {',
|
||||
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
|
||||
' [System.IO.File]::Delete($old)',
|
||||
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
|
||||
' }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($old)',
|
||||
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
|
||||
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
|
||||
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
|
||||
' if ($entries.Length -gt 0) { break }',
|
||||
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
|
||||
' }',
|
||||
' }',
|
||||
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
|
||||
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
|
||||
' }',
|
||||
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
|
||||
' }',
|
||||
' if ([System.IO.File]::Exists($PlanPath)) {',
|
||||
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
|
||||
' }',
|
||||
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
|
||||
' if ([System.IO.File]::Exists($exe)) {',
|
||||
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
|
||||
' Write-Log "Relaunched $exe"',
|
||||
' }',
|
||||
'} catch {',
|
||||
' Write-Log "Portable update failed: $_"',
|
||||
' exit 1',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
}
|
||||
|
||||
export async function preparePortableInstall(
|
||||
archivePath: string,
|
||||
expectedVersion: string,
|
||||
updatesRoot: string,
|
||||
installDir = dirname(process.execPath),
|
||||
resourcesDir = process.resourcesPath,
|
||||
parentPid = process.pid,
|
||||
): Promise<PreparedPortableUpdate> {
|
||||
await assertWritableFolder(installDir);
|
||||
await mkdir(updatesRoot, { recursive: true });
|
||||
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||
await mkdir(stagingDir, { recursive: true });
|
||||
try {
|
||||
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
|
||||
|
||||
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
|
||||
if (stagedInventory.version !== expectedVersion) {
|
||||
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
|
||||
}
|
||||
const newFiles = stagedInventory.files;
|
||||
const newSet = new Set(newFiles);
|
||||
const requiredEntries = [
|
||||
LAUNCHER_EXECUTABLE,
|
||||
`resources/${PORTABLE_MARKER_FILE}`,
|
||||
`resources/${PORTABLE_FILES_MANIFEST}`,
|
||||
];
|
||||
for (const required of requiredEntries) {
|
||||
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
|
||||
}
|
||||
for (const rel of newFiles) {
|
||||
const stagedPath = resolveInside(stagingDir, rel);
|
||||
const stats = await lstat(stagedPath);
|
||||
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||
}
|
||||
|
||||
const oldFiles = await readPortableInventory(resourcesDir);
|
||||
const staleFiles = oldFiles
|
||||
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
|
||||
: [];
|
||||
|
||||
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
|
||||
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
|
||||
const plan: PortableUpdatePlan = {
|
||||
pid: parentPid,
|
||||
installDir: resolve(installDir),
|
||||
stagingDir,
|
||||
archivePath,
|
||||
logPath: join(updatesRoot, 'portable-update.log'),
|
||||
executable: LAUNCHER_EXECUTABLE,
|
||||
newFiles,
|
||||
staleFiles,
|
||||
};
|
||||
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
|
||||
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||
return { scriptPath, planPath, stagingDir };
|
||||
} catch (error) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
||||
const child = spawn('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', prepared.scriptPath, prepared.planPath,
|
||||
], {
|
||||
cwd: dirname(prepared.scriptPath),
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { AppError } from '@shared/errors.ts';
|
||||
import type { Copies } from '@shared/schemas/install.ts';
|
||||
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
|
||||
import { hydrateCopiesStatus, relocateCopyRecord } from '../install/install-record.ts';
|
||||
import { backUpStockFiles } from '../install/stock-backup.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup } from '../install/stock-backup.ts';
|
||||
|
||||
/**
|
||||
* Re-point an existing registered client to its moved folder while keeping its id, name, saves,
|
||||
@@ -12,7 +12,10 @@ export async function relocateCopy(id: string, newPath: string): Promise<Copies>
|
||||
const game = await inspectGameFolder(newPath);
|
||||
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path: newPath });
|
||||
if (game.needsStockSource) throw new AppError('stock_source_invalid');
|
||||
const stockBackupPath = await backUpStockFiles(game.resolvedPath);
|
||||
const stock = await installStockSource(game.resolvedPath, game.version);
|
||||
const stockBackupPath = stock.refresh
|
||||
? await refreshStockBackup(game.resolvedPath)
|
||||
: await backUpStockFiles(game.resolvedPath);
|
||||
const updated = await relocateCopyRecord(id, {
|
||||
copyPath: newPath,
|
||||
stockBackupPath,
|
||||
|
||||
@@ -1,15 +1,31 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { release } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { app, dialog, shell, type BrowserWindow } from 'electron';
|
||||
import { zipSync } from 'fflate';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { COPIES_FILENAME, readInstallRecord } from '../install/install-record.ts';
|
||||
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
|
||||
|
||||
type ArchiveFiles = Record<string, Uint8Array>;
|
||||
|
||||
/** Bound individual client log files so a huge crash dump or session log cannot exhaust memory. */
|
||||
const MAX_CLIENT_LOG_BYTES = 16 * 1024 * 1024;
|
||||
/** Number of recent .game_logs entries listed in client-logs/summary.json. */
|
||||
const RECENT_GAME_LOGS_LIMIT = 10;
|
||||
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||
const HOOK_CONFIG_FILENAME = 'wto_ws.cfg';
|
||||
|
||||
interface ListedFile {
|
||||
readonly name: string;
|
||||
readonly size: number;
|
||||
readonly modifiedAt: string;
|
||||
}
|
||||
|
||||
export async function openLogsFolder(): Promise<void> {
|
||||
const path = launcherLogFolder();
|
||||
try {
|
||||
@@ -45,6 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
|
||||
if (dataPath) await addServerLogs(files, dataPath);
|
||||
if (record) await addClientLogs(files, record);
|
||||
|
||||
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
@@ -73,6 +90,145 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise<voi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Include the hook library log, the latest game .clog and a small metadata summary for the active
|
||||
* client so startup crashes can be diagnosed without touching player saves.
|
||||
*/
|
||||
async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promise<void> {
|
||||
const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable));
|
||||
const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME);
|
||||
const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME);
|
||||
const gameLogsFolder = join(record.copyPath, '.game_logs');
|
||||
|
||||
const [hookLogStat, hookConfigStat] = await Promise.all([
|
||||
readRegularFileStat(hookLogPath),
|
||||
readRegularFileStat(hookConfigPath),
|
||||
]);
|
||||
|
||||
let hookLogIncluded = false;
|
||||
let hookLogOmittedReason: string | null = null;
|
||||
if (hookLogStat) {
|
||||
const added = await addBoundedClientFile(files, `client-logs/${HOOK_LOG_FILENAME}`, hookLogPath, hookLogStat.size);
|
||||
hookLogIncluded = added.included;
|
||||
hookLogOmittedReason = added.omittedReason;
|
||||
}
|
||||
|
||||
const recentGameLogs: ListedFile[] = [];
|
||||
let latestClog: ListedFile | null = null;
|
||||
let latestClogIncluded = false;
|
||||
let latestClogOmittedReason: string | null = null;
|
||||
|
||||
const gameLogsDirStat = await safeStat(gameLogsFolder);
|
||||
if (gameLogsDirStat?.isDirectory()) {
|
||||
const entries = await safeReadDir(gameLogsFolder);
|
||||
const inspected: Array<ListedFile & { readonly mtimeMs: number }> = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
const stats = await readRegularFileStat(join(gameLogsFolder, entry.name));
|
||||
if (!stats) continue;
|
||||
inspected.push({
|
||||
name: entry.name,
|
||||
size: stats.size,
|
||||
modifiedAt: new Date(stats.mtimeMs).toISOString(),
|
||||
mtimeMs: stats.mtimeMs,
|
||||
});
|
||||
}
|
||||
inspected.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
||||
for (const item of inspected.slice(0, RECENT_GAME_LOGS_LIMIT)) {
|
||||
recentGameLogs.push({ name: item.name, size: item.size, modifiedAt: item.modifiedAt });
|
||||
}
|
||||
const newestClog = inspected.find((item) => item.name.toLowerCase().endsWith('.clog')) ?? null;
|
||||
if (newestClog) {
|
||||
latestClog = { name: newestClog.name, size: newestClog.size, modifiedAt: newestClog.modifiedAt };
|
||||
const added = await addBoundedClientFile(
|
||||
files,
|
||||
`client-logs/game-logs/${newestClog.name}`,
|
||||
join(gameLogsFolder, newestClog.name),
|
||||
newestClog.size,
|
||||
);
|
||||
latestClogIncluded = added.included;
|
||||
latestClogOmittedReason = added.omittedReason;
|
||||
}
|
||||
}
|
||||
|
||||
const summary = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
launcherVersion: app.getVersion(),
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
osRelease: release(),
|
||||
copyId: record.id,
|
||||
gameVersion: record.gameVersion,
|
||||
hookConfig: hookConfigStat
|
||||
? { present: true, size: hookConfigStat.size, modifiedAt: new Date(hookConfigStat.mtimeMs).toISOString() }
|
||||
: { present: false },
|
||||
hookLog: hookLogStat
|
||||
? {
|
||||
present: true,
|
||||
size: hookLogStat.size,
|
||||
modifiedAt: new Date(hookLogStat.mtimeMs).toISOString(),
|
||||
included: hookLogIncluded,
|
||||
...(hookLogOmittedReason ? { omittedReason: hookLogOmittedReason } : {}),
|
||||
}
|
||||
: { present: false },
|
||||
gameLogsFolderPresent: gameLogsDirStat?.isDirectory() ?? false,
|
||||
recentGameLogs,
|
||||
latestClog: latestClog
|
||||
? {
|
||||
...latestClog,
|
||||
included: latestClogIncluded,
|
||||
...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`);
|
||||
}
|
||||
|
||||
async function addBoundedClientFile(
|
||||
files: ArchiveFiles,
|
||||
entry: string,
|
||||
path: string,
|
||||
size: number,
|
||||
): Promise<{ readonly included: boolean; readonly omittedReason: string | null }> {
|
||||
if (size > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||
try {
|
||||
const bytes = await readFile(path);
|
||||
if (bytes.byteLength > MAX_CLIENT_LOG_BYTES) return { included: false, omittedReason: 'too-large' };
|
||||
files[entry] = bytes;
|
||||
return { included: true, omittedReason: null };
|
||||
} catch (error) {
|
||||
console.warn('[diagnostics] could not read client log:', path, error);
|
||||
return { included: false, omittedReason: 'unreadable' };
|
||||
}
|
||||
}
|
||||
|
||||
async function readRegularFileStat(path: string) {
|
||||
const stats = await safeStat(path);
|
||||
return stats?.isFile() ? stats : null;
|
||||
}
|
||||
|
||||
async function safeStat(path: string) {
|
||||
try {
|
||||
return await lstat(path);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.warn('[diagnostics] could not inspect path:', path, error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function safeReadDir(path: string) {
|
||||
try {
|
||||
return await readdir(path, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
console.warn('[diagnostics] could not read folder:', path, error);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function addFile(files: ArchiveFiles, entry: string, path: string): Promise<void> {
|
||||
if (!(await ifPresent(() => lstat(path)))?.isFile()) return;
|
||||
const bytes = await ifPresent(() => readFile(path));
|
||||
|
||||
@@ -23,28 +23,43 @@ export async function inspectGameFolder(path: string): Promise<GameFolderInspect
|
||||
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
|
||||
}
|
||||
const stockRoot = join(resolved, STOCK_BACKUP_FOLDER);
|
||||
let hasOfflineBackup = true;
|
||||
let hasStockFiles = true;
|
||||
for (const file of required) {
|
||||
if (!(await exists(join(stockRoot, file)))) {
|
||||
hasOfflineBackup = false;
|
||||
hasStockFiles = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const resources = resourcePaths();
|
||||
const executablePath = hasOfflineBackup
|
||||
? join(stockRoot, GAME_FILES.executable)
|
||||
: join(resolved, GAME_FILES.executable);
|
||||
const executableBytes = (!hasOfflineBackup && missingFiles.includes(GAME_FILES.executable))
|
||||
const liveExeBytes = missingFiles.includes(GAME_FILES.executable)
|
||||
? null
|
||||
: await readBytes(executablePath);
|
||||
const version = executableBytes ? readVersionFromBytes(executableBytes) : null;
|
||||
: await readBytes(join(resolved, GAME_FILES.executable));
|
||||
const liveVersion = liveExeBytes ? readVersionFromBytes(liveExeBytes) : null;
|
||||
const backupExeBytes = hasStockFiles
|
||||
? await readBytes(join(stockRoot, GAME_FILES.executable))
|
||||
: null;
|
||||
const backupVersion = backupExeBytes ? readVersionFromBytes(backupExeBytes) : null;
|
||||
|
||||
// Always report the live executable's version when readable so an externally updated client
|
||||
// (for example, an in-place folder updated by the official launcher) is never masked by a stale
|
||||
// wtoffline/stock backup.
|
||||
const version = liveVersion ?? backupVersion;
|
||||
const hasOfflineBackup = hasStockFiles && backupVersion !== null && (liveVersion === null || backupVersion === liveVersion);
|
||||
const liveExePatched = liveExeBytes !== null && liveExeBytes.includes(PATCHED_EXE_MARKER);
|
||||
|
||||
let needsStockSource = false;
|
||||
if (!hasOfflineBackup && missingFiles.length === 0) {
|
||||
const exeDir = join(resolved, dirname(GAME_FILES.executable));
|
||||
const hasMarkerFile = (await Promise.all(
|
||||
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
|
||||
)).some(Boolean);
|
||||
needsStockSource = hasMarkerFile || (executableBytes !== null && executableBytes.includes(PATCHED_EXE_MARKER));
|
||||
if (hasStockFiles && backupVersion !== null && liveVersion !== null && backupVersion !== liveVersion) {
|
||||
// A stale stock backup only needs an external stock source if the live executable is already
|
||||
// patched; an unpatched live executable can refresh wtoffline/stock directly during install.
|
||||
needsStockSource = liveExePatched;
|
||||
} else {
|
||||
const exeDir = join(resolved, dirname(GAME_FILES.executable));
|
||||
const hasMarkerFile = (await Promise.all(
|
||||
PATCH_MARKER_FILES.map((file) => exists(join(exeDir, file))),
|
||||
)).some(Boolean);
|
||||
needsStockSource = hasMarkerFile || liveExePatched;
|
||||
}
|
||||
}
|
||||
return {
|
||||
path,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { discardDecalCache, importDecalCache } from './decals.ts';
|
||||
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
|
||||
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
|
||||
import { checkPatches } from './patch-check.ts';
|
||||
import { backUpStockFiles, backUpStockFilesFrom, installStockSource, refreshStockBackup, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
|
||||
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
|
||||
|
||||
/**
|
||||
* Install the offline version: check the patches against the player's game,
|
||||
@@ -95,7 +95,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
|
||||
|
||||
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
|
||||
const stockBackup = externalStockPath
|
||||
? await backUpStockFilesFrom(copyPath, externalStockPath)
|
||||
? await refreshStockBackupFrom(copyPath, externalStockPath)
|
||||
: (request.method === 'in-place' || request.method === 'existing') && stock.refresh
|
||||
? await refreshStockBackup(copyPath)
|
||||
: await backUpStockFiles(copyPath);
|
||||
|
||||
@@ -50,22 +50,36 @@ export async function backUpStockFilesFrom(copyFolder: string, sourceFolder: str
|
||||
return backup;
|
||||
}
|
||||
|
||||
/** A new game version must pass the patch checks before replacing an existing stock backup. */
|
||||
/** A new game version or damaged backup must pass the patch checks before replacing wtoffline/stock. */
|
||||
export async function installStockSource(copyFolder: string, version: string | null) {
|
||||
const backup = await requireStockBackupLocation(copyFolder);
|
||||
if (!await exists(join(backup, GAME_FILES.executable))) return { path: copyFolder, refresh: await exists(backup) };
|
||||
const backedUpVersion = executableVersion(await readFile(join(backup, GAME_FILES.executable)));
|
||||
return version !== null && backedUpVersion !== version ? { path: copyFolder, refresh: true } : { path: backup, refresh: false };
|
||||
const backupExe = join(backup, GAME_FILES.executable);
|
||||
if (!await exists(backupExe)) return { path: copyFolder, refresh: await exists(backup) };
|
||||
let backedUpVersion: string | null = null;
|
||||
try {
|
||||
backedUpVersion = executableVersion(await readFile(backupExe));
|
||||
} catch (error) {
|
||||
console.warn('[stock-backup] unreadable backed-up executable, will refresh:', backupExe, error);
|
||||
return { path: copyFolder, refresh: true };
|
||||
}
|
||||
return backedUpVersion === null || (version !== null && backedUpVersion !== version)
|
||||
? { path: copyFolder, refresh: true }
|
||||
: { path: backup, refresh: false };
|
||||
}
|
||||
|
||||
export async function refreshStockBackup(copyFolder: string): Promise<string> {
|
||||
return refreshStockBackupFrom(copyFolder, copyFolder);
|
||||
}
|
||||
|
||||
/** Replace wtoffline/stock atomically with the four stock files from `sourceFolder`. */
|
||||
export async function refreshStockBackupFrom(copyFolder: string, sourceFolder: string): Promise<string> {
|
||||
const backup = await requireStockBackupLocation(copyFolder);
|
||||
return await changeCopyFiles(copyFolder, async (incoming) => {
|
||||
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
|
||||
for (const file of Object.values(GAME_FILES)) {
|
||||
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await copyFile(join(copyFolder, file), target);
|
||||
await copyFile(join(sourceFolder, file), target);
|
||||
}
|
||||
return { replace, remove: [] };
|
||||
}, async () => backup);
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { constants } from 'node:fs';
|
||||
import { access, lstat, open, readdir } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
||||
import type { GameExit } from '@shared/schemas/launch.ts';
|
||||
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const HOOK_DLL_FILENAME = 'wto_ws.dll';
|
||||
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
|
||||
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
||||
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
|
||||
const HOOK_LOG_TAIL_LINES = 8;
|
||||
const HOOK_LOG_LINE_LIMIT = 200;
|
||||
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
|
||||
const MTIME_SKEW_MS = 2000;
|
||||
|
||||
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
||||
if (process.platform !== 'win32') return false;
|
||||
@@ -18,8 +28,13 @@ export async function runGameProcess(
|
||||
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
||||
): Promise<GameExit> {
|
||||
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
||||
await verifyLaunchFiles(copyPath);
|
||||
signal.throwIfAborted();
|
||||
const child = spawn(join(copyPath, GAME_FILES.executable), [...offlineGameArguments, ...additionalArguments], {
|
||||
const executable = join(copyPath, GAME_FILES.executable);
|
||||
const args = [...offlineGameArguments, ...additionalArguments];
|
||||
const startedAt = Date.now();
|
||||
console.info('[game] starting:', executable, args);
|
||||
const child = spawn(executable, args, {
|
||||
cwd: copyPath, shell: false, stdio: 'ignore',
|
||||
});
|
||||
const stop = (): void => { child.kill(); };
|
||||
@@ -27,6 +42,7 @@ export async function runGameProcess(
|
||||
try {
|
||||
return await new Promise<GameExit>((resolve, reject) => {
|
||||
child.once('spawn', () => {
|
||||
console.info('[game] process started, pid:', child.pid ?? 'unknown');
|
||||
if (signal.aborted) stop();
|
||||
else onStart();
|
||||
});
|
||||
@@ -36,9 +52,16 @@ export async function runGameProcess(
|
||||
});
|
||||
child.once('close', (code, reason) => {
|
||||
const logFolder = join(copyPath, '.game_logs');
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
|
||||
if (code !== 0 && !signal.aborted) {
|
||||
console.warn('[game] process exited:', code ?? reason, logFolder);
|
||||
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
|
||||
void logAbnormalExitContext(copyPath, startedAt)
|
||||
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
|
||||
.finally(() => resolve({ code, signal: reason, logFolder }));
|
||||
return;
|
||||
}
|
||||
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
|
||||
resolve({ code, signal: reason, logFolder });
|
||||
});
|
||||
signal.addEventListener('abort', stop, { once: true });
|
||||
@@ -47,3 +70,103 @@ export async function runGameProcess(
|
||||
signal.removeEventListener('abort', stop);
|
||||
}
|
||||
}
|
||||
|
||||
/** Verify the patched executable and hook files are still present and readable right before spawn. */
|
||||
async function verifyLaunchFiles(copyPath: string): Promise<void> {
|
||||
const exeFolder = dirname(GAME_FILES.executable);
|
||||
const required = [
|
||||
GAME_FILES.executable,
|
||||
join(exeFolder, HOOK_DLL_FILENAME),
|
||||
join(exeFolder, HOOK_CFG_FILENAME),
|
||||
];
|
||||
const missing: string[] = [];
|
||||
for (const relativePath of required) {
|
||||
const fullPath = join(copyPath, relativePath);
|
||||
try {
|
||||
const stats = await lstat(fullPath);
|
||||
if (!stats.isFile() || stats.size === 0) {
|
||||
missing.push(`${relativePath} (not a non-empty file)`);
|
||||
continue;
|
||||
}
|
||||
await access(fullPath, constants.R_OK);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code ?? 'error';
|
||||
missing.push(`${relativePath} (${code})`);
|
||||
}
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
console.error('[game] required launch files unavailable before start:', missing.join(', '));
|
||||
throw new AppError('launch_game_files_missing');
|
||||
}
|
||||
}
|
||||
|
||||
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
|
||||
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
|
||||
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
|
||||
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
|
||||
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
|
||||
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
|
||||
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
|
||||
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
|
||||
]);
|
||||
const hookLogDesc = hookLogStat
|
||||
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
|
||||
: 'missing';
|
||||
console.warn(
|
||||
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
|
||||
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
|
||||
);
|
||||
if (hookLogStat && hookLogStat.size > 0) {
|
||||
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
|
||||
if (tail.length > 0) {
|
||||
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function describeFile(path: string): Promise<string> {
|
||||
const stats = await safeRegularStat(path);
|
||||
return stats ? `${stats.size} bytes` : 'missing';
|
||||
}
|
||||
|
||||
async function safeRegularStat(path: string) {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
return stats.isFile() ? stats : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
|
||||
try {
|
||||
const entries = await readdir(folder, { withFileTypes: true });
|
||||
const recent: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
const stats = await safeRegularStat(join(folder, entry.name));
|
||||
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
|
||||
recent.push(`${entry.name} (${stats.size} bytes)`);
|
||||
}
|
||||
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
|
||||
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
|
||||
const start = fileSize - length;
|
||||
const handle = await open(path, 'r');
|
||||
try {
|
||||
const buffer = Buffer.alloc(length);
|
||||
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
||||
const text = buffer.subarray(0, bytesRead).toString('utf8');
|
||||
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
|
||||
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
|
||||
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
|
||||
));
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
@@ -144,6 +144,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
||||
}
|
||||
const currentVersion = await readVersion(record.copyPath, signal);
|
||||
if (!currentVersion || currentVersion !== record.gameVersion) {
|
||||
console.warn(
|
||||
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
|
||||
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
|
||||
);
|
||||
update(job, { phase: 'version-changed', actualVersion: currentVersion });
|
||||
return null;
|
||||
}
|
||||
@@ -171,6 +175,11 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (!copyVersion || copyVersion !== stockVersion) {
|
||||
console.warn(
|
||||
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
|
||||
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
|
||||
);
|
||||
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
|
||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||
}
|
||||
if (games) throw new AppError('launch_game_running');
|
||||
@@ -189,6 +198,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
update(job, { phase: 'building', port });
|
||||
const buildStart = Date.now();
|
||||
let writtenFiles = 0;
|
||||
await buildCopy({
|
||||
kind: 'build',
|
||||
stockPath,
|
||||
@@ -200,10 +211,12 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc
|
||||
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
writtenFiles = filesWritten;
|
||||
if (!signal.aborted) update(job, {
|
||||
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
});
|
||||
});
|
||||
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
|
||||
}
|
||||
|
||||
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Adaptation pack updates: which patch set the builds use, whether GitHub has a newer pack, and
|
||||
* Adaptation pack updates: which patch set the builds use, whether a source has a newer pack, and
|
||||
* installing it. The launcher checks at start (when the setting allows) and from the About page;
|
||||
* a pack is installed only when the player confirms.
|
||||
*
|
||||
@@ -20,12 +20,10 @@ import {
|
||||
import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts';
|
||||
import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts';
|
||||
import { activeDownloadedPack, bundledPatchVersion, installPack, useBundledPatchSet } from './pack-store.ts';
|
||||
import { downloadReleaseFile, FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type PackReleaseFiles } from './release-feed.ts';
|
||||
|
||||
/** The manifest copy beside a release is a few hundred bytes. */
|
||||
const MANIFEST_COPY_MAX_BYTES = 64 * 1024;
|
||||
/** A signature file is 89 bytes. */
|
||||
const SIGNATURE_MAX_BYTES = 1024;
|
||||
import {
|
||||
newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, withReleaseSources, type PackReleaseFiles, type ReleaseSource,
|
||||
} from './release-feed.ts';
|
||||
import { FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES } from './release-assets.ts';
|
||||
|
||||
export function activePatchSet(): ActivePatchSet {
|
||||
const root = bundledResourcePaths().patches;
|
||||
@@ -38,7 +36,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
|
||||
const active = activePatchSet();
|
||||
if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
|
||||
try {
|
||||
const found = await newestRelease(active.version);
|
||||
const found = await withReleaseSources((source) => newestRelease(active.version, source));
|
||||
if (!found || !isNewer(found.manifest.version, active.version)) return { status: 'up_to_date', active, latest: found ? release(found) : null, problem: null };
|
||||
const status = manifestIncompatibility(found.manifest, app.getVersion()) ? 'needs_app_update' : 'available';
|
||||
return { status, active, latest: release(found), problem: null };
|
||||
@@ -48,18 +46,26 @@ export async function checkPackUpdate(): Promise<PackCheck> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Download and activate the newest pack, when it is newer than the active set and usable. */
|
||||
export async function applyPackUpdate(): Promise<PackApplyResult> {
|
||||
/** Download and activate the selected pack when it is newer than the active set and usable. */
|
||||
export async function applyPackUpdate(version: string): Promise<PackApplyResult> {
|
||||
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
|
||||
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
try {
|
||||
const found = await newestRelease(activePatchSet().version);
|
||||
if (!found || !isNewer(found.manifest.version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
if (manifestIncompatibility(found.manifest, app.getVersion())) return { ok: false, problem: 'needs_app_update' };
|
||||
const tuning = patchPackTuning();
|
||||
const zip = await downloadReleaseFile(found.files.zipUrl, tuning.maxPackBytes);
|
||||
const signature = new TextDecoder().decode(await downloadReleaseFile(found.files.signatureUrl, SIGNATURE_MAX_BYTES));
|
||||
await installPack(found.files.version, zip, signature);
|
||||
console.info(`[patch-pack] pack ${found.files.version} installed and active`);
|
||||
const downloaded = await withReleaseSources(async (source) => {
|
||||
const files = await projectReleaseVersion('pack', version, source);
|
||||
const manifest = await readPackManifest(files);
|
||||
if (manifestIncompatibility(manifest, app.getVersion())) return null;
|
||||
const tuning = patchPackTuning();
|
||||
const zip = await readReleaseAsset(files.zipUrl, tuning.maxPackBytes, AbortSignal.timeout(tuning.requestTimeoutMs), source);
|
||||
const signature = new TextDecoder().decode(await readReleaseAsset(
|
||||
files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, AbortSignal.timeout(tuning.requestTimeoutMs), source,
|
||||
));
|
||||
return { zip, signature };
|
||||
});
|
||||
if (!downloaded) return { ok: false, problem: 'needs_app_update' };
|
||||
if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' };
|
||||
await installPack(version, downloaded.zip, downloaded.signature);
|
||||
console.info(`[patch-pack] pack ${version} installed and active`);
|
||||
return { ok: true, active: activePatchSet() };
|
||||
} catch (error) {
|
||||
console.warn('[patch-pack] update failed:', error);
|
||||
@@ -78,13 +84,17 @@ interface FoundRelease {
|
||||
readonly manifest: PatchPackManifest;
|
||||
}
|
||||
|
||||
async function newestRelease(installedVersion: string | null): Promise<FoundRelease | null> {
|
||||
const files = await newestProjectRelease('pack', installedVersion);
|
||||
if (!files) return null;
|
||||
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
|
||||
async function newestRelease(installedVersion: string | null, source: ReleaseSource): Promise<FoundRelease | null> {
|
||||
const files = await newestProjectRelease('pack', installedVersion, source);
|
||||
return files ? { files, manifest: await readPackManifest(files) } : null;
|
||||
}
|
||||
|
||||
async function readPackManifest(files: PackReleaseFiles): Promise<PatchPackManifest> {
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
const text = new TextDecoder().decode(await readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, deadline, files.source));
|
||||
const manifest = parseManifest(text);
|
||||
if (manifest.version !== files.version) throw new PatchPackError('contents', `release ${files.version} carries the manifest of ${manifest.version}`);
|
||||
return { files, manifest };
|
||||
return manifest;
|
||||
}
|
||||
|
||||
function release(found: FoundRelease): PackRelease {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Readable } from 'node:stream';
|
||||
import { net, type IncomingMessage } from 'electron';
|
||||
import { PatchPackError } from '@wto/patcher';
|
||||
import type { ReleaseSource } from './release-feed.ts';
|
||||
|
||||
const GITHUB_ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']);
|
||||
export const UPDATE_USER_AGENT = 'WTOffline-Launcher';
|
||||
export const RELEASE_MANIFEST_MAX_BYTES = 64 * 1024;
|
||||
export const RELEASE_SIGNATURE_MAX_BYTES = 1024;
|
||||
|
||||
export class FeedUnreachableError extends Error {
|
||||
override readonly name = 'FeedUnreachableError';
|
||||
}
|
||||
|
||||
function isReleaseAsset(value: string, source: ReleaseSource): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== 'https:' || url.username || url.password) return false;
|
||||
return !source.githubDownloads || (!url.port && GITHUB_ASSET_HOSTS.has(url.hostname));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Download over HTTPS, including redirects, without sending session credentials. */
|
||||
export function requestReleaseAsset(
|
||||
url: URL, signal: AbortSignal, source: ReleaseSource,
|
||||
): Promise<IncomingMessage & Readable> {
|
||||
if (signal.aborted) return Promise.reject(new FeedUnreachableError('The release download timed out.'));
|
||||
if (!isReleaseAsset(url.href, source)) {
|
||||
return Promise.reject(new FeedUnreachableError('The release asset URL is not allowed.'));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' });
|
||||
request.setHeader('User-Agent', UPDATE_USER_AGENT);
|
||||
const cleanup = (): void => signal.removeEventListener('abort', abort);
|
||||
const fail = (error: FeedUnreachableError): void => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
request.abort();
|
||||
};
|
||||
const abort = (): void => fail(new FeedUnreachableError('The release download timed out.'));
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
|
||||
request.once('error', (error) => {
|
||||
cleanup();
|
||||
reject(new FeedUnreachableError('The release asset could not be downloaded.', { cause: error }));
|
||||
});
|
||||
request.on('redirect', (_status, _method, destination) => {
|
||||
if (isReleaseAsset(destination, source)) request.followRedirect();
|
||||
else fail(new FeedUnreachableError('The release asset redirected to a disallowed URL.'));
|
||||
});
|
||||
request.once('response', (response) => {
|
||||
if (response.statusCode !== 200) {
|
||||
fail(new FeedUnreachableError(`The update source answered HTTP ${response.statusCode} for a release asset.`));
|
||||
return;
|
||||
}
|
||||
const stream = response as IncomingMessage & Readable;
|
||||
stream.once('end', cleanup);
|
||||
stream.once('close', cleanup);
|
||||
resolve(stream);
|
||||
});
|
||||
request.end();
|
||||
});
|
||||
}
|
||||
|
||||
export async function* releaseAssetChunks(response: Readable): AsyncGenerator<Buffer> {
|
||||
try {
|
||||
for await (const chunk of response) yield chunk as Buffer;
|
||||
} catch (error) {
|
||||
throw new FeedUnreachableError('The release asset download was interrupted.', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
export async function readReleaseAsset(
|
||||
url: URL, limit: number, signal: AbortSignal, source: ReleaseSource,
|
||||
): Promise<Uint8Array> {
|
||||
const response = await requestReleaseAsset(url, signal, source);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of releaseAssetChunks(response)) {
|
||||
size += chunk.length;
|
||||
if (size > limit) throw new PatchPackError('size', 'the release asset is larger than expected');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
@@ -1,71 +1,135 @@
|
||||
/**
|
||||
* The launcher and adaptation pack channels share GitHub's public Releases list.
|
||||
* Requests send no account, no cookie and nothing about the player.
|
||||
* The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list.
|
||||
* The project repository is tried first, with an optional player-configured fallback.
|
||||
*/
|
||||
import { net } from 'electron';
|
||||
import {
|
||||
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
|
||||
} from '@wto/patcher';
|
||||
import { z } from 'zod';
|
||||
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||
import { releaseRepositoryUrl } from '@shared/update-source.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
|
||||
|
||||
export interface ReleaseSource {
|
||||
readonly feed: URL;
|
||||
readonly githubDownloads: URL | null;
|
||||
}
|
||||
|
||||
export interface PortableReleaseAssets {
|
||||
readonly archive: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
}
|
||||
|
||||
export interface LauncherRelease {
|
||||
readonly source: ReleaseSource;
|
||||
readonly version: string;
|
||||
readonly notes: string;
|
||||
readonly installer: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
readonly portable?: PortableReleaseAssets;
|
||||
}
|
||||
|
||||
export interface PackReleaseFiles {
|
||||
readonly source: ReleaseSource;
|
||||
readonly version: string;
|
||||
readonly publishedAt: string | null;
|
||||
readonly zipUrl: string;
|
||||
readonly signatureUrl: string;
|
||||
readonly manifestUrl: string;
|
||||
readonly zipUrl: URL;
|
||||
readonly signatureUrl: URL;
|
||||
readonly manifestUrl: URL;
|
||||
}
|
||||
|
||||
interface ReleaseCandidates {
|
||||
launcher: LauncherRelease | null;
|
||||
pack: PackReleaseFiles | null;
|
||||
interface ReleaseByChannel {
|
||||
launcher: LauncherRelease;
|
||||
pack: PackReleaseFiles;
|
||||
}
|
||||
|
||||
type ReleaseChannel = keyof ReleaseCandidates;
|
||||
type ReleaseChannel = keyof ReleaseByChannel;
|
||||
type ReleaseVersions = { [Channel in ReleaseChannel]: Map<string, ReleaseByChannel[Channel]> };
|
||||
|
||||
interface ReleaseListing {
|
||||
readonly candidates: ReleaseCandidates;
|
||||
readonly versions: ReleaseVersions;
|
||||
readonly incomplete: Readonly<Partial<Record<ReleaseChannel, string>>>;
|
||||
readonly pageLimit: number | null;
|
||||
}
|
||||
|
||||
/** Thrown when GitHub cannot be reached or answers with an error. */
|
||||
export class FeedUnreachableError extends Error {
|
||||
override readonly name = 'FeedUnreachableError';
|
||||
}
|
||||
|
||||
/** Thrown when the list ends at the configured page limit without finding a newer release. */
|
||||
export class ReleasePageLimitError extends Error {
|
||||
override readonly name = 'ReleasePageLimitError';
|
||||
}
|
||||
|
||||
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() });
|
||||
const LauncherReleaseEntry = z.object({
|
||||
draft: z.literal(false),
|
||||
prerelease: z.literal(false),
|
||||
assets: z.array(z.object({ name: z.string() })),
|
||||
assets: z.array(ReleaseAsset),
|
||||
body: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
let listing: Promise<ReleaseListing> | null = null;
|
||||
const listings = new Map<string, Promise<ReleaseListing>>();
|
||||
|
||||
function releaseSource(repository: URL): ReleaseSource {
|
||||
const githubPath = repository.origin === 'https://github.com' ? repository.pathname
|
||||
: repository.origin === 'https://api.github.com'
|
||||
? /^\/repos(\/[\w.-]+\/[\w.-]+)(?:\/releases)?$/.exec(repository.pathname)?.[1]
|
||||
: null;
|
||||
if (githubPath) {
|
||||
return {
|
||||
feed: new URL(`https://api.github.com/repos${githubPath}/releases`),
|
||||
githubDownloads: new URL(`https://github.com${githubPath}/releases/download/`),
|
||||
};
|
||||
}
|
||||
const feed = new URL(repository);
|
||||
if (!feed.pathname.endsWith('/releases')) feed.pathname = `${feed.pathname.replace(/\/$/, '')}/releases`;
|
||||
return { feed, githubDownloads: null };
|
||||
}
|
||||
|
||||
export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean {
|
||||
return a.githubDownloads && b.githubDownloads
|
||||
? a.feed.href.toLowerCase() === b.feed.href.toLowerCase()
|
||||
: a.feed.href === b.feed.href;
|
||||
}
|
||||
|
||||
/** Keep a check or download on its preferred source until that source becomes unavailable. */
|
||||
export async function withReleaseSources<T>(
|
||||
read: (source: ReleaseSource) => Promise<T>, preferred?: ReleaseSource,
|
||||
): Promise<T> {
|
||||
const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`));
|
||||
const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl);
|
||||
const mirror = repository ? releaseSource(repository) : null;
|
||||
if (!mirror || sameReleaseSource(primary, mirror)) return read(primary);
|
||||
const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror];
|
||||
try {
|
||||
return await read(first);
|
||||
} catch (error) {
|
||||
if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error;
|
||||
console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`);
|
||||
return read(second);
|
||||
}
|
||||
}
|
||||
|
||||
function listingFor(source: ReleaseSource): Promise<ReleaseListing> {
|
||||
const key = source.feed.href;
|
||||
const existing = listings.get(key);
|
||||
if (existing) return existing;
|
||||
const pending = readProjectReleases(source).finally(() => { listings.delete(key); });
|
||||
listings.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Share the in-flight scan when the launcher checks both release channels at startup. */
|
||||
export async function newestProjectRelease<Channel extends ReleaseChannel>(
|
||||
channel: Channel, installedVersion: string | null,
|
||||
): Promise<ReleaseCandidates[Channel]> {
|
||||
listing ??= readProjectReleases().finally(() => { listing = null; });
|
||||
const { candidates, incomplete, pageLimit } = await listing;
|
||||
const candidate = candidates[channel];
|
||||
channel: Channel, installedVersion: string | null, source: ReleaseSource,
|
||||
): Promise<ReleaseByChannel[Channel] | null> {
|
||||
const { versions, incomplete, pageLimit } = await listingFor(source);
|
||||
const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions;
|
||||
let candidate: ReleaseByChannel[Channel] | null = null;
|
||||
for (const release of versions[channel].values()) {
|
||||
if (!candidate || compare(release.version, candidate.version) > 0) candidate = release;
|
||||
}
|
||||
if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate;
|
||||
if (pageLimit !== null) {
|
||||
throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`);
|
||||
@@ -77,29 +141,52 @@ export async function newestProjectRelease<Channel extends ReleaseChannel>(
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function readProjectReleases(): Promise<ReleaseListing> {
|
||||
/** The fallback must supply the same release the player selected. */
|
||||
export async function projectReleaseVersion<Channel extends ReleaseChannel>(
|
||||
channel: Channel, version: string, source: ReleaseSource,
|
||||
): Promise<ReleaseByChannel[Channel]> {
|
||||
const release = (await listingFor(source)).versions[channel].get(version);
|
||||
if (!release) throw new FeedUnreachableError(`This update source does not have the files for ${version}.`);
|
||||
return release;
|
||||
}
|
||||
|
||||
async function readProjectReleases(source: ReleaseSource): Promise<ReleaseListing> {
|
||||
const tuning = patchPackTuning();
|
||||
const candidates: ReleaseCandidates = { launcher: null, pack: null };
|
||||
const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() };
|
||||
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
|
||||
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasePageSize}`;
|
||||
const url = new URL(source.feed);
|
||||
url.searchParams.set('per_page', String(tuning.releasePageSize));
|
||||
const headers = {
|
||||
Accept: 'application/json', 'User-Agent': UPDATE_USER_AGENT,
|
||||
...(source.githubDownloads ? GITHUB_HEADERS : {}),
|
||||
};
|
||||
for (let page = 1; page <= tuning.maxReleasePages; page += 1) {
|
||||
const response = await request(`${url}&page=${page}`, HEADERS, tuning.requestTimeoutMs);
|
||||
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for release page ${page}`);
|
||||
const releases: unknown = await response.json();
|
||||
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
|
||||
collectReleases(releases, candidates, incomplete, tuning.repository);
|
||||
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
|
||||
url.searchParams.set('page', String(page));
|
||||
const result = await requestReleasePage(url, headers, tuning.requestTimeoutMs);
|
||||
collectReleases(result.releases, versions, incomplete, source);
|
||||
// GitHub does not sort release pages by tag version.
|
||||
if (!hasNextPage) {
|
||||
return { candidates, incomplete, pageLimit: null };
|
||||
}
|
||||
if (!result.hasNextPage) return { versions, incomplete, pageLimit: null };
|
||||
}
|
||||
console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`);
|
||||
return { candidates, incomplete, pageLimit: tuning.maxReleasePages };
|
||||
return { versions, incomplete, pageLimit: tuning.maxReleasePages };
|
||||
}
|
||||
|
||||
async function requestReleasePage(url: URL, headers: Record<string, string>, timeoutMs: number) {
|
||||
try {
|
||||
const response = await net.fetch(url.href, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
|
||||
if (!response.ok) throw new FeedUnreachableError(`The update source answered HTTP ${response.status} for a release page.`);
|
||||
const releases: unknown = await response.json();
|
||||
if (!Array.isArray(releases)) throw new FeedUnreachableError('The update source did not return a release list.');
|
||||
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
|
||||
return { releases: releases as readonly unknown[], hasNextPage };
|
||||
} catch (error) {
|
||||
if (error instanceof FeedUnreachableError) throw error;
|
||||
throw new FeedUnreachableError('The update source could not be read.', { cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
function collectReleases(
|
||||
entries: readonly unknown[], candidates: ReleaseCandidates, incomplete: Partial<Record<ReleaseChannel, string>>, repository: string,
|
||||
entries: readonly unknown[], versions: ReleaseVersions, incomplete: Partial<Record<ReleaseChannel, string>>, source: ReleaseSource,
|
||||
): void {
|
||||
for (const entry of entries) {
|
||||
if (typeof entry !== 'object' || entry === null) continue;
|
||||
@@ -111,78 +198,72 @@ function collectReleases(
|
||||
if (release['prerelease'] === true) continue;
|
||||
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
|
||||
if (!version.success) continue;
|
||||
const launcher = launcherRelease(release, version.data, repository);
|
||||
if (!launcher) {
|
||||
const missing = incomplete.launcher;
|
||||
if (!missing || compareAppVersions(version.data, missing) > 0) incomplete.launcher = version.data;
|
||||
} else if (!candidates.launcher || compareAppVersions(launcher.version, candidates.launcher.version) > 0) {
|
||||
candidates.launcher = launcher;
|
||||
}
|
||||
const launcher = launcherRelease(release, version.data, source);
|
||||
if (launcher) versions.launcher.set(launcher.version, launcher);
|
||||
else if (!incomplete.launcher || compareAppVersions(version.data, incomplete.launcher) > 0) incomplete.launcher = version.data;
|
||||
continue;
|
||||
}
|
||||
|
||||
const version = packVersionOfTag(tag);
|
||||
if (!version) continue;
|
||||
const pack = packRelease(release, version);
|
||||
if (!pack) {
|
||||
const missing = incomplete.pack;
|
||||
if (!missing || comparePackVersions(version, missing) > 0) incomplete.pack = version;
|
||||
} else if (!candidates.pack || comparePackVersions(pack.version, candidates.pack.version) > 0) {
|
||||
candidates.pack = pack;
|
||||
}
|
||||
const pack = packRelease(release, version, tag, source);
|
||||
if (pack) versions.pack.set(pack.version, pack);
|
||||
else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version;
|
||||
}
|
||||
}
|
||||
|
||||
function launcherRelease(entry: Record<string, unknown>, version: string, repository: string): LauncherRelease | null {
|
||||
function assetUrls(assets: readonly unknown[], tag: string, source: ReleaseSource): Map<string, URL> {
|
||||
const urls = new Map<string, URL>();
|
||||
for (const asset of assets) {
|
||||
const parsed = ReleaseAsset.safeParse(asset);
|
||||
if (!parsed.success) continue;
|
||||
const { name, browser_download_url: download } = parsed.data;
|
||||
if (source.githubDownloads) {
|
||||
urls.set(name, new URL(`${tag}/${encodeURIComponent(name)}`, source.githubDownloads));
|
||||
continue;
|
||||
}
|
||||
const url = download ? URL.parse(download, source.feed.href) : null;
|
||||
if (url?.protocol === 'https:' && !url.username && !url.password) urls.set(name, url);
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
function launcherRelease(entry: Record<string, unknown>, version: string, source: ReleaseSource): LauncherRelease | null {
|
||||
const parsed = LauncherReleaseEntry.safeParse(entry);
|
||||
if (!parsed.success) return null;
|
||||
const { assets, body } = parsed.data;
|
||||
const names = launcherReleaseFiles(version);
|
||||
const present = new Set(assets.map(({ name }) => name));
|
||||
if (!Object.values(names).every((name) => present.has(name))) return null;
|
||||
const directory = `https://github.com/${repository}/releases/download/v${version}/`;
|
||||
const portableNames = portableLauncherReleaseFiles(version);
|
||||
const urls = assetUrls(assets, `v${version}`, source);
|
||||
const installer = urls.get(names.installer);
|
||||
const manifest = urls.get(names.manifest);
|
||||
const signature = urls.get(names.signature);
|
||||
if (!installer || !manifest || !signature) return null;
|
||||
const portableArchive = urls.get(portableNames.archive);
|
||||
const portableManifest = urls.get(portableNames.manifest);
|
||||
const portableSignature = urls.get(portableNames.signature);
|
||||
const portable = portableArchive && portableManifest && portableSignature
|
||||
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
|
||||
: undefined;
|
||||
return {
|
||||
source,
|
||||
version,
|
||||
notes: body?.trim().slice(0, 1600) ?? '',
|
||||
installer: new URL(names.installer, directory),
|
||||
manifest: new URL(names.manifest, directory),
|
||||
signature: new URL(names.signature, directory),
|
||||
installer,
|
||||
manifest,
|
||||
signature,
|
||||
...(portable ? { portable } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function packRelease(release: Record<string, unknown>, version: string): PackReleaseFiles | null {
|
||||
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
|
||||
if (!Array.isArray(release['assets'])) return null;
|
||||
const urls = new Map<string, string>();
|
||||
for (const asset of release['assets'] as unknown[]) {
|
||||
if (typeof asset !== 'object' || asset === null) continue;
|
||||
const { name, browser_download_url: download } = asset as Record<string, unknown>;
|
||||
if (typeof name === 'string' && typeof download === 'string' && download.startsWith('https://')) urls.set(name, download);
|
||||
}
|
||||
const urls = assetUrls(release['assets'], tag, source);
|
||||
const names = packFileNames(version);
|
||||
const zipUrl = urls.get(names.zip);
|
||||
const signatureUrl = urls.get(names.signature);
|
||||
const manifestUrl = urls.get(names.manifest);
|
||||
if (!zipUrl || !signatureUrl || !manifestUrl) return null;
|
||||
const publishedAt = typeof release['published_at'] === 'string' ? release['published_at'] : null;
|
||||
return { version, publishedAt, zipUrl, signatureUrl, manifestUrl };
|
||||
}
|
||||
|
||||
/** Download a release file, refusing anything larger than `maxBytes`. */
|
||||
export async function downloadReleaseFile(url: string, maxBytes: number): Promise<Uint8Array> {
|
||||
const tuning = patchPackTuning();
|
||||
const response = await request(url, { 'User-Agent': HEADERS['User-Agent'] }, tuning.requestTimeoutMs);
|
||||
if (!response.ok) throw new FeedUnreachableError(`HTTP ${response.status} for ${url}`);
|
||||
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||
if (declared > maxBytes) throw new PatchPackError('size', `${url} is ${declared} bytes, more than ${maxBytes}`);
|
||||
const content = new Uint8Array(await response.arrayBuffer());
|
||||
if (content.length > maxBytes) throw new PatchPackError('size', `${url} is more than ${maxBytes} bytes`);
|
||||
return content;
|
||||
}
|
||||
|
||||
async function request(url: string, headers: Record<string, string>, timeoutMs: number): Promise<Response> {
|
||||
try {
|
||||
return await net.fetch(url, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
|
||||
} catch (error) {
|
||||
throw new FeedUnreachableError(`${url}: ${(error as Error).message}`);
|
||||
}
|
||||
return { source, version, publishedAt, zipUrl, signatureUrl, manifestUrl };
|
||||
}
|
||||
@@ -490,6 +490,9 @@
|
||||
"appUpdatesToggle": "Check for launcher updates at start",
|
||||
"patchPacks": "Adaptation pack updates",
|
||||
"patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.",
|
||||
"updateMirror": "Update mirror repository",
|
||||
"updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.",
|
||||
"updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.",
|
||||
"patchPacksToggle": "Check for a new adaptation pack at start",
|
||||
"windowClose": "When closing the window",
|
||||
"windowQuit": "Quit launcher",
|
||||
@@ -572,7 +575,7 @@
|
||||
"downloaded": "Adaptation pack {{version}}",
|
||||
"useBundled": "Go back to the included patches",
|
||||
"check": "Check for updates",
|
||||
"checkHint": "Looks for a new adaptation pack on GitHub.",
|
||||
"checkHint": "Checks for a new adaptation pack.",
|
||||
"checkButton": "Check",
|
||||
"checking": "Checking…",
|
||||
"applying": "Downloading and verifying the adaptation pack…",
|
||||
@@ -584,7 +587,7 @@
|
||||
"needsAppUpdate": "Adaptation pack {{version}} needs offline version {{app}} or newer. Update the offline version first.",
|
||||
"checkFailed": {
|
||||
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
|
||||
"network": "GitHub could not be reached. Try again later.",
|
||||
"network": "The update source could not be reached. Try again later.",
|
||||
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
|
||||
"contents": "The released adaptation pack is incomplete or malformed.",
|
||||
"signature": "The adaptation pack's signature is wrong. It was refused.",
|
||||
@@ -592,7 +595,7 @@
|
||||
},
|
||||
"applyFailed": {
|
||||
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
|
||||
"network": "The download failed: GitHub could not be reached. Try again later.",
|
||||
"network": "Could not reach the update source to download the adaptation pack. Try again later.",
|
||||
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
|
||||
"contents": "The adaptation pack is incomplete or malformed. It is not in use.",
|
||||
"signature": "The adaptation pack's signature is wrong. It was refused and is not in use.",
|
||||
@@ -612,7 +615,7 @@
|
||||
"install": "Quit and install",
|
||||
"installing": "Opening the installer…",
|
||||
"errors": {
|
||||
"network": "GitHub Releases could not be reached.",
|
||||
"network": "The update source could not be reached.",
|
||||
"page_limit": "Could not confirm whether a newer version is available.",
|
||||
"contents": "The launcher release information is invalid.",
|
||||
"signature": "The launcher update signature could not be verified.",
|
||||
@@ -703,12 +706,14 @@
|
||||
"launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.",
|
||||
"launch_location": "The client, stock backup, or data folder location is invalid.",
|
||||
"launch_stock_version": "The stock backup and client versions do not match.",
|
||||
"launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.",
|
||||
"launch_build_failed": "The game files could not be generated.",
|
||||
"launch_build_unavailable": "The build found unavailable patches that require review.",
|
||||
"launch_port_busy": "The local server port is already in use.",
|
||||
"launch_server_failed": "The local server could not be started. See the launcher log.",
|
||||
"launch_server_exited": "The local server is unavailable.",
|
||||
"launch_game_failed": "The game process could not start. See the launcher log.",
|
||||
"launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.",
|
||||
"settings_write_failed": "The settings could not be saved.",
|
||||
"folder_unreadable": "The folder cannot be read: {{path}}",
|
||||
"not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}",
|
||||
|
||||
@@ -490,6 +490,9 @@
|
||||
"appUpdatesToggle": "启动时检查本体更新",
|
||||
"patchPacks": "适配包更新",
|
||||
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。",
|
||||
"updateMirror": "备用更新仓库",
|
||||
"updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。",
|
||||
"updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。",
|
||||
"patchPacksToggle": "启动时检查有没有新的适配包",
|
||||
"windowClose": "关闭窗口时",
|
||||
"windowQuit": "退出启动器",
|
||||
@@ -572,7 +575,7 @@
|
||||
"downloaded": "适配包 {{version}}",
|
||||
"useBundled": "改回启动器自带",
|
||||
"check": "检查更新",
|
||||
"checkHint": "在 GitHub 上查找新的适配包。",
|
||||
"checkHint": "检查是否有新的适配包。",
|
||||
"checkButton": "检查",
|
||||
"checking": "正在检查…",
|
||||
"applying": "正在下载并校验适配包…",
|
||||
@@ -584,7 +587,7 @@
|
||||
"needsAppUpdate": "适配包 {{version}} 需要离线版 {{app}} 或更新的版本,请先更新离线版。",
|
||||
"checkFailed": {
|
||||
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
|
||||
"network": "连不上 GitHub,请稍后再试。",
|
||||
"network": "无法连接更新源,请稍后再试。",
|
||||
"page_limit": "无法确认是否有新的适配包。",
|
||||
"contents": "发布的适配包信息不完整或格式不对。",
|
||||
"signature": "适配包的签名不对,已拒绝。",
|
||||
@@ -592,7 +595,7 @@
|
||||
},
|
||||
"applyFailed": {
|
||||
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
|
||||
"network": "下载失败:连不上 GitHub,请稍后再试。",
|
||||
"network": "无法连接更新源来下载适配包,请稍后再试。",
|
||||
"page_limit": "无法确认是否有新的适配包。",
|
||||
"contents": "适配包内容不完整或格式不对,没有启用。",
|
||||
"signature": "适配包的签名不对,已拒绝,没有启用。",
|
||||
@@ -612,7 +615,7 @@
|
||||
"install": "退出并安装",
|
||||
"installing": "正在打开安装包…",
|
||||
"errors": {
|
||||
"network": "暂时无法访问 GitHub 发布页。",
|
||||
"network": "暂时无法访问更新源。",
|
||||
"page_limit": "无法确认是否有新版本。",
|
||||
"contents": "本体更新的发布信息无效。",
|
||||
"signature": "本体更新签名校验失败。",
|
||||
@@ -703,12 +706,14 @@
|
||||
"launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。",
|
||||
"launch_location": "客户端、原版文件备份或数据目录的位置无效。",
|
||||
"launch_stock_version": "原版文件备份的版本与客户端不一致。",
|
||||
"launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。",
|
||||
"launch_build_failed": "无法生成游戏文件。",
|
||||
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
|
||||
"launch_port_busy": "本地服务器端口已被占用。",
|
||||
"launch_server_failed": "无法启动本地服务器。请查看启动器日志。",
|
||||
"launch_server_exited": "本地服务器不可用。",
|
||||
"launch_game_failed": "游戏进程无法启动。请查看启动器日志。",
|
||||
"launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。",
|
||||
"settings_write_failed": "无法保存设置。",
|
||||
"folder_unreadable": "无法读取文件夹:{{path}}",
|
||||
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import { formatExitCode, type LaunchState } from '@shared/schemas/launch.ts';
|
||||
import type { BarModel } from '../../shell/bar-model.ts';
|
||||
import { missingFeatures } from '../copies/missing-features.ts';
|
||||
|
||||
@@ -24,8 +24,11 @@ export function homeBar(
|
||||
const starting = { label: t('launch.starting'), disabled: true };
|
||||
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
|
||||
const { gameExit } = state;
|
||||
const exitCodeLabel = gameExit
|
||||
? (gameExit.code !== null ? formatExitCode(gameExit.code) : (gameExit.signal ?? t('launch.exitCodeUnknown')))
|
||||
: undefined;
|
||||
const exitDetail = gameExit && gameExit.code !== 0
|
||||
? t('launch.exitDetail', { code: gameExit.code ?? gameExit.signal ?? t('launch.exitCodeUnknown'), path: gameExit.logFolder })
|
||||
? t('launch.exitDetail', { code: exitCodeLabel, path: gameExit.logFolder })
|
||||
: undefined;
|
||||
switch (state.phase) {
|
||||
case 'checking':
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { BACKGROUND_RANDOM, type BackgroundPicture } from '@shared/schemas/background.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { UpdateMirrorUrlSchema, type Settings } from '@shared/schemas/settings.ts';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import { ipcInvoke } from '../../ipc.ts';
|
||||
@@ -71,6 +71,32 @@ export function GeneralSettings({ settings, appUpdatesSupported, pictures, onErr
|
||||
{t('settings.patchPacksToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
<Row label={t('settings.updateMirror')} hint={t('settings.updateMirrorHint')}>
|
||||
<input
|
||||
className="select"
|
||||
aria-label={t('settings.updateMirror')}
|
||||
type="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder="https://…"
|
||||
defaultValue={settings.updateMirrorUrl}
|
||||
key={settings.updateMirrorUrl}
|
||||
onChange={(event) => event.currentTarget.setCustomValidity('')}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') event.currentTarget.blur();
|
||||
}}
|
||||
onBlur={(event) => {
|
||||
const input = event.currentTarget;
|
||||
const parsed = UpdateMirrorUrlSchema.safeParse(input.value);
|
||||
if (!parsed.success) {
|
||||
input.setCustomValidity(t('settings.updateMirrorInvalid'));
|
||||
input.reportValidity();
|
||||
return;
|
||||
}
|
||||
if (parsed.data !== settings.updateMirrorUrl) update({ updateMirrorUrl: parsed.data });
|
||||
}}
|
||||
/>
|
||||
</Row>
|
||||
<h3 className="section-title section-title-spaced">{t('background.title')}</h3>
|
||||
<p className="small">{t('background.hint')}</p>
|
||||
{pictures.length === 0 ? (
|
||||
|
||||
@@ -52,9 +52,11 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) =>
|
||||
}, [checkOnStart, checkNow]);
|
||||
|
||||
const apply = useCallback((): void => {
|
||||
const version = check?.status === 'available' ? check.latest?.version : undefined;
|
||||
if (!version) return;
|
||||
setBusy('applying');
|
||||
setApplyFailure(null);
|
||||
ipcInvoke('patches:apply')
|
||||
ipcInvoke('patches:apply', { version })
|
||||
.then((result) => {
|
||||
if (!result.ok) {
|
||||
setApplyFailure(result.problem);
|
||||
@@ -65,7 +67,7 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) =>
|
||||
})
|
||||
.catch(onError)
|
||||
.finally(() => setBusy(null));
|
||||
}, [onError]);
|
||||
}, [check, onError]);
|
||||
|
||||
const useBundled = useCallback((): void => {
|
||||
setBusy('reverting');
|
||||
|
||||
@@ -59,12 +59,16 @@ export const APP_ERROR_CODES = [
|
||||
'launch_steam_confirmation_required',
|
||||
'launch_location',
|
||||
'launch_stock_version',
|
||||
/** The wtoffline/stock backup executable is missing or unreadable before launch. */
|
||||
'launch_stock_missing',
|
||||
'launch_build_failed',
|
||||
'launch_build_unavailable',
|
||||
'launch_port_busy',
|
||||
'launch_server_failed',
|
||||
'launch_server_exited',
|
||||
'launch_game_failed',
|
||||
/** Core files built for the launch (aces.exe, wto_ws.dll, wto_ws.cfg) are missing or unreadable. */
|
||||
'launch_game_files_missing',
|
||||
/** A folder the player chose does not exist or cannot be read (params: path). */
|
||||
'folder_unreadable',
|
||||
/** The chosen folder lacks the files of a War Thunder installation (params: path). */
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from '../schemas/install.ts';
|
||||
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
|
||||
import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts';
|
||||
import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts';
|
||||
import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts';
|
||||
import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts';
|
||||
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
|
||||
@@ -282,13 +282,13 @@ export const ipcContract = {
|
||||
output: ActivePatchSetSchema,
|
||||
},
|
||||
'patches:check': {
|
||||
/** Asks GitHub for the newest adaptation pack. */
|
||||
/** Checks for a newer adaptation pack. */
|
||||
input: z.void(),
|
||||
output: PackCheckSchema,
|
||||
},
|
||||
'patches:apply': {
|
||||
/** Downloads, verifies and activates the newest pack; the window asks the player first. */
|
||||
input: z.void(),
|
||||
/** Downloads, verifies and activates the pack version selected by the player. */
|
||||
input: z.object({ version: PackReleaseSchema.shape.version }),
|
||||
output: PackApplyResultSchema,
|
||||
},
|
||||
'patches:useBundled': {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[
|
||||
"-forcestart",
|
||||
"-skip_pkg_validation",
|
||||
"-nobeac",
|
||||
"-crashpad-disable-upload",
|
||||
"--nosteam"
|
||||
|
||||
@@ -9,6 +9,11 @@ export function launcherReleaseFiles(version: string) {
|
||||
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export function portableLauncherReleaseFiles(version: string) {
|
||||
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64-portable`;
|
||||
return { archive: `${base}.zip`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export const LauncherReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-release'),
|
||||
format: z.literal(1),
|
||||
@@ -19,6 +24,16 @@ export const LauncherReleaseManifest = z.strictObject({
|
||||
});
|
||||
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
||||
|
||||
export const PortableReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-portable-release'),
|
||||
format: z.literal(1),
|
||||
version: AppReleaseVersionSchema,
|
||||
platform: z.literal('win32-x64'),
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type PortableReleaseManifest = z.output<typeof PortableReleaseManifest>;
|
||||
|
||||
const AppUpdateReleaseSchema = z.object({
|
||||
version: AppReleaseVersionSchema,
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
|
||||
@@ -9,6 +9,12 @@ const GameExitSchema = z.object({
|
||||
|
||||
export type GameExit = z.output<typeof GameExitSchema>;
|
||||
|
||||
/** Append the unsigned 32-bit hex form for Windows NTSTATUS/HRESULT exit codes. */
|
||||
export function formatExitCode(code: number): string {
|
||||
if (code >= 0 && code <= 0xffff) return String(code);
|
||||
return `${code} (0x${(code >>> 0).toString(16).toUpperCase().padStart(8, '0')})`;
|
||||
}
|
||||
|
||||
export const LaunchStateSchema = z.object({
|
||||
phase: z.enum([
|
||||
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
import { LANGUAGE_CHOICES } from '../languages.ts';
|
||||
import { parseLaunchArguments } from '../launch-arguments.ts';
|
||||
import { releaseRepositoryUrl } from '../update-source.ts';
|
||||
import { BACKGROUND_RANDOM, BackgroundChoiceSchema } from './background.ts';
|
||||
|
||||
const LanguageChoiceSchema = z.enum(LANGUAGE_CHOICES);
|
||||
@@ -11,6 +12,7 @@ const PortModeSchema = z.enum(['auto', 'fixed']);
|
||||
const PortSchema = z.number().int().min(1).max(65535);
|
||||
export const LAUNCH_ARGUMENTS_LIMIT = 4000;
|
||||
const LaunchArgumentsSchema = z.string().max(LAUNCH_ARGUMENTS_LIMIT).refine((value) => parseLaunchArguments(value) !== null);
|
||||
export const UpdateMirrorUrlSchema = z.string().trim().refine((value) => value === '' || releaseRepositoryUrl(value) !== null);
|
||||
|
||||
/** The launcher's own settings (not the game's, not the local service's tuning). */
|
||||
export const SettingsSchema = z.object({
|
||||
@@ -19,9 +21,10 @@ export const SettingsSchema = z.object({
|
||||
background: BackgroundChoiceSchema.default(BACKGROUND_RANDOM),
|
||||
/** Fetch wallpapers from the game website's public gallery. */
|
||||
officialWallpapers: z.boolean().default(true),
|
||||
/** Ask GitHub for a newer adaptation pack when the launcher starts. */
|
||||
/** Check for a newer adaptation pack when the launcher starts. */
|
||||
checkPatchPacksOnStart: z.boolean().default(true),
|
||||
checkLauncherUpdatesOnStart: z.boolean().default(true),
|
||||
updateMirrorUrl: UpdateMirrorUrlSchema.default(''),
|
||||
windowClose: WindowCloseSchema.default('quit'),
|
||||
afterGameStarts: AfterGameStartsSchema.default('minimize'),
|
||||
autoSaveBackups: z.boolean().default(true),
|
||||
@@ -43,6 +46,7 @@ export const SettingsPatchSchema = z.object({
|
||||
officialWallpapers: z.boolean().optional(),
|
||||
checkPatchPacksOnStart: z.boolean().optional(),
|
||||
checkLauncherUpdatesOnStart: z.boolean().optional(),
|
||||
updateMirrorUrl: UpdateMirrorUrlSchema.optional(),
|
||||
windowClose: WindowCloseSchema.optional(),
|
||||
afterGameStarts: AfterGameStartsSchema.optional(),
|
||||
autoSaveBackups: z.boolean().optional(),
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Parse a repository URL that can be used with the release update protocol. */
|
||||
export function releaseRepositoryUrl(value: string): URL | null {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) return null;
|
||||
url.pathname = url.pathname.replace(/\/+$/, '').replace(/\.git$/, '') || '/';
|
||||
if (url.origin === 'https://github.com' && !/^\/[\w.-]+\/[\w.-]+$/.test(url.pathname)) return null;
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,20 @@ static HMODULE g_ws2;
|
||||
int hook_export(const char *name, void *replacement, void **original)
|
||||
{
|
||||
void *target = (void *)GetProcAddress(g_ws2, name);
|
||||
MH_STATUS status;
|
||||
if (target == NULL) {
|
||||
log_line("hook %s: not exported by ws2_32.dll", name);
|
||||
return 0;
|
||||
}
|
||||
if (MH_CreateHook(target, replacement, original) != MH_OK || MH_EnableHook(target) != MH_OK) {
|
||||
log_line("hook %s: failed", name);
|
||||
status = MH_CreateHook(target, replacement, original);
|
||||
if (status != MH_OK) {
|
||||
log_line("hook %s: MH_CreateHook failed (%s)", name, MH_StatusToString(status));
|
||||
return 0;
|
||||
}
|
||||
status = MH_QueueEnableHook(target);
|
||||
if (status != MH_OK) {
|
||||
log_line("hook %s: MH_QueueEnableHook failed (%s)", name, MH_StatusToString(status));
|
||||
MH_RemoveHook(target);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
@@ -33,12 +41,26 @@ int hook_export(const char *name, void *replacement, void **original)
|
||||
|
||||
static int install(void)
|
||||
{
|
||||
MH_STATUS status;
|
||||
/* ws2_32.dll is already loaded: this DLL links against it. */
|
||||
g_ws2 = GetModuleHandleW(L"ws2_32.dll");
|
||||
if (g_ws2 == NULL || MH_Initialize() != MH_OK)
|
||||
if (g_ws2 == NULL) {
|
||||
log_line("wto_ws: ws2_32.dll module handle unavailable");
|
||||
return 0;
|
||||
}
|
||||
status = MH_Initialize();
|
||||
if (status != MH_OK) {
|
||||
log_line("wto_ws: MH_Initialize failed (%s)", MH_StatusToString(status));
|
||||
return 0;
|
||||
}
|
||||
if (!install_resolver_hooks() || !install_connection_hooks())
|
||||
return 0;
|
||||
/* Enable all mandatory network hooks in one thread-freeze pass before touching LocalMP hooks. */
|
||||
status = MH_ApplyQueued();
|
||||
if (status != MH_OK) {
|
||||
log_line("wto_ws: MH_ApplyQueued for ws2_32 failed (%s)", MH_StatusToString(status));
|
||||
return 0;
|
||||
}
|
||||
install_local_mp_hooks();
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -125,15 +125,12 @@ static uint8_t __fastcall hook_mp_construct_local(uint8_t *mp, void *mis, void *
|
||||
|
||||
int install_local_mp_action_hooks(void)
|
||||
{
|
||||
uint8_t *p_construct = g_lmp.mp_construct_local;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "mp_construct_local", g_lmp.mp_construct_local, (void *)&hook_mp_construct_local, (void **)&orig_mp_construct_local },
|
||||
};
|
||||
|
||||
fn_mp_init_chat = (MpInitChatFn)g_lmp.mp_init_chat;
|
||||
fn_dagmem_alloc = (DagmemAllocFn)g_lmp.dagmem_alloc;
|
||||
|
||||
if (MH_CreateHook(p_construct, (void *)&hook_mp_construct_local, (void **)&orig_mp_construct_local) != MH_OK ||
|
||||
MH_EnableHook(p_construct) != MH_OK) {
|
||||
log_line("local_mp: failed to install the LocalMP construction hook");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
return local_mp_queue_hooks("local_mp_actions", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "hook_config.h"
|
||||
#include "local_mp_internal.h"
|
||||
#include "local_mp_offsets.h"
|
||||
#include "MinHook.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
@@ -162,10 +163,38 @@ static void use_core_values(void)
|
||||
g_lmp_datablock_get_str = (LmpDataBlockGetStrFn)g_lmp.datablock_get_str;
|
||||
}
|
||||
|
||||
int local_mp_queue_hooks(const char *module, const LocalMpHookSpec *specs, size_t count)
|
||||
{
|
||||
size_t created = 0;
|
||||
|
||||
while (created < count) {
|
||||
MH_STATUS status = MH_CreateHook(specs[created].target, specs[created].detour, specs[created].original);
|
||||
if (status != MH_OK) {
|
||||
log_line("local_mp: %s hook %s MH_CreateHook failed (%s)",
|
||||
module, specs[created].name, MH_StatusToString(status));
|
||||
goto failed;
|
||||
}
|
||||
++created;
|
||||
status = MH_QueueEnableHook(specs[created - 1].target);
|
||||
if (status != MH_OK) {
|
||||
log_line("local_mp: %s hook %s MH_QueueEnableHook failed (%s)",
|
||||
module, specs[created - 1].name, MH_StatusToString(status));
|
||||
goto failed;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
|
||||
failed:
|
||||
while (created != 0)
|
||||
MH_RemoveHook(specs[--created].target);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void install_local_mp_hooks(void)
|
||||
{
|
||||
size_t i;
|
||||
unsigned installed = 0;
|
||||
MH_STATUS status;
|
||||
|
||||
if (!config_native_matches_executable()) {
|
||||
log_line("local_mp: wto_ws.cfg was built for another aces.exe, LocalMP bridge disabled");
|
||||
@@ -184,5 +213,12 @@ void install_local_mp_hooks(void)
|
||||
else
|
||||
log_line("local_mp: %s failed to install its hooks", MODULES[i].name);
|
||||
}
|
||||
if (installed > 0) {
|
||||
status = MH_ApplyQueued();
|
||||
if (status != MH_OK) {
|
||||
log_line("local_mp: MH_ApplyQueued failed (%s), LocalMP hooks not enabled", MH_StatusToString(status));
|
||||
return;
|
||||
}
|
||||
}
|
||||
log_line("local_mp: %u of %u LocalMP modules installed", installed, (unsigned)(sizeof(MODULES) / sizeof(MODULES[0])));
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
/*
|
||||
* Bind the stock barrel and breech HUD notices to the damaged unit on a LocalMP host.
|
||||
* The native damage and firing handlers retain their normal effects.
|
||||
* Bind self damage, avionics failure and hit-parts feedback to the local player on a LocalMP host.
|
||||
* All native damage, avionics failure and firing effects remain unchanged for every unit.
|
||||
*/
|
||||
#include "local_mp_internal.h"
|
||||
#include "local_mp_offsets.h"
|
||||
#include "local_mp_values.h"
|
||||
#include "MinHook.h"
|
||||
#include "hook_config.h"
|
||||
|
||||
typedef uint8_t (__fastcall *BarrelDamageFn)(void *damage, const uint8_t *impact);
|
||||
typedef void (__fastcall *FireUpdateFn)(
|
||||
@@ -13,10 +14,18 @@ typedef void (__fastcall *FireUpdateFn)(
|
||||
typedef void (__fastcall *DeliverHudFn)(
|
||||
int32_t type, int32_t id, int32_t arg3, int32_t arg4, int32_t arg5,
|
||||
float arg6, float arg7, uint8_t arg8);
|
||||
typedef void (__fastcall *DeliverDamageHudFn)(int32_t type, int32_t text_id, int32_t id);
|
||||
typedef void (__fastcall *AvionicsDamageFn)(const uint8_t *component, uint32_t kind);
|
||||
typedef uint64_t (__fastcall *ExitOpticViewFn)(void *camera, int32_t arg2, uint8_t arg3);
|
||||
typedef uint64_t (__fastcall *UnitOnEventFn)(void *unit, const uint8_t *event, void *arg3, void *arg4);
|
||||
typedef void (__fastcall *HitPartsFeedbackFn)(void *hud, const uint8_t *victim, const void *info);
|
||||
typedef const uint8_t *(__fastcall *ControlledUnitFn)(const uint8_t *mplayer);
|
||||
|
||||
/* HUD_MSG_EVENT is registered in the stock hudMessages module. */
|
||||
enum { HUD_MSG_EVENT = 9 };
|
||||
/* HUD message types, registered in the stock hudMessages module. */
|
||||
enum { HUD_MSG_DAMAGE = 4, HUD_MSG_EVENT = 9 };
|
||||
|
||||
/* Diagnostics are bounded so a long battle cannot flood the run log. */
|
||||
enum { SUPPRESSED_LOG_LIMIT = 12 };
|
||||
|
||||
typedef struct DamageNotice {
|
||||
const uint8_t *context;
|
||||
@@ -25,11 +34,77 @@ typedef struct DamageNotice {
|
||||
int32_t id;
|
||||
} DamageNotice;
|
||||
|
||||
/* Both producers deliver synchronously. Keep nested events and simulation threads independent. */
|
||||
/* All hooked producers deliver synchronously; thread-local slots keep nested calls isolated. */
|
||||
static __declspec(thread) const DamageNotice *active_notice;
|
||||
static __declspec(thread) const uint8_t *active_avionics_unit;
|
||||
static __declspec(thread) const uint8_t *active_hit_event;
|
||||
|
||||
static BarrelDamageFn original_barrel_damage;
|
||||
static FireUpdateFn original_fire_update;
|
||||
static DeliverHudFn original_deliver_hud;
|
||||
static DeliverDamageHudFn original_damage_deliver_hud;
|
||||
static AvionicsDamageFn original_avionics_damage;
|
||||
static ExitOpticViewFn original_exit_optic_view;
|
||||
static UnitOnEventFn original_unit_on_event;
|
||||
static HitPartsFeedbackFn original_enqueue_enemy_parts;
|
||||
static HitPartsFeedbackFn original_hit_cam_important;
|
||||
static HitPartsFeedbackFn original_naval_hit_state;
|
||||
|
||||
static int suppressed_avionics_logged;
|
||||
static int suppressed_optic_logged;
|
||||
static int suppressed_parts_logged;
|
||||
|
||||
/* The unit the local player's MPlayer controls, falling back to g_hero when MPlayer is absent. */
|
||||
static const uint8_t *local_controlled_unit(void)
|
||||
{
|
||||
const uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
|
||||
const uint8_t *unit = mplayer != NULL ? (const uint8_t *)((ControlledUnitFn)g_lmp.mplayer_controlled_unit)(mplayer) : NULL;
|
||||
|
||||
if (unit != NULL)
|
||||
return unit;
|
||||
return g_local_mp_hero != NULL ? *g_local_mp_hero : NULL;
|
||||
}
|
||||
|
||||
static int is_local_controlled_unit(const uint8_t *unit)
|
||||
{
|
||||
const uint8_t *controlled;
|
||||
|
||||
if (unit == NULL)
|
||||
return 0;
|
||||
controlled = local_controlled_unit();
|
||||
return controlled != NULL && unit == controlled;
|
||||
}
|
||||
|
||||
static int is_controlled_damage(const DamageNotice *notice)
|
||||
{
|
||||
uintptr_t unit;
|
||||
|
||||
if (notice->context == NULL)
|
||||
return 0;
|
||||
unit = *(const uintptr_t *)(notice->context + notice->unit_offset) & ~notice->unit_tag;
|
||||
return is_local_controlled_unit((const uint8_t *)unit);
|
||||
}
|
||||
|
||||
/*
|
||||
* Enemy parts-list and hit-camera special-event feedback belong to the local player's own attacks
|
||||
* (including in-flight munitions fired before switching to a drone or support plane) or to the
|
||||
* watched unit while spectating.
|
||||
*/
|
||||
static int is_local_or_watched_attacker(const uint8_t *offender)
|
||||
{
|
||||
const uint8_t *owner_mp;
|
||||
const uint8_t *watched;
|
||||
|
||||
if (offender == NULL)
|
||||
return 0;
|
||||
if (is_local_controlled_unit(offender))
|
||||
return 1;
|
||||
owner_mp = *(const uint8_t *const *)(offender + LMP_UNIT_OFF_MPLAYER);
|
||||
if (local_mp_is_local_mplayer(owner_mp))
|
||||
return 1;
|
||||
watched = g_lmp.watched_hero != NULL ? *(const uint8_t *const *)g_lmp.watched_hero : NULL;
|
||||
return watched != NULL && offender == watched;
|
||||
}
|
||||
|
||||
static uint8_t __fastcall hook_barrel_damage(void *damage, const uint8_t *impact)
|
||||
{
|
||||
@@ -58,17 +133,6 @@ static void __fastcall hook_fire_update(
|
||||
active_notice = previous;
|
||||
}
|
||||
|
||||
static int is_controlled_damage(const DamageNotice *notice)
|
||||
{
|
||||
const uint8_t *mplayer = g_local_mp_mplayer ? *g_local_mp_mplayer : NULL;
|
||||
uintptr_t unit;
|
||||
|
||||
if (mplayer == NULL || notice->context == NULL)
|
||||
return 0;
|
||||
unit = *(const uintptr_t *)(notice->context + notice->unit_offset) & ~notice->unit_tag;
|
||||
return unit != 0 && (const uint8_t *)unit == ((ControlledUnitFn)g_lmp.mplayer_controlled_unit)(mplayer);
|
||||
}
|
||||
|
||||
static void __fastcall hook_deliver_hud(
|
||||
int32_t type, int32_t id, int32_t arg3, int32_t arg4, int32_t arg5,
|
||||
float arg6, float arg7, uint8_t arg8)
|
||||
@@ -81,29 +145,118 @@ static void __fastcall hook_deliver_hud(
|
||||
original_deliver_hud(type, id, arg3, arg4, arg5, arg6, arg7, arg8);
|
||||
}
|
||||
|
||||
/*
|
||||
* Track the unit whose avionics/electronics component is failing. The stock dispatcher checks the
|
||||
* unit's hero flag only for night-vision failure and emits HUD_MSG_DAMAGE (and optic-view exits)
|
||||
* unconditionally for all other cases (guidance, sensors, radar, RWR, TWS, optics, targeting pod,
|
||||
* laser designator, indicators).
|
||||
*/
|
||||
static void __fastcall hook_avionics_damage(const uint8_t *component, uint32_t kind)
|
||||
{
|
||||
const uint8_t *previous = active_avionics_unit;
|
||||
|
||||
if (component != NULL && local_mp_is_host())
|
||||
active_avionics_unit = *(const uint8_t *const *)(component + g_lmp.avionics_unit);
|
||||
original_avionics_damage(component, kind);
|
||||
active_avionics_unit = previous;
|
||||
}
|
||||
|
||||
static void __fastcall hook_deliver_damage_hud(int32_t type, int32_t text_id, int32_t id)
|
||||
{
|
||||
const uint8_t *unit = active_avionics_unit;
|
||||
|
||||
if (unit != NULL && type == HUD_MSG_DAMAGE && local_mp_is_host() && !is_local_controlled_unit(unit)) {
|
||||
if (suppressed_avionics_logged < SUPPRESSED_LOG_LIMIT) {
|
||||
++suppressed_avionics_logged;
|
||||
log_line("local_mp: dropped avionics damage notice %d of a non-local unit", (int)text_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
original_damage_deliver_hud(type, text_id, id);
|
||||
}
|
||||
|
||||
static uint64_t __fastcall hook_exit_optic_view(void *camera, int32_t arg2, uint8_t arg3)
|
||||
{
|
||||
const uint8_t *unit = active_avionics_unit;
|
||||
|
||||
if (unit != NULL && local_mp_is_host() && !is_local_controlled_unit(unit)) {
|
||||
if (suppressed_optic_logged < 4) {
|
||||
++suppressed_optic_logged;
|
||||
log_line("local_mp: prevented optic view exit triggered by a non-local unit");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return original_exit_optic_view(camera, arg2, arg3);
|
||||
}
|
||||
|
||||
static uint64_t __fastcall hook_unit_on_event(void *unit, const uint8_t *event, void *arg3, void *arg4)
|
||||
{
|
||||
const uint8_t *previous = active_hit_event;
|
||||
uint64_t result;
|
||||
|
||||
if (event != NULL && local_mp_is_host())
|
||||
active_hit_event = event;
|
||||
result = original_unit_on_event(unit, event, arg3, arg4);
|
||||
active_hit_event = previous;
|
||||
return result;
|
||||
}
|
||||
|
||||
static int should_drop_hit_parts_feedback(void)
|
||||
{
|
||||
const uint8_t *event = active_hit_event;
|
||||
const uint8_t *offender;
|
||||
|
||||
if (event == NULL || !local_mp_is_host())
|
||||
return 0;
|
||||
offender = *(const uint8_t *const *)(event + g_lmp.hit_event_offender);
|
||||
if (is_local_or_watched_attacker(offender))
|
||||
return 0;
|
||||
if (suppressed_parts_logged < SUPPRESSED_LOG_LIMIT) {
|
||||
++suppressed_parts_logged;
|
||||
log_line("local_mp: dropped enemy parts feedback from a non-local attacker");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void __fastcall hook_enqueue_enemy_parts(void *hud, const uint8_t *victim, const void *info)
|
||||
{
|
||||
if (should_drop_hit_parts_feedback())
|
||||
return;
|
||||
original_enqueue_enemy_parts(hud, victim, info);
|
||||
}
|
||||
|
||||
static void __fastcall hook_hit_cam_important(void *hud, const uint8_t *victim, const void *info)
|
||||
{
|
||||
if (should_drop_hit_parts_feedback())
|
||||
return;
|
||||
original_hit_cam_important(hud, victim, info);
|
||||
}
|
||||
|
||||
static void __fastcall hook_naval_hit_state(void *hud, const uint8_t *victim, const void *info)
|
||||
{
|
||||
if (should_drop_hit_parts_feedback())
|
||||
return;
|
||||
original_naval_hit_state(hud, victim, info);
|
||||
}
|
||||
|
||||
int install_local_mp_damage_notification_hooks(void)
|
||||
{
|
||||
const struct { void *target, *detour, **original; } hooks[] = {
|
||||
{ g_lmp.barrel_notice_deliver, (void *)&hook_deliver_hud, (void **)&original_deliver_hud },
|
||||
{ g_lmp.barrel_damage, (void *)&hook_barrel_damage, (void **)&original_barrel_damage },
|
||||
{ g_lmp.breech_fire_update, (void *)&hook_fire_update, (void **)&original_fire_update },
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "barrel_notice_deliver", g_lmp.barrel_notice_deliver, (void *)&hook_deliver_hud, (void **)&original_deliver_hud },
|
||||
{ "barrel_damage", g_lmp.barrel_damage, (void *)&hook_barrel_damage, (void **)&original_barrel_damage },
|
||||
{ "breech_fire_update", g_lmp.breech_fire_update, (void *)&hook_fire_update, (void **)&original_fire_update },
|
||||
{ "hud_damage_deliver", g_lmp.hud_damage_deliver, (void *)&hook_deliver_damage_hud, (void **)&original_damage_deliver_hud },
|
||||
{ "avionics_damage", g_lmp.avionics_damage, (void *)&hook_avionics_damage, (void **)&original_avionics_damage },
|
||||
{ "avionics_exit_optic", g_lmp.avionics_exit_optic, (void *)&hook_exit_optic_view, (void **)&original_exit_optic_view },
|
||||
{ "unit_on_event", g_lmp.unit_on_event, (void *)&hook_unit_on_event, (void **)&original_unit_on_event },
|
||||
{ "enqueue_enemy_parts", g_lmp.enqueue_enemy_parts, (void *)&hook_enqueue_enemy_parts, (void **)&original_enqueue_enemy_parts },
|
||||
{ "hit_cam_important", g_lmp.hit_cam_important, (void *)&hook_hit_cam_important, (void **)&original_hit_cam_important },
|
||||
{ "naval_hit_state", g_lmp.naval_hit_state, (void *)&hook_naval_hit_state, (void **)&original_naval_hit_state },
|
||||
};
|
||||
size_t created = 0;
|
||||
|
||||
if (g_lmp.barrel_notice_deliver != g_lmp.breech_notice_deliver)
|
||||
if (g_lmp.barrel_notice_deliver != g_lmp.breech_notice_deliver) {
|
||||
log_line("local_mp: local_mp_damage_notifications skipped: barrel and breech deliver addresses differ");
|
||||
return 0;
|
||||
while (created < sizeof(hooks) / sizeof(hooks[0])) {
|
||||
if (MH_CreateHook(hooks[created].target, hooks[created].detour, hooks[created].original) != MH_OK)
|
||||
goto failed;
|
||||
++created;
|
||||
if (MH_QueueEnableHook(hooks[created - 1].target) != MH_OK)
|
||||
goto failed;
|
||||
}
|
||||
if (MH_ApplyQueued() == MH_OK)
|
||||
return 1;
|
||||
|
||||
failed:
|
||||
while (created != 0)
|
||||
MH_RemoveHook(hooks[--created].target);
|
||||
return 0;
|
||||
return local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -226,27 +226,14 @@ static void __fastcall hook_dispatch_naval_damage(int64_t uid, uint8_t *victim,
|
||||
|
||||
int install_local_mp_event_hooks(void)
|
||||
{
|
||||
uint8_t *p_igm_ass = g_lmp.iground_award_assists;
|
||||
uint8_t *p_assist = g_lmp.dispatch_assist;
|
||||
uint8_t *p_cap = g_lmp.dispatch_capture_zone;
|
||||
uint8_t *p_hit = g_lmp.dispatch_hit_crit;
|
||||
uint8_t *p_sev = g_lmp.dispatch_severe_damage;
|
||||
uint8_t *p_nav = g_lmp.dispatch_naval_damage;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "iground_award_assists", g_lmp.iground_award_assists, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists },
|
||||
{ "dispatch_assist", g_lmp.dispatch_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist },
|
||||
{ "dispatch_capture_zone", g_lmp.dispatch_capture_zone, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone },
|
||||
{ "dispatch_hit_crit", g_lmp.dispatch_hit_crit, (void *)&hook_dispatch_hit_crit, (void **)&orig_dispatch_hit_crit },
|
||||
{ "dispatch_severe_damage", g_lmp.dispatch_severe_damage, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage },
|
||||
{ "dispatch_naval_damage", g_lmp.dispatch_naval_damage, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage },
|
||||
};
|
||||
|
||||
if (MH_CreateHook(p_igm_ass, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists) != MH_OK ||
|
||||
MH_EnableHook(p_igm_ass) != MH_OK ||
|
||||
MH_CreateHook(p_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist) != MH_OK ||
|
||||
MH_EnableHook(p_assist) != MH_OK ||
|
||||
MH_CreateHook(p_cap, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone) != MH_OK ||
|
||||
MH_EnableHook(p_cap) != MH_OK ||
|
||||
MH_CreateHook(p_hit, (void *)&hook_dispatch_hit_crit, (void **)&orig_dispatch_hit_crit) != MH_OK ||
|
||||
MH_EnableHook(p_hit) != MH_OK ||
|
||||
MH_CreateHook(p_sev, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage) != MH_OK ||
|
||||
MH_EnableHook(p_sev) != MH_OK ||
|
||||
MH_CreateHook(p_nav, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage) != MH_OK ||
|
||||
MH_EnableHook(p_nav) != MH_OK) {
|
||||
log_line("local_mp: failed to install combat event hooks");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
return local_mp_queue_hooks("local_mp_events", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -82,6 +82,16 @@ void local_mp_add_mplayer_score(uint8_t *mp, float delta, uint32_t event_id);
|
||||
void local_mp_mark_mplayer_dirty(uint8_t *mp);
|
||||
void local_mp_inc_mplayer_stat(uint8_t *mp, size_t off);
|
||||
|
||||
/* Hook descriptor queued by a LocalMP module and enabled in a single batch by local_mp_core.c. */
|
||||
typedef struct LocalMpHookSpec {
|
||||
const char *name;
|
||||
void *target;
|
||||
void *detour;
|
||||
void **original;
|
||||
} LocalMpHookSpec;
|
||||
|
||||
int local_mp_queue_hooks(const char *module, const LocalMpHookSpec *specs, size_t count);
|
||||
|
||||
/* Module hook installers, called by install_local_mp_hooks() once the module's values are loaded. */
|
||||
int install_local_mp_player_hooks(void);
|
||||
int install_local_mp_loadout_hooks(void);
|
||||
|
||||
@@ -192,18 +192,13 @@ static void __fastcall hook_on_unit_dead_once(uint8_t *victim)
|
||||
|
||||
int install_local_mp_kill_hooks(void)
|
||||
{
|
||||
uint8_t *p_ground_dead = g_lmp.iground_on_dead;
|
||||
uint8_t *p_dead = g_lmp.on_unit_dead_once;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "iground_on_dead", g_lmp.iground_on_dead, (void *)&hook_iground_on_became_dead, (void **)&orig_iground_on_dead },
|
||||
{ "on_unit_dead_once", g_lmp.on_unit_dead_once, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once },
|
||||
};
|
||||
|
||||
fn_mplayer_add_score = (MPlayerAddScoreFn)g_lmp.mplayer_add_score;
|
||||
fn_net_mark_dirty = (NetMarkDirtyFn)g_lmp.net_mark_dirty;
|
||||
|
||||
if (MH_CreateHook(p_ground_dead, (void *)&hook_iground_on_became_dead, (void **)&orig_iground_on_dead) != MH_OK ||
|
||||
MH_EnableHook(p_ground_dead) != MH_OK ||
|
||||
MH_CreateHook(p_dead, (void *)&hook_on_unit_dead_once, (void **)&orig_on_unit_dead_once) != MH_OK ||
|
||||
MH_EnableHook(p_dead) != MH_OK) {
|
||||
log_line("local_mp: failed to install unit-death scoring hooks");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
return local_mp_queue_hooks("local_mp_kills", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -202,7 +202,9 @@ static void __fastcall hook_sem_change_aircraft_send(
|
||||
|
||||
int install_local_mp_loadout_hooks(void)
|
||||
{
|
||||
uint8_t *p_sem_send = g_lmp.sem_change_aircraft_send;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "sem_change_aircraft_send", g_lmp.sem_change_aircraft_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send },
|
||||
};
|
||||
|
||||
/* The reflection is built in a fixed stack buffer; its bullet sets vector is its last member. */
|
||||
if (LMP_REFL_OFF_BULLETS_VEC + 0x20u > LMP_REFL_SIZE) {
|
||||
@@ -222,10 +224,5 @@ int install_local_mp_loadout_hooks(void)
|
||||
fn_namemap_add = (NameMapAddNameIdFn)g_lmp.namemap_add_name_id;
|
||||
fn_crew_skills_init = (CrewSkillsInitFn)g_lmp.crew_skills_init;
|
||||
|
||||
if (MH_CreateHook(p_sem_send, (void *)&hook_sem_change_aircraft_send, (void **)&orig_sem_send) != MH_OK ||
|
||||
MH_EnableHook(p_sem_send) != MH_OK) {
|
||||
log_line("local_mp: failed to install SemChangeAircraftRequest::send hook");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
return local_mp_queue_hooks("local_mp_loadout", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -129,17 +129,11 @@ static uint64_t __fastcall hook_cta_logic(uint8_t *ctx, void *a2, void *a3, void
|
||||
|
||||
int install_local_mp_nuke_hooks(void)
|
||||
{
|
||||
uint8_t *p_launch = g_lmp.shell_launch;
|
||||
uint8_t *p_explode = g_lmp.shell_explode;
|
||||
uint8_t *p_cta = g_lmp.cta_logic_action;
|
||||
if (MH_CreateHook(p_launch, (void *)&hook_shell_launch, (void **)&orig_shell_launch) != MH_OK ||
|
||||
MH_CreateHook(p_explode, (void *)&hook_shell_explode, (void **)&orig_shell_explode) != MH_OK ||
|
||||
MH_CreateHook(p_cta, (void *)&hook_cta_logic, (void **)&orig_cta_logic) != MH_OK ||
|
||||
MH_EnableHook(p_launch) != MH_OK ||
|
||||
MH_EnableHook(p_explode) != MH_OK ||
|
||||
MH_EnableHook(p_cta) != MH_OK) {
|
||||
log_line("local_mp: failed to install the nuclear instant-win hooks");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "shell_launch", g_lmp.shell_launch, (void *)&hook_shell_launch, (void **)&orig_shell_launch },
|
||||
{ "shell_explode", g_lmp.shell_explode, (void *)&hook_shell_explode, (void **)&orig_shell_explode },
|
||||
{ "cta_logic_action", g_lmp.cta_logic_action, (void *)&hook_cta_logic, (void **)&orig_cta_logic },
|
||||
};
|
||||
|
||||
return local_mp_queue_hooks("local_mp_nuke", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -208,21 +208,12 @@ static uint8_t __fastcall hook_is_slot_ready_at_host(int32_t slot_id, const char
|
||||
|
||||
int install_local_mp_player_hooks(void)
|
||||
{
|
||||
uint8_t *p_gui_update = g_lmp.gui_state_update;
|
||||
uint8_t *p_mp_init = g_lmp.mplayer_init_matching;
|
||||
uint8_t *p_do_respawn = g_lmp.do_respawn_player;
|
||||
uint8_t *p_slot_ready = g_lmp.is_slot_ready_at_host;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "gui_state_update", g_lmp.gui_state_update, (void *)&hook_gui_state_update, (void **)&orig_gui_state_update },
|
||||
{ "mplayer_init_matching", g_lmp.mplayer_init_matching, (void *)&hook_mplayer_init_from_matching, (void **)&orig_mplayer_init_matching },
|
||||
{ "do_respawn_player", g_lmp.do_respawn_player, (void *)&hook_do_respawn_player, (void **)&orig_do_respawn },
|
||||
{ "is_slot_ready_at_host", g_lmp.is_slot_ready_at_host, (void *)&hook_is_slot_ready_at_host, (void **)&orig_is_slot_ready_at_host },
|
||||
};
|
||||
|
||||
if (MH_CreateHook(p_gui_update, (void *)&hook_gui_state_update, (void **)&orig_gui_state_update) != MH_OK ||
|
||||
MH_EnableHook(p_gui_update) != MH_OK ||
|
||||
MH_CreateHook(p_mp_init, (void *)&hook_mplayer_init_from_matching, (void **)&orig_mplayer_init_matching) != MH_OK ||
|
||||
MH_EnableHook(p_mp_init) != MH_OK ||
|
||||
MH_CreateHook(p_do_respawn, (void *)&hook_do_respawn_player, (void **)&orig_do_respawn) != MH_OK ||
|
||||
MH_EnableHook(p_do_respawn) != MH_OK ||
|
||||
MH_CreateHook(p_slot_ready, (void *)&hook_is_slot_ready_at_host, (void **)&orig_is_slot_ready_at_host) != MH_OK ||
|
||||
MH_EnableHook(p_slot_ready) != MH_OK) {
|
||||
log_line("local_mp: failed to install player state hooks");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
return local_mp_queue_hooks("local_mp_players", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -100,11 +100,9 @@ static void __fastcall hook_set_controlled_unit(uint8_t *mp, uint32_t eid)
|
||||
|
||||
int install_local_mp_support_hooks(void)
|
||||
{
|
||||
uint8_t *p_set = g_lmp.set_controlled_unit;
|
||||
if (MH_CreateHook(p_set, (void *)&hook_set_controlled_unit, (void **)&orig_set_controlled_unit) != MH_OK ||
|
||||
MH_EnableHook(p_set) != MH_OK) {
|
||||
log_line("local_mp: failed to install the support unit hook");
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
const LocalMpHookSpec hooks[] = {
|
||||
{ "set_controlled_unit", g_lmp.set_controlled_unit, (void *)&hook_set_controlled_unit, (void **)&orig_set_controlled_unit },
|
||||
};
|
||||
|
||||
return local_mp_queue_hooks("local_mp_support", hooks, sizeof(hooks) / sizeof(hooks[0]));
|
||||
}
|
||||
@@ -150,6 +150,14 @@ static const LmpValueSpec SPECS[] = {
|
||||
A(DAMAGE_NOTICES, "breech_damage_notice.deliver", breech_notice_deliver),
|
||||
O(DAMAGE_NOTICES, "breech_damage_notice.id", breech_notice_id),
|
||||
A(DAMAGE_NOTICES, "mplayer_controlled_unit", mplayer_controlled_unit),
|
||||
A(DAMAGE_NOTICES, "hud_damage_deliver", hud_damage_deliver),
|
||||
A(DAMAGE_NOTICES, "avionics_damage", avionics_damage), O(DAMAGE_NOTICES, "avionics_damage.unit", avionics_unit),
|
||||
A(DAMAGE_NOTICES, "avionics_exit_optic.call", avionics_exit_optic),
|
||||
A(DAMAGE_NOTICES, "unit_on_event", unit_on_event), O(DAMAGE_NOTICES, "hit_event_offender.offender", hit_event_offender),
|
||||
A(DAMAGE_NOTICES, "hit_watched_hero.watched_hero", watched_hero),
|
||||
A(DAMAGE_NOTICES, "hit_parts_feedback.enqueue_enemy_parts", enqueue_enemy_parts),
|
||||
A(DAMAGE_NOTICES, "hit_parts_feedback.hit_cam_important", hit_cam_important),
|
||||
A(DAMAGE_NOTICES, "hit_parts_feedback.naval_hit_state", naval_hit_state),
|
||||
};
|
||||
|
||||
static void store(const LmpValueSpec *spec, int64_t value, uint8_t *base)
|
||||
|
||||
@@ -77,7 +77,9 @@ typedef struct LmpValues {
|
||||
|
||||
/* local_mp_damage_notifications */
|
||||
uint8_t *barrel_damage, *breech_fire_update, *barrel_notice_deliver, *breech_notice_deliver, *mplayer_controlled_unit;
|
||||
size_t barrel_unit_ref, breech_unit, barrel_notice_id, breech_notice_id;
|
||||
uint8_t *hud_damage_deliver, *avionics_damage, *avionics_exit_optic;
|
||||
uint8_t *unit_on_event, *watched_hero, *enqueue_enemy_parts, *hit_cam_important, *naval_hit_state;
|
||||
size_t barrel_unit_ref, breech_unit, barrel_notice_id, breech_notice_id, avionics_unit, hit_event_offender;
|
||||
} LmpValues;
|
||||
|
||||
extern LmpValues g_lmp;
|
||||
|
||||
Generated
+1
-1
@@ -21,7 +21,7 @@
|
||||
},
|
||||
"apps/launcher": {
|
||||
"name": "@wto/launcher",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"@fontsource/roboto-condensed": "^5.3.0",
|
||||
"@wto/patcher": "*",
|
||||
|
||||
@@ -1,20 +1,61 @@
|
||||
/**
|
||||
* Write the built files into the game copy folder.
|
||||
* Write the built files into the game copy folder atomically so transient antivirus locks or
|
||||
* interrupted writes never leave a missing or truncated game file.
|
||||
*/
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import type { GameCopyFile } from './build-game-copy.ts';
|
||||
|
||||
const TRANSIENT_REPLACE_ERRORS = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
||||
const MAX_REPLACE_ATTEMPTS = 8;
|
||||
const WAIT_BUFFER = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
/** Writes every file and returns the full paths written, in order. */
|
||||
export function writeGameCopy(copyFolder: string, files: readonly GameCopyFile[]): string[] {
|
||||
return files.map((file) => {
|
||||
const path = join(copyFolder, file.path);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
// Remove before writing: a read-only file is replaced instead of failing with EPERM, and a
|
||||
// file hard-linked to the stock folder gets a new file of its own instead of changing the
|
||||
// stock one through the link.
|
||||
rmSync(path, { force: true });
|
||||
writeFileSync(path, file.content);
|
||||
writeFileAtomically(path, file.content);
|
||||
return path;
|
||||
});
|
||||
}
|
||||
|
||||
function writeFileAtomically(path: string, content: Uint8Array): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
// Replacing via rename keeps hard-linked stock files untouched by giving the copy its own inode,
|
||||
// and avoids deleting the target before the replacement is fully flushed to disk.
|
||||
const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
||||
const fd = openSync(temporary, 'w');
|
||||
try {
|
||||
writeFileSync(fd, content);
|
||||
fsyncSync(fd);
|
||||
} catch (error) {
|
||||
try { closeSync(fd); } catch { /* ignore */ }
|
||||
try { rmSync(temporary, { force: true }); } catch { /* ignore */ }
|
||||
throw error;
|
||||
}
|
||||
closeSync(fd);
|
||||
try {
|
||||
renameWithRetry(temporary, path);
|
||||
} catch (error) {
|
||||
try { rmSync(temporary, { force: true }); } catch { /* ignore */ }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function renameWithRetry(source: string, target: string): void {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
renameSync(source, target);
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (attempt >= MAX_REPLACE_ATTEMPTS || !code || !TRANSIENT_REPLACE_ERRORS.has(code)) throw error;
|
||||
// A read-only target fails rename with EPERM/EACCES on Windows; clear the attribute before retrying.
|
||||
if (code === 'EPERM' || code === 'EACCES') {
|
||||
try { chmodSync(target, 0o666); } catch { /* ignore */ }
|
||||
}
|
||||
Atomics.wait(WAIT_BUFFER, 0, 0, attempt * 30);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Never invoke the official launcher.exe from the helper that spawns "\..\launcher.exe" and exits.
|
||||
// Why the executable: the startup package-size check ignores -forcestart, and fatal file read errors (0x81110007)
|
||||
// bypass config.blk noLauncher too; no local service can intercept a direct ShellExecute call.
|
||||
// Without it: any content/warthunder.blk size mismatch or file read error spawns launcher.exe -fullcheck,
|
||||
// which connects to Gaijin and overwrites the patched offline files back to the online build.
|
||||
{
|
||||
"id": "isolation/never-launch-official-launcher",
|
||||
"title": "禁止游戏拉起官方启动器 launcher.exe(保留退出日志和退出码)",
|
||||
"features": [
|
||||
"A-Isolation from the official game",
|
||||
"A-No Gaijin connections"
|
||||
],
|
||||
"requires": [],
|
||||
"variants": [
|
||||
// Tail of the official launcher spawner from the "-fullcheck" argument setup through ExitProcess(1), 106 bytes;
|
||||
// rip-relative displacements and relative call targets are wildcards.
|
||||
// 2.61.0.37: unique hit at 0xeedd07 (function 0xeedc70-0xeedd72), os_shell_execute call at +64 (0xeedd47).
|
||||
// 2.61.0.43: unique hit at 0xef1d37 (function 0xef1ca0-0xef1da2), os_shell_execute call at +64 (0xef1d77).
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "signature",
|
||||
"section": ".text",
|
||||
"pattern": "4c 8d 05 ?? ?? ?? ?? 48 85 f6 48 8d 15 ?? ?? ?? ?? 48 0f 45 d6 31 c0 84 db 4c 0f 44 c0 c6 44 24 20 01 48 8d 35 ?? ?? ?? ?? 48 8d 05 ?? ?? ?? ?? 48 8d 3d ?? ?? ?? ?? 48 0f 45 f8 31 c9 45 31 c9 e8 ?? ?? ?? ?? b9 4d 41 49 4e 48 89 f2 e8 ?? ?? ?? ?? 48 89 f9 e8 ?? ?? ?? ?? e8 ?? ?? ?? ?? b9 01 00 00 00 ff 15 ?? ?? ?? ??"
|
||||
},
|
||||
"edit": {
|
||||
"offset": 64,
|
||||
"asm": [
|
||||
"nop",
|
||||
"nop",
|
||||
"nop",
|
||||
"nop",
|
||||
"nop"
|
||||
],
|
||||
"bytes": "90 90 90 90 90",
|
||||
"expect_original": "e8 ?? ?? ?? ??"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// Send barrel explosion and breech misfire notices only for the locally controlled unit.
|
||||
// The native producers know the affected unit. The HUD receives only the type, text and ID.
|
||||
// Bind self damage, avionics failure and hit-parts feedback to the player on a LocalMP host.
|
||||
// The stock damage producers skip hero/attacker checks on dedicated-server paths because a
|
||||
// dedicated server has no HUD; on a LocalMP host both run in the same process.
|
||||
// The HUD receives only the type, text index and ID, or the victim's damaged parts list.
|
||||
{
|
||||
"module": "local_mp_damage_notifications",
|
||||
"features": [
|
||||
@@ -87,6 +89,124 @@
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// HUD_MSG_DAMAGE delivery: resolves the text index to localized text, then pushes
|
||||
// {type, text, id} into the local HUD event queue.
|
||||
// 2.61.0.37: 0x19b1030; 2.61.0.43: 0x19b6ba0.
|
||||
"hud_damage_deliver": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "signature",
|
||||
"pattern": "56 57 53 48 83 ec 50 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 44 89 c6 89 cf b0 01"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Unit avionics/electronics failure dispatcher (13-entry switch for guidance, sensors, radar,
|
||||
// RWR, TWS, optics, targeting pod, laser designator, NVG, indicators). Reads its owning Unit*
|
||||
// from [comp + unit]; most cases emit HUD_MSG_DAMAGE without checking the unit's hero flag.
|
||||
// 2.61.0.37: 0xfca8b0; 2.61.0.43: 0xfce8e0.
|
||||
"avionics_damage": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "signature",
|
||||
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 58 0f 29 74 24 40 48 89 ce 83 fa 0c 0f 87 ?? ?? ?? ?? 89 d0 48 8d 0d ?? ?? ?? ?? 48 63 04 81 48 01 c8 ff e0 48 8b 46 ??",
|
||||
"captures": {
|
||||
"unit": { "offset": 54, "type": "u8" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Camera optic-view exit invoked by avionics_damage cases 2, 7 and 8 without checking hero.
|
||||
// 2.61.0.37: 0xfcab0b -> 0x15cd9c0; 2.61.0.43: 0xfceb3b -> 0x15d2760.
|
||||
"avionics_exit_optic": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "within",
|
||||
"in": "avionics_damage",
|
||||
"pattern": "48 81 c1 ?? ?? ?? ?? 89 d3 ba 01 00 00 00 41 b0 01 e8 ?? ?? ?? ??",
|
||||
"captures": {
|
||||
"call": { "offset": 18, "type": "rel32" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Unit::onEvent: receives hit events for every unit on a LocalMP host and falls through into
|
||||
// enemy parts-list and hit-camera special-event delivery even when the attacker is an AI unit.
|
||||
// 2.61.0.37: 0x103fbc0; 2.61.0.43: 0x1043fe0.
|
||||
"unit_on_event": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "signature",
|
||||
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec c8 04 00 00 44 0f 29 bc 24 b0 04 00 00 44 0f 29 b4 24 a0 04 00 00 44 0f 29 ac 24 90 04 00 00 44 0f 29 a4 24 80 04 00 00 44 0f 29 9c 24 70 04 00 00 44 0f 29 94 24 60 04 00 00 44 0f 29 8c 24 50 04 00 00 44 0f 29 84 24 40 04 00 00 0f 29 bc 24 30 04 00 00 0f 29 b4 24 20 04 00 00 48 89 d7 49 89 cd 0f b7 42 20"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Hit event attacker Unit* offset loaded before comparing against g_hero in Unit::onEvent.
|
||||
// 2.61.0.37: 0x104495d (offender=0xd0); 2.61.0.43: 0x1048d7d (offender=0xd0).
|
||||
"hit_event_offender": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "within",
|
||||
"in": "unit_on_event",
|
||||
"pattern": "48 8b bf ?? ?? ?? ?? 48 8b 35 ?? ?? ?? ?? 48 85 f6 74 ?? 48 8b 8e ?? ?? ?? ??",
|
||||
"captures": {
|
||||
"offender": { "offset": 3, "type": "u32" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Watched hero cell used when spectating in Unit::onEvent.
|
||||
// 2.61.0.37: 0x10449ab -> 0x7bad420; 2.61.0.43: 0x1048dcb -> 0x7bb9780.
|
||||
"hit_watched_hero": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "within",
|
||||
"in": "unit_on_event",
|
||||
"pattern": "40 84 ed 74 ?? 48 8b 15 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 48 39 d7 75 ??",
|
||||
"captures": {
|
||||
"watched_hero": { "offset": 8, "type": "rel32" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
// Unconditional enemy parts-list, hit-camera important events and naval hit-state calls
|
||||
// reached after the hit-camera attacker check in Unit::onEvent.
|
||||
// 2.61.0.37: 0x1045fc3 -> 0x18977c0, 0x1897cc0, 0x1896a40;
|
||||
// 2.61.0.43: 0x104a3d9 -> 0x189d140, 0x189d640, 0x189c3c0.
|
||||
"hit_parts_feedback": {
|
||||
"variants": [
|
||||
{
|
||||
"written_for": "2.61.0.37",
|
||||
"locate": {
|
||||
"method": "within",
|
||||
"in": "unit_on_event",
|
||||
"pattern": "48 8b 0d ?? ?? ?? ?? 4c 8d b4 24 00 01 00 00 4c 89 ea 4d 89 f0 e8 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 4c 89 ea 4d 89 f0 e8 ?? ?? ?? ?? 66 41 83 bd 8c 00 00 00 05 75 ?? 48 8b 0d ?? ?? ?? ?? 4c 8d 84 24 00 01 00 00 4c 89 ea e8 ?? ?? ?? ??",
|
||||
"captures": {
|
||||
"enqueue_enemy_parts": { "offset": 22, "type": "rel32" },
|
||||
"hit_cam_important": { "offset": 40, "type": "rel32" },
|
||||
"naval_hit_state": { "offset": 74, "type": "rel32" }
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
// Patch check results for this game build; written by scripts/record-game-version.ts.
|
||||
{
|
||||
"game_version": "2.61.0.55",
|
||||
"executable_sha256": "9886e2fa909518d5f30a4cd347d18847cb09dfbc79d17275ffbdb70c487acf15",
|
||||
"gui_pack_sha256": "dcba2a00fd9f99b437b10ece005fef4b0cd06ddee819c2049cf5de47241529d8",
|
||||
"exe_patches": {
|
||||
"battle/allow-local-host-bot-spawns": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x11b782a"
|
||||
},
|
||||
"battle/allow-local-host-player-respawn": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x104995c"
|
||||
},
|
||||
"battle/allow-local-host-ucav-launch": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x1021753"
|
||||
},
|
||||
"battle/count-bots-as-active-players": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x11be968"
|
||||
},
|
||||
"isolation/never-load-battleye": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x30d60fc"
|
||||
},
|
||||
"isolation/never-upload-crash-reports": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x4104dda"
|
||||
},
|
||||
"isolation/registry-key": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x7a4b11c"
|
||||
},
|
||||
"isolation/user-data-folder-name": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x778f22e"
|
||||
},
|
||||
"online/accept-local-tls-certificate": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x5655772"
|
||||
},
|
||||
"online/matching-server-public-key": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x7352660"
|
||||
},
|
||||
"online/network-hook-library": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x7a5c5aa"
|
||||
},
|
||||
"startup/skip-resource-archive-signature-check": {
|
||||
"variant": "2.61.0.37",
|
||||
"rva": "0x4082ed0"
|
||||
}
|
||||
},
|
||||
"gui_patches": {
|
||||
"agreement/require-explicit-acceptance": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"agreement/show-offline-terms": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/append-extra-battle-slots": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/force-extra-slot-weapons": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/launch-local-battle-from-queue": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/lineup-br-for-submodes": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/local-host-spawn-score": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/lock-single-slot-lineup": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/match-settled-battle-room-logs": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/open-replay-from-battle-log": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/pass-spawn-modifications-blk": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/play-local-battle-replay": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/quit-local-host-spectator-to-debriefing": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/quit-local-host-to-debriefing": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/ready-local-host-respawn": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/record-local-battle-awards": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/report-local-battle-settlement": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/scoreboard-team-country-flags": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/stabilize-respawn-countdown-button": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/tag-local-battle-replay": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"battle/use-settled-debriefing-stats": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"inventory/local-content-public-key": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"inventory/show-coupon-redemption-reward": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/bypass-external-sso-for-local-urls": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/collect-entitlement-purchase-rewards": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/defer-explicit-browser-update-to-close": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/free-offline-payment-method": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/localize-vehicle-pack-titles": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/open-entitlement-purchase-receipts": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/present-saved-entitlement-grants": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/refresh-profile-after-browser-close": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/refresh-profile-after-currency-shop-close": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/refresh-profile-after-premium-shop-close": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/render-retired-entitlement-log": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/resume-purchase-receipts-after-price-update": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/return-entitlement-reward-handler": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/show-direct-entitlement-gift-icons": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/show-direct-entitlement-gifts": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/show-entitlement-purchase-rewards": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"online-shop/use-entitlement-receipt-for-native-payment": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"registration/keep-local-page-embedded": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"registration/open-local-page": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"tutorials/cancel-guide-without-target": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"tutorials/guard-crew-training-intro": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"tutorials/immediate-save-skip-tutorial": {
|
||||
"variant": "2.61.0.37"
|
||||
},
|
||||
"tutorials/save-crew-training-completion": {
|
||||
"variant": "2.61.0.37"
|
||||
}
|
||||
},
|
||||
"native_modules": {
|
||||
"local_mp_core": {
|
||||
"disabled_slots_mask": "2.61.0.37",
|
||||
"do_respawn_player": "2.61.0.37",
|
||||
"get_player_country": "2.61.0.37",
|
||||
"sq_local_country": "2.61.0.37",
|
||||
"refl_dtor": "2.61.0.37",
|
||||
"aircraft_change_result": "2.61.0.37",
|
||||
"set_player_gui_state": "2.61.0.37",
|
||||
"get_unit_by_eid": "2.61.0.37",
|
||||
"set_owning_mplayer": "2.61.0.37",
|
||||
"iground_on_dead": "2.61.0.37",
|
||||
"datablock_get_str": "2.61.0.37",
|
||||
"datablock_set_from": "2.61.0.37",
|
||||
"mp_construct_local": "2.61.0.37",
|
||||
"gui_state_update": "2.61.0.37",
|
||||
"app_econ_state": "2.61.0.37",
|
||||
"mplayer_matching": "2.61.0.37",
|
||||
"unit_change_aircraft": "2.61.0.37",
|
||||
"unit_type": "2.61.0.37",
|
||||
"unit_info_name": "2.61.0.37",
|
||||
"unit_mplayer": "2.61.0.37",
|
||||
"refl_stdmem": "2.61.0.37",
|
||||
"mission_settings_load": "2.61.0.37",
|
||||
"mission_custom_bots": "2.61.0.37",
|
||||
"scoreboard_rows": "2.61.0.37",
|
||||
"mplayer_unit_eid": "2.61.0.37"
|
||||
},
|
||||
"local_mp_actions": {
|
||||
"mp_init_chat": "2.61.0.37",
|
||||
"mp_chat": "2.61.0.37",
|
||||
"bot_system_setup": "2.61.0.37",
|
||||
"mp_team_countries": "2.61.0.37"
|
||||
},
|
||||
"local_mp_awards": {
|
||||
"add_score_message": "2.61.0.37",
|
||||
"score_msg_blk_ctor": "2.61.0.37",
|
||||
"score_msg_blk_set_str": "2.61.0.37",
|
||||
"score_msg_blk_to_owned": "2.61.0.37",
|
||||
"score_msg_blk_set_int": "2.61.0.37",
|
||||
"score_msg_hud_queue": "2.61.0.37",
|
||||
"score_msg_blk_dtor": "2.61.0.37",
|
||||
"score_msg_exp_class": "2.61.0.37",
|
||||
"game_save_data": "2.61.0.37"
|
||||
},
|
||||
"local_mp_damage_notifications": {
|
||||
"barrel_damage": "2.61.0.37",
|
||||
"barrel_damage_notice": "2.61.0.37",
|
||||
"breech_fire_update": "2.61.0.37",
|
||||
"breech_damage_notice": "2.61.0.37",
|
||||
"mplayer_controlled_unit": "2.61.0.37",
|
||||
"hud_damage_deliver": "2.61.0.37",
|
||||
"hero_unit": "2.61.0.37"
|
||||
},
|
||||
"local_mp_scores": {
|
||||
"datablock_get_real": "2.61.0.37",
|
||||
"mission_score_params": "2.61.0.37"
|
||||
},
|
||||
"local_mp_kills": {
|
||||
"mplayer_add_score": "2.61.0.37",
|
||||
"mplayer_score": "2.61.0.37",
|
||||
"mplayer_stat_sync": "2.61.0.37",
|
||||
"net_mark_dirty": "2.61.0.37",
|
||||
"on_unit_dead_once": "2.61.0.37",
|
||||
"unit_severe": "2.61.0.37",
|
||||
"ground_death_flags": "2.61.0.37",
|
||||
"ground_bailout": "2.61.0.37",
|
||||
"ground_offenders": "2.61.0.37",
|
||||
"iground_award_assists": "2.61.0.37",
|
||||
"offender_fields": "2.61.0.37",
|
||||
"stat_kills": "2.61.0.37",
|
||||
"stat_ground_kills": "2.61.0.37",
|
||||
"stat_human_kills": "2.61.0.37",
|
||||
"stat_naval_kills": "2.61.0.37",
|
||||
"stat_team_kills": "2.61.0.37",
|
||||
"stat_ai_kills": "2.61.0.37",
|
||||
"stat_ai_ground_kills": "2.61.0.37",
|
||||
"stat_ai_naval_kills": "2.61.0.37",
|
||||
"stat_assists": "2.61.0.37",
|
||||
"stat_deaths": "2.61.0.37",
|
||||
"stat_capture_zone": "2.61.0.37",
|
||||
"stat_score": "2.61.0.37",
|
||||
"stat_award_damage": "2.61.0.37",
|
||||
"stat_air_severe": "2.61.0.37",
|
||||
"stat_ship_severe": "2.61.0.37"
|
||||
},
|
||||
"local_mp_events": {
|
||||
"dispatch_assist": "2.61.0.37",
|
||||
"caller_capture_zone": "2.61.0.37",
|
||||
"caller_hit_crit": "2.61.0.37",
|
||||
"caller_severe_damage": "2.61.0.37",
|
||||
"caller_naval_damage": "2.61.0.37",
|
||||
"offender_assist": "2.61.0.37"
|
||||
},
|
||||
"local_mp_players": {
|
||||
"mplayer_init_matching": "2.61.0.37",
|
||||
"is_slot_ready_at_host": "2.61.0.37",
|
||||
"mplayer_gui_state": "2.61.0.37",
|
||||
"mplayer_clear_before_lobby": "2.61.0.37",
|
||||
"mplayer_used_spares": "2.61.0.37",
|
||||
"mission_allies_country": "2.61.0.37",
|
||||
"mission_axis_country": "2.61.0.37",
|
||||
"mission_arcade_country": "2.61.0.37"
|
||||
},
|
||||
"local_mp_loadout": {
|
||||
"sem_change_aircraft_send": "2.61.0.37",
|
||||
"refl_ctor": "2.61.0.37",
|
||||
"datablock_dtor": "2.61.0.37",
|
||||
"bullet_vec_assign": "2.61.0.37",
|
||||
"get_decals_blk": "2.61.0.37",
|
||||
"get_attachables_blk": "2.61.0.37",
|
||||
"str_hash_fnv1": "2.61.0.37",
|
||||
"namemap_add_name_id": "2.61.0.37",
|
||||
"crew_skills_init": "2.61.0.37",
|
||||
"refl_objects": "2.61.0.37",
|
||||
"refl_names": "2.61.0.37",
|
||||
"refl_flags": "2.61.0.37",
|
||||
"refl_targeting": "2.61.0.37",
|
||||
"refl_vertical_targeting": "2.61.0.37",
|
||||
"refl_bomb_fuse": "2.61.0.37",
|
||||
"respawn_spawn": "2.61.0.37",
|
||||
"unit_spawn_state": "2.61.0.37",
|
||||
"change_req_slot": "2.61.0.37",
|
||||
"econ_clear": "2.61.0.37",
|
||||
"change_req_bullets": "2.61.0.37",
|
||||
"unit_crew_skills": "2.61.0.37"
|
||||
},
|
||||
"local_mp_nuke": {
|
||||
"shell_launch": "2.61.0.37",
|
||||
"shell_instant_win": "2.61.0.37",
|
||||
"shell_explode": "2.61.0.37",
|
||||
"cta_logic_action": "2.61.0.37",
|
||||
"mission_vars_data": "2.61.0.37",
|
||||
"mission_vars_walk": "2.61.0.37",
|
||||
"mission_vars_step": "2.61.0.37",
|
||||
"mission_vars_value": "2.61.0.37"
|
||||
},
|
||||
"local_mp_support": {
|
||||
"set_controlled_unit": "2.61.0.37",
|
||||
"mplayer_update": "2.61.0.37",
|
||||
"mplayer_support_unit": "2.61.0.37"
|
||||
}
|
||||
},
|
||||
"native_values": {
|
||||
"add_score_message": "0x18a28d0",
|
||||
"aircraft_change_result": "0xec0a90",
|
||||
"aircraft_change_result.econ_change_req": "0xf578",
|
||||
"app_econ_state": "0x1565b27",
|
||||
"app_econ_state.econ_holder": "0x3f0",
|
||||
"app_econ_state.econ_state": "0x9a8",
|
||||
"barrel_damage": "0x398ab0",
|
||||
"barrel_damage_notice": "0x398cdf",
|
||||
"barrel_damage_notice.deliver": "0x19b9a70",
|
||||
"barrel_damage_notice.id": "0x1e2",
|
||||
"barrel_damage.unit": "0x18",
|
||||
"bot_system_setup": "0x11b3fe0",
|
||||
"breech_damage_notice": "0x13e7798",
|
||||
"breech_damage_notice.deliver": "0x19b9a70",
|
||||
"breech_damage_notice.id": "0x1e4",
|
||||
"breech_fire_update": "0x13e61e0",
|
||||
"breech_fire_update.unit": "0x8",
|
||||
"bullet_vec_assign": "0x4f19c0",
|
||||
"caller_capture_zone": "0x3db410",
|
||||
"caller_capture_zone.call": "0x357640",
|
||||
"caller_hit_crit": "0xffd01a",
|
||||
"caller_hit_crit.call": "0x35bf50",
|
||||
"caller_naval_damage": "0xd0874a",
|
||||
"caller_naval_damage.call": "0x35a920",
|
||||
"caller_severe_damage": "0xe59aba",
|
||||
"caller_severe_damage.call": "0x35c640",
|
||||
"change_req_bullets": "0x2dd3df",
|
||||
"change_req_bullets.bullets_begin": "0xf608",
|
||||
"change_req_bullets.bullets_end": "0xf610",
|
||||
"change_req_slot": "0xec0c57",
|
||||
"change_req_slot.slot_id": "0xf65c",
|
||||
"crew_skills_init": "0x1036bc0",
|
||||
"cta_logic_action": "0x11c11f0",
|
||||
"datablock_dtor": "0x30a2a00",
|
||||
"datablock_get_real": "0x54545d0",
|
||||
"datablock_get_str": "0x30a33a0",
|
||||
"datablock_set_from": "0x30a21b0",
|
||||
"datablock_set_from.dagmem_alloc": "0x6c04d8c",
|
||||
"disabled_slots_mask": "0x6bdb20",
|
||||
"disabled_slots_mask.app": "0x7bbc848",
|
||||
"disabled_slots_mask.local_mplayer": "0x7b927f0",
|
||||
"disabled_slots_mask.mplayer_broken_slots": "0x4d0",
|
||||
"disabled_slots_mask.multiplayer": "0x7b94ce0",
|
||||
"dispatch_assist": "0x35c1e0",
|
||||
"do_respawn_player": "0xc6fdb0",
|
||||
"do_respawn_player.app_score_rules": "0x3e0",
|
||||
"do_respawn_player.hero": "0x7bbe858",
|
||||
"econ_clear": "0x2dd280",
|
||||
"game_save_data": "0x4283b9",
|
||||
"game_save_data.game_save_data": "0x7c05df8",
|
||||
"get_attachables_blk": "0x2e0870",
|
||||
"get_decals_blk": "0x2df920",
|
||||
"get_player_country": "0x127d0f0",
|
||||
"get_player_country.mp_is_local_mp": "0x61",
|
||||
"get_player_country.player_count": "0x7b92810",
|
||||
"get_player_country.player_table": "0x7b92800",
|
||||
"get_unit_by_eid": "0x1110460",
|
||||
"ground_bailout": "0x428001",
|
||||
"ground_bailout.bailout_dead": "0x3888",
|
||||
"ground_death_flags": "0x427a30",
|
||||
"ground_death_flags.already_dead": "0x2101",
|
||||
"ground_death_flags.dead_silent": "0x1c19",
|
||||
"ground_offenders": "0x42804d",
|
||||
"ground_offenders.killer": "0x19e8",
|
||||
"ground_offenders.killer_pid": "0x1a08",
|
||||
"ground_offenders.killer_uid": "0x1a40",
|
||||
"ground_offenders.offender_size": "0x160",
|
||||
"ground_offenders.offenders": "0x17c0",
|
||||
"ground_offenders.offenders_count": "0x17d0",
|
||||
"ground_offenders.unit_type": "0x8c",
|
||||
"gui_state_update": "0x1565a00",
|
||||
"hero_unit": "0xeca919",
|
||||
"hero_unit.cell": "0x7bbe858",
|
||||
"hud_damage_deliver": "0x19b9560",
|
||||
"iground_award_assists": "0x465ae0",
|
||||
"iground_award_assists.choose_offender": "0x498",
|
||||
"iground_on_dead": "0x4279a0",
|
||||
"is_slot_ready_at_host": "0x17a9da0",
|
||||
"mission_allies_country": "0x127d240",
|
||||
"mission_allies_country.allies_country": "0xd0",
|
||||
"mission_arcade_country": "0x127d1ca",
|
||||
"mission_arcade_country.arcade_country": "0x1d0",
|
||||
"mission_axis_country": "0x127d258",
|
||||
"mission_axis_country.axis_country": "0xc8",
|
||||
"mission_custom_bots": "0x1274ccd",
|
||||
"mission_custom_bots.custom_bots": "0x718",
|
||||
"mission_score_params": "0x12734a2",
|
||||
"mission_score_params.custom_score_params": "0x6d8",
|
||||
"mission_settings_load": "0x126b4e0",
|
||||
"mission_vars_data": "0x11c12e6",
|
||||
"mission_vars_data.data": "0x40",
|
||||
"mission_vars_step": "0x11c1f70",
|
||||
"mission_vars_step.name": "-0x8",
|
||||
"mission_vars_step.stride": "0x20",
|
||||
"mission_vars_value": "0x11c1f96",
|
||||
"mission_vars_value.value": "0x8",
|
||||
"mission_vars_walk": "0x11c1f44",
|
||||
"mission_vars_walk.count": "0x50",
|
||||
"mission_vars_walk.entry_bias": "0x8",
|
||||
"mp_chat": "0x5be432",
|
||||
"mp_chat.mp_chat": "0x1f0",
|
||||
"mp_construct_local": "0x5be660",
|
||||
"mp_construct_local.mp_chat_host": "0xf8",
|
||||
"mp_construct_local.mp_is_host": "0x60",
|
||||
"mp_init_chat": "0x5be3a0",
|
||||
"mp_team_countries": "0x11b498f",
|
||||
"mp_team_countries.team1_countries": "0x150",
|
||||
"mp_team_countries.team2_countries": "0x170",
|
||||
"mplayer_add_score": "0x59ffe0",
|
||||
"mplayer_clear_before_lobby": "0x59a390",
|
||||
"mplayer_controlled_unit": "0x5998d0",
|
||||
"mplayer_gui_state": "0x1565c61",
|
||||
"mplayer_gui_state.gui_state": "0x640",
|
||||
"mplayer_init_matching": "0x59f370",
|
||||
"mplayer_matching": "0x59f66f",
|
||||
"mplayer_matching.match_team": "0x4",
|
||||
"mplayer_matching.mp_team": "0x228",
|
||||
"mplayer_matching.mp_user_id": "0xb8",
|
||||
"mplayer_score": "0x5a001d",
|
||||
"mplayer_score.score": "0x8f8",
|
||||
"mplayer_stat_sync": "0x5a0308",
|
||||
"mplayer_stat_sync.dirty": "0xa10",
|
||||
"mplayer_stat_sync.payload": "0xa30",
|
||||
"mplayer_support_unit": "0x59e74c",
|
||||
"mplayer_support_unit.eid": "0xb58",
|
||||
"mplayer_support_unit.unit": "0xb50",
|
||||
"mplayer_unit_eid": "0x129899b",
|
||||
"mplayer_unit_eid.controlled_eid": "0x880",
|
||||
"mplayer_unit_eid.unit_eid": "0x850",
|
||||
"mplayer_update": "0x59df80",
|
||||
"mplayer_used_spares": "0x59ae12",
|
||||
"mplayer_used_spares.used_spares": "0x520",
|
||||
"namemap_add_name_id": "0xed4b0",
|
||||
"net_mark_dirty": "0x3112040",
|
||||
"offender_assist": "0x465e36",
|
||||
"offender_assist.assist_sent": "0x148",
|
||||
"offender_fields": "0x465dd2",
|
||||
"offender_fields.army": "0x1c",
|
||||
"offender_fields.pid": "0x20",
|
||||
"offender_fields.uid": "0x58",
|
||||
"offender_fields.unit_army": "0x1010",
|
||||
"on_unit_dead_once": "0xe5f1d0",
|
||||
"on_unit_dead_once.skip_kill": "0x3058",
|
||||
"refl_bomb_fuse": "0xff5e23",
|
||||
"refl_bomb_fuse.bomb_fuse": "0xe4",
|
||||
"refl_ctor": "0xcd0c00",
|
||||
"refl_dtor": "0x5494d0",
|
||||
"refl_flags": "0xff5d7a",
|
||||
"refl_flags.flags": "0xd0",
|
||||
"refl_names": "0x549552",
|
||||
"refl_names.custom_skin": "0x68",
|
||||
"refl_names.skin": "0x60",
|
||||
"refl_names.unit": "0x50",
|
||||
"refl_names.weapon": "0x58",
|
||||
"refl_objects": "0x5494f5",
|
||||
"refl_objects.attachables": "0x90",
|
||||
"refl_objects.bullets": "0x190",
|
||||
"refl_objects.custom_preset": "0xb0",
|
||||
"refl_objects.decals": "0x70",
|
||||
"refl_objects.disabled_mods": "0x140",
|
||||
"refl_objects.enabled_mods": "0xf0",
|
||||
"refl_stdmem": "0x54955b",
|
||||
"refl_stdmem.stdmem": "0x8036b98",
|
||||
"refl_targeting": "0xff5dae",
|
||||
"refl_targeting.gun_convergence": "0xdc",
|
||||
"refl_vertical_targeting": "0xff5dee",
|
||||
"refl_vertical_targeting.vertical_targeting": "0xe0",
|
||||
"respawn_spawn": "0xc7022a",
|
||||
"respawn_spawn.resp_base_id": "0xbd8",
|
||||
"respawn_spawn.spawn_delay_a": "0xbf4",
|
||||
"respawn_spawn.spawn_pos_x": "0xbfc",
|
||||
"respawn_spawn.spawn_pos_y": "0xc00",
|
||||
"respawn_spawn.spawn_pos_z": "0xc04",
|
||||
"score_msg_blk_ctor": "0x18a398c",
|
||||
"score_msg_blk_ctor.call": "0x30a1fa0",
|
||||
"score_msg_blk_dtor": "0x18a3e80",
|
||||
"score_msg_blk_dtor.call": "0x30a2a00",
|
||||
"score_msg_blk_set_int": "0x18a3a58",
|
||||
"score_msg_blk_set_int.call": "0x30a40d0",
|
||||
"score_msg_blk_set_str": "0x18a3a24",
|
||||
"score_msg_blk_set_str.call": "0x30a38f0",
|
||||
"score_msg_blk_to_owned": "0x18a3a3f",
|
||||
"score_msg_blk_to_owned.call": "0x30a8860",
|
||||
"score_msg_exp_class": "0x18a3b09",
|
||||
"score_msg_exp_class.exp_class": "0x38",
|
||||
"score_msg_exp_class.unit_info": "0x1020",
|
||||
"score_msg_hud_queue": "0x18a3e2b",
|
||||
"score_msg_hud_queue.call": "0x180bd80",
|
||||
"score_msg_hud_queue.queue": "0xb10",
|
||||
"scoreboard_rows": "0x1298790",
|
||||
"sem_change_aircraft_send": "0xccf860",
|
||||
"set_controlled_unit": "0x599780",
|
||||
"set_owning_mplayer": "0xfd2ac0",
|
||||
"set_owning_mplayer.mp_pid": "0x8",
|
||||
"set_player_gui_state": "0x1565b60",
|
||||
"shell_explode": "0xbeb990",
|
||||
"shell_instant_win": "0x14391cd",
|
||||
"shell_instant_win.instant_win": "0x70",
|
||||
"shell_instant_win.record": "0x18",
|
||||
"shell_launch": "0x1437ae0",
|
||||
"sq_local_country": "0x17a5fd0",
|
||||
"sq_local_country.mission_settings": "0x7bc64b8",
|
||||
"stat_ai_ground_kills": "0x1123cbe",
|
||||
"stat_ai_ground_kills.field": "0x9e6",
|
||||
"stat_ai_kills": "0x1123ca7",
|
||||
"stat_ai_kills.field": "0x9e4",
|
||||
"stat_ai_naval_kills": "0x1123cd5",
|
||||
"stat_ai_naval_kills.field": "0x9e8",
|
||||
"stat_air_severe": "0x129923c",
|
||||
"stat_air_severe.field": "0xa06",
|
||||
"stat_assists": "0x1123cec",
|
||||
"stat_assists.field": "0x9ec",
|
||||
"stat_award_damage": "0x1123d6b",
|
||||
"stat_award_damage.field": "0xa00",
|
||||
"stat_capture_zone": "0x1123d1a",
|
||||
"stat_capture_zone.field": "0x9ee",
|
||||
"stat_deaths": "0x1123d03",
|
||||
"stat_deaths.field": "0x9dc",
|
||||
"stat_ground_kills": "0x1123c4b",
|
||||
"stat_ground_kills.field": "0x9de",
|
||||
"stat_human_kills": "0x1123c62",
|
||||
"stat_human_kills.field": "0x9e0",
|
||||
"stat_kills": "0x1123c34",
|
||||
"stat_kills.field": "0x9d8",
|
||||
"stat_naval_kills": "0x1123c79",
|
||||
"stat_naval_kills.field": "0x9e2",
|
||||
"stat_score": "0x1123d47",
|
||||
"stat_score.fallback": "0x2d8",
|
||||
"stat_score.score": "0x8f8",
|
||||
"stat_ship_severe": "0x1299268",
|
||||
"stat_ship_severe.field": "0xa08",
|
||||
"stat_team_kills": "0x1123c90",
|
||||
"stat_team_kills.field": "0x9da",
|
||||
"str_hash_fnv1": "0x21b670",
|
||||
"unit_change_aircraft": "0xff5a00",
|
||||
"unit_crew_skills": "0x485df0",
|
||||
"unit_crew_skills.crew_skills": "0x10a8",
|
||||
"unit_info_name": "0xff5c85",
|
||||
"unit_info_name.info_name": "0x10",
|
||||
"unit_info_name.unit_info": "0x1020",
|
||||
"unit_mplayer": "0xfd2dc8",
|
||||
"unit_mplayer.unit_mplayer": "0xf98",
|
||||
"unit_severe": "0xe5f297",
|
||||
"unit_severe.severe_idx": "0x6b0",
|
||||
"unit_severe.severe_pid": "0x6d0",
|
||||
"unit_severe.severe_uid": "0x708",
|
||||
"unit_spawn_state": "0x1049a81",
|
||||
"unit_spawn_state.resp_base_id": "0xbd8",
|
||||
"unit_spawn_state.spawn_delay_a": "0xbf4",
|
||||
"unit_spawn_state.spawn_delay_b": "0xbf8",
|
||||
"unit_spawn_state.unit_mplayer": "0xf98",
|
||||
"unit_type": "0xff5bef",
|
||||
"unit_type.unit_type": "0x8c"
|
||||
},
|
||||
"unavailable": {}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { cp, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { Arch, build, Platform } from 'electron-builder';
|
||||
import { launcherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import { launcherReleaseFiles, portableLauncherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import { formatManifest, MANIFEST_FILE, PATCH_PACK_FORMAT, recordedGameVersions } from '../packages/patcher/src/index.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
@@ -97,8 +97,13 @@ async function cleanInstallerOutput(version: string): Promise<void> {
|
||||
if (relative(output, root) !== '') throw new Error('The installer output directory is redirected.');
|
||||
|
||||
const { installer, manifest, signature } = launcherReleaseFiles(version);
|
||||
const portable = portableLauncherReleaseFiles(version);
|
||||
const legacy = `WTOffline Launcher Setup ${version}.exe`;
|
||||
const names = [installer, installer + '.blockmap', legacy, legacy + '.blockmap', manifest, signature, 'win-unpacked'];
|
||||
const names = [
|
||||
installer, installer + '.blockmap',
|
||||
portable.archive, portable.manifest, portable.signature,
|
||||
legacy, legacy + '.blockmap', manifest, signature, 'win-unpacked',
|
||||
];
|
||||
const artifacts = [];
|
||||
for (const name of names) {
|
||||
const path = join(root, name);
|
||||
@@ -160,10 +165,55 @@ async function main(): Promise<void> {
|
||||
},
|
||||
});
|
||||
for (const artifact of artifacts) console.info(artifact);
|
||||
const portablePath = await packagePortableArchive(output, manifest.version);
|
||||
console.info(portablePath);
|
||||
} finally {
|
||||
const actual = await realpath(stage);
|
||||
if (actual === stage && dirname(actual) === temp) await rm(stage, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function listRelativeFiles(root: string): Promise<string[]> {
|
||||
const files: string[] = [];
|
||||
const pending = [root];
|
||||
while (pending.length) {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const fullPath = join(folder, entry.name);
|
||||
if (entry.isDirectory()) pending.push(fullPath);
|
||||
else if (entry.isFile()) files.push(relative(root, fullPath).split(sep).join('/'));
|
||||
}
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Package win-unpacked into the portable archive with a portable marker and an inventory of
|
||||
* launcher-owned files so portable in-place updates only replace launcher files and never remove
|
||||
* unrelated user files in the extraction folder.
|
||||
*/
|
||||
async function packagePortableArchive(outputFolder: string, version: string): Promise<string> {
|
||||
const unpacked = join(outputFolder, 'win-unpacked');
|
||||
const resources = join(unpacked, 'resources');
|
||||
const markerPath = join(resources, 'portable-mode');
|
||||
const inventoryPath = join(resources, 'portable-files.json');
|
||||
const portable = join(outputFolder, portableLauncherReleaseFiles(version).archive);
|
||||
try {
|
||||
await writeFile(markerPath, 'portable\n', 'utf8');
|
||||
await writeFile(inventoryPath, '', 'utf8');
|
||||
const ownedFiles = await listRelativeFiles(unpacked);
|
||||
await writeFile(inventoryPath, `${JSON.stringify({ format: 1, version, files: ownedFiles }, null, 2)}\n`, 'utf8');
|
||||
const unpackedGlob = join(unpacked, '*').replaceAll("'", "''");
|
||||
const destination = portable.replaceAll("'", "''");
|
||||
execFileSync('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-Command',
|
||||
`Compress-Archive -Path '${unpackedGlob}' -DestinationPath '${destination}' -Force`,
|
||||
], { cwd: repository, stdio: 'inherit', windowsHide: true });
|
||||
return portable;
|
||||
} finally {
|
||||
await rm(markerPath, { force: true }).catch(() => undefined);
|
||||
await rm(inventoryPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -1,15 +1,21 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { access, readFile, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher';
|
||||
import { installerDigest, launcherSignaturePayload } from '../apps/launcher/src/main/services/app-update/installer-integrity.ts';
|
||||
import { launcherReleaseFiles, LauncherReleaseManifest } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import {
|
||||
installerDigest, launcherSignaturePayload, portableSignaturePayload,
|
||||
} from '../apps/launcher/src/main/services/app-update/installer-integrity.ts';
|
||||
import {
|
||||
launcherReleaseFiles, LauncherReleaseManifest,
|
||||
portableLauncherReleaseFiles, PortableReleaseManifest,
|
||||
} from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { version } = JSON.parse(await readFile(join(repository, 'apps', 'launcher', 'package.json'), 'utf8')) as { version: string };
|
||||
const files = launcherReleaseFiles(version);
|
||||
const installer = join(repository, 'build', 'windows-installer', files.installer);
|
||||
const outputFolder = join(repository, 'build', 'windows-installer');
|
||||
const installer = join(outputFolder, files.installer);
|
||||
const privateKey = process.env['PATCH_SIGNING_KEY'];
|
||||
const publicKey = packSigningPublicKey();
|
||||
if (!privateKey || !publicKey) throw new Error('The project signing key pair is required.');
|
||||
@@ -29,6 +35,38 @@ async function main(): Promise<void> {
|
||||
await writeFile(join(folder, files.manifest), bytes);
|
||||
await writeFile(join(folder, files.signature), signature, 'utf8');
|
||||
for (const file of Object.values(files)) console.info(join(folder, file));
|
||||
|
||||
// Sign the portable archive with a separate manifest so older launchers whose installer manifest
|
||||
// schema is strict keep validating releases without error.
|
||||
const portableFiles = portableLauncherReleaseFiles(version);
|
||||
const portableArchive = join(folder, portableFiles.archive);
|
||||
if (await fileExists(portableArchive)) {
|
||||
const portableManifest = PortableReleaseManifest.parse({
|
||||
kind: 'wto-launcher-portable-release',
|
||||
format: 1,
|
||||
platform: 'win32-x64',
|
||||
version,
|
||||
...await installerDigest(portableArchive),
|
||||
});
|
||||
const portableBytes = Buffer.from(JSON.stringify(portableManifest, null, 2) + '\n', 'utf8');
|
||||
const portablePayload = portableSignaturePayload(portableBytes);
|
||||
const portableSig = signEd25519(portablePayload, privateKey);
|
||||
if (!verifyEd25519(portablePayload, portableSig, publicKey)) {
|
||||
throw new Error('The portable release key does not match the bundled public key.');
|
||||
}
|
||||
await writeFile(join(folder, portableFiles.manifest), portableBytes);
|
||||
await writeFile(join(folder, portableFiles.signature), portableSig, 'utf8');
|
||||
for (const file of Object.values(portableFiles)) console.info(join(folder, file));
|
||||
}
|
||||
}
|
||||
|
||||
async function fileExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
Reference in new issue
Block a user