diff --git a/.github/workflows/launcher-release.yml b/.github/workflows/launcher-release.yml deleted file mode 100644 index 55821e4..0000000 --- a/.github/workflows/launcher-release.yml +++ /dev/null @@ -1,97 +0,0 @@ -# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release -# tagged v. The launcher's update check reads v 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.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" diff --git a/.github/workflows/patch-pack.yml b/.github/workflows/patch-pack.yml deleted file mode 100644 index 32dc233..0000000 --- a/.github/workflows/patch-pack.yml +++ /dev/null @@ -1,78 +0,0 @@ -# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish -# it as a GitHub prerelease tagged patches-, where the launcher looks for it. -# -# Start it either way: -# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29 -# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen -# branch's latest commit. -# The signing key comes from the repository secret PATCH_SIGNING_KEY -# (scripts/generate-patch-signing-key.ts). -name: Adaptation pack - -on: - push: - tags: ['patches-*'] - workflow_dispatch: - inputs: - version: - description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N' - required: true - type: string - draft: - description: 'Keep the signed prerelease as a draft for editing before publication' - type: boolean - default: false - -permissions: - contents: write - -jobs: - release: - runs-on: ubuntu-latest - env: - # Packing needs no Electron binary. - ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }} - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: 24 - cache: npm - - - run: npm ci - - - name: Pack and sign - env: - PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }} - run: | - if [ -n "$VERSION" ]; then - node scripts/build-patch-pack.ts --version "$VERSION" --out dist - else - # The version comes from the pushed tag (GITHUB_REF_NAME). - node scripts/build-patch-pack.ts --out dist - fi - - - name: Create the prerelease - env: - GH_TOKEN: ${{ github.token }} - DRAFT: ${{ inputs.draft || false }} - run: | - manifest=$(ls dist/*.manifest.json) - field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; } - version=$(field version) - printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \ - "$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md - release_flags=(--prerelease) - if [ "$DRAFT" = 'true' ]; then - release_flags+=(--draft) - fi - gh release create "patches-$version" \ - "dist/wtoffline-patches-$version.zip" \ - "dist/wtoffline-patches-$version.zip.sig" \ - "dist/wtoffline-patches-$version.manifest.json" \ - "${release_flags[@]}" \ - --title "Adaptation pack $version" \ - --notes-file dist/notes.md \ - --target "$GITHUB_SHA" diff --git a/packages/patcher/src/patch-pack/manifest.ts b/packages/patcher/src/patch-pack/manifest.ts index 2ae42bf..3630c43 100644 --- a/packages/patcher/src/patch-pack/manifest.ts +++ b/packages/patcher/src/patch-pack/manifest.ts @@ -3,9 +3,8 @@ * numbers it carries. * * An adaptation pack is a patch set (patch-set.ts) released on its own, so that a new game build - * can be adapted without a new release of the offline version. It is published as a GitHub - * release tagged `patches-` with two files: the zip and its Ed25519 signature - * (signature.ts). + * can be adapted without a new release of the offline version. A `patches-` + * release holds the zip, its Ed25519 signature (signature.ts), and a copy of the manifest. * * format layout of the pack; a launcher uses only formats it knows * version pack version, `YYYY.MM.DD` or `YYYY.MM.DD.N` for a second pack on a day diff --git a/packages/patcher/tuning/release-channels.jsonc b/packages/patcher/tuning/release-channels.jsonc index 69ae20a..f74ba25 100644 --- a/packages/patcher/tuning/release-channels.jsonc +++ b/packages/patcher/tuning/release-channels.jsonc @@ -4,9 +4,7 @@ // launcher tags use `v` and pack tags use `patches-`. "primary_source": "https://dl.wto-project.net", // Default ordered fallback sources tried when the primary source is unreachable. - "fallback_sources": [ - "https://github.com/N0VAN0M4LY/WT-Offline" - ], + "fallback_sources": [], // Entries per request (GitHub allows up to 100) and pages per shared check. "release_page_size": 30, "max_release_pages": 5, diff --git a/scripts/build-patch-pack.ts b/scripts/build-patch-pack.ts index 1d9affd..2f25d7b 100644 --- a/scripts/build-patch-pack.ts +++ b/scripts/build-patch-pack.ts @@ -3,11 +3,10 @@ * * node scripts/build-patch-pack.ts --version [--out ] [--min-app-version ] [--unsigned] * - * The private key comes from the environment variable PATCH_SIGNING_KEY (PEM text), as the release - * workflow .github/workflows/patch-pack.yml passes it from the GitHub secret of the same name. + * The private key comes from the environment variable PATCH_SIGNING_KEY (PEM text). * --unsigned writes the zip without a signature, for a look at the contents only: the launcher - * refuses an unsigned pack. In GitHub Actions --version defaults to the pushed tag - * (`patches-`). + * refuses an unsigned pack. If omitted, --version can be read from a `patches-` tag + * in GITHUB_REF_NAME. * * Only committed files go into a pack: the script refuses when patches/ has uncommitted changes or * untracked files, so a version record is released only after it was committed (it is committed @@ -105,7 +104,7 @@ function main(): number { return 0; } -/** In GitHub Actions, the version of the pushed `patches-*` tag. */ +/** The pack version supplied by GITHUB_REF_NAME. */ function tagVersion(): string | undefined { const ref = process.env['GITHUB_REF_NAME']; return ref ? (packVersionOfTag(ref) ?? undefined) : undefined; diff --git a/scripts/gitea/release.ts b/scripts/gitea/release.ts new file mode 100644 index 0000000..142bfa8 --- /dev/null +++ b/scripts/gitea/release.ts @@ -0,0 +1,162 @@ +import { createHash } from 'node:crypto'; +import { createReadStream, openAsBlob } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import { basename } from 'node:path'; + +interface Attachment { + readonly name: string; + readonly size: number; + readonly uuid: string; + readonly digest?: string; +} + +export interface GiteaRelease { + readonly id: number; + readonly tag_name: string; + readonly draft: boolean; + readonly prerelease: boolean; + readonly assets: readonly Attachment[] | null; +} + +interface DraftRelease { + readonly tag_name: string; + readonly target_commitish: string; + readonly name: string; + readonly body: string; + readonly prerelease: boolean; +} + +interface GitRef { + readonly ref: string; + readonly object: { readonly sha: string }; +} + +const REQUEST_TIMEOUT_MS = 30_000; +const TRANSFER_TIMEOUT_MS = 15 * 60_000; + +export class GiteaReleaseClient { + readonly #base: URL; + readonly #api: URL; + readonly #token: string; + + constructor(base: string, repository: string, token: string) { + const url = new URL(base); + const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname); + if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || + url.username || url.password || url.search || url.hash) { + throw new Error('GITEA_URL must be a clean HTTPS or loopback HTTP URL.'); + } + if (!/^[\w-][\w.-]*\/[\w-][\w.-]*$/.test(repository)) { + throw new Error('GITEA_REPOSITORY must be in owner/repository form.'); + } + url.pathname = `${url.pathname.replace(/\/+$/, '')}/`; + this.#base = url; + this.#api = new URL(`api/v1/repos/${repository}/`, url); + this.#token = token; + } + + async verifyTag(tag: string, objectId: string): Promise { + const url = new URL(`git/refs/tags/${encodeURIComponent(tag)}`, this.#api); + const response = await this.#request(url); + const result = await response.json() as GitRef | GitRef[]; + const refs = Array.isArray(result) ? result : [result]; + if (!refs.some(({ ref, object }) => ref === `refs/tags/${tag}` && object.sha === objectId)) { + throw new Error(`The local tag ${tag} differs from the tag on Gitea.`); + } + } + + async findRelease(tag: string): Promise { + // The list includes drafts when the token has repository write access. + for (let page = 1; ; page += 1) { + const url = new URL(`releases?limit=50&page=${page}`, this.#api); + const response = await this.#request(url); + const releases = await response.json() as GiteaRelease[]; + const release = releases.find((entry) => entry.tag_name === tag); + if (release || !/;\s*rel="next"/i.test(response.headers.get('link') ?? '')) { + return release; + } + } + } + + async createDraft(draft: DraftRelease): Promise { + return this.#writeRelease('POST', 'releases', { ...draft, draft: true }); + } + + async publish(id: number): Promise { + const release = await this.#writeRelease('PATCH', `releases/${id}`, { draft: false }); + if (release.draft) throw new Error('Gitea kept the release as a draft.'); + } + + async syncAttachments(release: GiteaRelease, paths: readonly string[]): Promise { + const missing: string[] = []; + for (const path of paths) { + const name = basename(path); + const matches = (release.assets ?? []).filter((attachment) => attachment.name === name); + if (matches.length > 1) throw new Error(`Gitea has duplicate attachments named ${name}.`); + const existing = matches[0]; + if (existing) await this.#verifyAttachment(existing, path); + else missing.push(path); + } + + if (missing.length && !release.draft) { + throw new Error(`Published Gitea release ${release.tag_name} is missing expected attachments.`); + } + for (const path of missing) { + const name = basename(path); + const file = await openAsBlob(path, { type: 'application/octet-stream' }); + const form = new FormData(); + form.set('attachment', file, name); + const url = new URL(`releases/${release.id}/assets`, this.#api); + console.info(`Uploading ${name} to Gitea...`); + const response = await this.#request(url, { method: 'POST', body: form }, TRANSFER_TIMEOUT_MS); + const uploaded = await response.json() as Attachment; + if (uploaded.name !== name || uploaded.size !== file.size) { + throw new Error(`Gitea returned unexpected attachment metadata for ${name}.`); + } + } + } + + async #verifyAttachment(attachment: Attachment, path: string): Promise { + if ((await stat(path)).size !== attachment.size) { + throw new Error(`Gitea already has different bytes for ${attachment.name}.`); + } + const localDigest = await digest(createReadStream(path)); + let remoteDigest = attachment.digest; + if (!remoteDigest) { + // Older Gitea versions omit the digest. Read back through this same server. + const url = new URL(`attachments/${encodeURIComponent(attachment.uuid)}`, this.#base); + const response = await this.#request(url, {}, TRANSFER_TIMEOUT_MS); + if (!response.body) throw new Error(`Gitea returned no bytes for ${attachment.name}.`); + remoteDigest = await digest(response.body); + } + if (localDigest !== remoteDigest) throw new Error(`Gitea already has different bytes for ${attachment.name}.`); + console.info(`Verified existing Gitea attachment ${attachment.name}.`); + } + + async #writeRelease(method: 'POST' | 'PATCH', path: string, payload: object): Promise { + const response = await this.#request(new URL(path, this.#api), { + method, + body: JSON.stringify(payload), + headers: { 'content-type': 'application/json' }, + }); + return await response.json() as GiteaRelease; + } + + async #request(url: URL, init: RequestInit = {}, timeout = REQUEST_TIMEOUT_MS): Promise { + const headers = new Headers(init.headers); + headers.set('authorization', `Bearer ${this.#token}`); + const response = await fetch(url, { ...init, headers, redirect: 'error', signal: AbortSignal.timeout(timeout) }); + if (!response.ok) { + const error = await response.json().catch(() => null) as { message?: string } | null; + const detail = error?.message ? `: ${error.message}` : ''; + throw new Error(`Gitea ${init.method ?? 'GET'} ${url.pathname} failed with HTTP ${response.status}${detail}`); + } + return response; + } +} + +async function digest(chunks: AsyncIterable): Promise { + const hash = createHash('sha256'); + for await (const chunk of chunks) hash.update(chunk); + return `sha256:${hash.digest('hex')}`; +} diff --git a/scripts/publish-r2-releases.ts b/scripts/publish-r2-releases.ts index 1800495..9a2aedb 100644 --- a/scripts/publish-r2-releases.ts +++ b/scripts/publish-r2-releases.ts @@ -16,6 +16,7 @@ * --repo-url Source repository URL linked on index.html (default: R2_REPO_URL or https://git.wto-project.net) * --no-merge-remote Do not merge previously published tags from R2 when uploading * --upload Sync staged files, releases feed, and index.html to Cloudflare R2 + * --immutable-assets Refuse to overwrite any versioned R2 object that has different bytes * --force Re-upload files even if matching size and SHA-256 already exist on R2 * --dry-run Show what would be staged/uploaded without modifying R2 * @@ -74,6 +75,7 @@ async function main(): Promise { 'repo-url': { type: 'string' }, 'no-merge-remote': { type: 'boolean', default: false }, upload: { type: 'boolean', default: false }, + 'immutable-assets': { type: 'boolean', default: false }, force: { type: 'boolean', default: false }, 'dry-run': { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false }, @@ -84,6 +86,7 @@ async function main(): Promise { printUsage(); return; } + if (values.force && values['immutable-assets']) throw new Error('Use either --force or --immutable-assets.'); const publicUrl = (values['public-url'] ?? process.env['R2_PUBLIC_URL'] ?? patchPackTuning().primarySource).replace(/\/+$/, ''); const repoUrl = (values['repo-url'] ?? process.env['R2_REPO_URL'] ?? DEFAULT_REPO_URL).replace(/\/+$/, ''); @@ -146,7 +149,11 @@ async function main(): Promise { } if (r2) { - await uploadToR2(r2, outDir, feedJson, html, values.force, values['dry-run']); + await uploadToR2(r2, outDir, feedJson, html, { + force: values.force, + dryRun: values['dry-run'], + immutableAssets: values['immutable-assets'], + }); } } @@ -310,8 +317,7 @@ async function uploadToR2( outDir: string, feedJson: string, html: string, - force: boolean, - dryRun: boolean, + { force, dryRun, immutableAssets }: { force: boolean; dryRun: boolean; immutableAssets: boolean }, ): Promise { const filesRoot = join(outDir, 'files'); const assetFiles = existsSync(filesRoot) ? await collectFiles(filesRoot) : []; @@ -328,6 +334,7 @@ async function uploadToR2( console.info(`Skipped unchanged ${relative}`); continue; } + if (head.exists && immutableAssets) throw new Error(`R2 already has a different object at ${relative}.`); } if (dryRun) { @@ -455,6 +462,7 @@ function printUsage(): void { ' --repo-url Source repo URL shown on index.html (default: https://git.wto-project.net)', ' --no-merge-remote Do not merge existing releases from R2 before uploading', ' --upload Upload staged files, releases feed, and index.html to R2', + ' --immutable-assets Refuse to overwrite any versioned R2 object that has different bytes', ' --force Upload assets even when size and SHA-256 already match on R2', ' --dry-run Preview actions without writing feed or uploading to R2', ].join('\n')); diff --git a/scripts/release-vps.ts b/scripts/release-vps.ts new file mode 100644 index 0000000..204ba05 --- /dev/null +++ b/scripts/release-vps.ts @@ -0,0 +1,211 @@ +/** Build a tagged release on the Gitea host and distribute its signed artifacts. */ +import { execFileSync, execSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { access, copyFile, mkdir, mkdtemp, open, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises'; +import { join, relative, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; +import { packFileNames, packVersionOfTag } from '../packages/patcher/src/patch-pack/manifest.ts'; +import { GiteaReleaseClient } from './gitea/release.ts'; +import type { ReleaseEntry } from './r2/download-page.ts'; + +const REPOSITORY = resolve(import.meta.dirname, '..'); +const RELEASES = join(REPOSITORY, 'build', 'vps-releases'); +const USAGE = `Usage: node scripts/release-vps.ts [--publish] + +Run from a clean checkout of the tag already pushed to Gitea. +Prepare a signed Gitea draft by default. With --publish, sync R2 and publish the draft. +Set GITEA_TOKEN and PATCH_SIGNING_KEY in the release environment, plus the R2 credentials for --publish.`; + +interface ReleaseBuild { + readonly tag: string; + readonly version: string; + readonly commit: string; + readonly pack: boolean; + readonly names: readonly string[]; +} + +// Keep release credentials out of dependency installation, type checks and builders. +const buildEnv = Object.fromEntries(Object.entries(process.env).filter(([name]) => + !/^(?:GITEA_TOKEN$|PATCH_SIGNING_KEY$|R2_)/i.test(name))); + +async function main(): Promise { + const { positionals, values } = parseArgs({ + allowPositionals: true, + options: { publish: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } }, + }); + if (values.help) { + console.info(USAGE); + return; + } + + const [tag] = positionals; + const packVersion = tag ? packVersionOfTag(tag) : null; + const launcherVersion = tag?.match(/^v(\d+\.\d+\.\d+)$/)?.[1]; + const version = packVersion ?? launcherVersion; + if (positionals.length !== 1 || !tag || !version) throw new Error(USAGE); + const pack = packVersion !== null; + + const gitea = new GiteaReleaseClient( + process.env['GITEA_URL'] ?? 'http://127.0.0.1:3000', + process.env['GITEA_REPOSITORY'] ?? 'Sh3ll_in_Sh3ll/WT-Offline', + requiredEnv('GITEA_TOKEN'), + ); + const commit = taggedCommit(tag); + const tagObject = git(['rev-parse', '--verify', `refs/tags/${tag}`]); + await gitea.verifyTag(tag, tagObject); + + await mkdir(RELEASES, { recursive: true }); + if (relative(RELEASES, await realpath(RELEASES)) !== '') throw new Error('The VPS releases directory is redirected.'); + const lockPath = join(RELEASES, 'release.lock'); + const lock = await open(lockPath, 'wx').catch((error: NodeJS.ErrnoException) => { + if (error.code === 'EEXIST') throw new Error(`A VPS release is already running or left a lock at ${lockPath}.`); + throw error; + }); + try { + await lock.writeFile(`${process.pid}\n`); + const folder = join(RELEASES, tag); + const prepared = existsSync(folder); + if (prepared && (await readFile(join(folder, 'source-commit'), 'utf8')).trim() !== commit) { + throw new Error(`The saved artifacts for ${tag} came from a different commit.`); + } + let release = await gitea.findRelease(tag); + if (!prepared && release && (!release.draft || release.assets?.length)) { + throw new Error(`Gitea already has a release for ${tag}. Restore its prepared artifacts to ${folder}.`); + } + if (release && release.prerelease !== pack) throw new Error(`Gitea release ${tag} has a different prerelease setting.`); + const signingKey = prepared ? null : requiredEnv('PATCH_SIGNING_KEY'); + + console.info(`${tag} at ${commit}: ${prepared ? 'using saved artifacts' : 'preparing signed artifacts'}.`); + npm('ci', { ...buildEnv, ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }); + const build = { tag, version, commit, pack, names: await artifactNames(version, pack) }; + const entry = signingKey ? await prepare(build, signingKey, folder) : await stage(build, folder); + + if (taggedCommit(tag) !== commit) throw new Error('The checkout changed during release preparation.'); + await gitea.verifyTag(tag, tagObject); + release ??= await gitea.createDraft({ + tag_name: tag, + target_commitish: commit, + name: entry.name, + body: entry.body, + prerelease: entry.prerelease, + }); + const files = build.names.map((name) => join(artifactFolder(folder, tag), name)); + await gitea.syncAttachments(release, files); + + if (!values.publish) { + console.info(`Gitea release ${tag} is ${release.draft ? 'ready for draft review' : 'published'}.`); + return; + } + await withTemporaryFolder('r2-', async (output) => { + const r2Env = Object.fromEntries(Object.entries(process.env).filter(([name]) => /^R2_/i.test(name))); + runNode('publish-r2-releases.ts', [ + ...r2Arguments(build, folder, output), '--upload', '--immutable-assets', + ], { ...buildEnv, ...r2Env }); + }); + if (release.draft) await gitea.publish(release.id); + console.info(`Published ${tag} on Gitea and R2.`); + } finally { + await lock.close(); + await unlink(lockPath); + } +} + +async function artifactNames(version: string, pack: boolean): Promise { + if (pack) return Object.values(packFileNames(version)); + const packagePath = join(REPOSITORY, 'apps', 'launcher', 'package.json'); + const manifest = JSON.parse(await readFile(packagePath, 'utf8')) as { version: string }; + if (manifest.version !== version) throw new Error(`Launcher version ${manifest.version} does not match v${version}.`); + await access(join(REPOSITORY, '.github', 'release-notes', `v${version}.md`)); + const { launcherReleaseFiles, portableLauncherReleaseFiles } = await import('../apps/launcher/src/shared/schemas/app-update.ts'); + return [...Object.values(launcherReleaseFiles(version)), ...Object.values(portableLauncherReleaseFiles(version))]; +} + +async function prepare(build: ReleaseBuild, signingKey: string, folder: string): Promise { + return withTemporaryFolder('prepare-', async (temp) => { + const assets = artifactFolder(temp, build.tag); + await mkdir(assets, { recursive: true }); + const signingEnv = { ...buildEnv, PATCH_SIGNING_KEY: signingKey }; + if (build.pack) { + runNode('build-patch-pack.ts', ['--version', build.version, '--out', assets], signingEnv); + } else { + execFileSync(process.execPath, ['node_modules/electron/install.js'], { + cwd: REPOSITORY, stdio: 'inherit', env: { ...buildEnv, ELECTRON_SKIP_BINARY_DOWNLOAD: undefined }, + }); + npm('run typecheck'); + npm('run typecheck --workspace @wto/launcher'); + npm('--workspace @wto/launcher run package:win'); + runNode('sign-launcher-release.ts', [], signingEnv); + for (const name of build.names) { + await copyFile(join(REPOSITORY, 'build', 'windows-installer', name), join(assets, name)); + } + } + const entry = await stage(build, temp); + await writeFile(join(temp, 'source-commit'), `${build.commit}\n`, 'utf8'); + await rename(temp, folder); + return entry; + }); +} + +async function stage(build: ReleaseBuild, folder: string): Promise { + runNode('publish-r2-releases.ts', r2Arguments(build, folder, folder)); + const entries = JSON.parse(await readFile(join(folder, 'releases'), 'utf8')) as ReleaseEntry[]; + const entry = entries.find((candidate) => candidate.tag_name === build.tag); + if (!entry || entry.assets.length !== build.names.length || + !build.names.every((name) => entry.assets.some((asset) => asset.name === name))) { + throw new Error(`The staged release for ${build.tag} is missing expected signed files.`); + } + return entry; +} + +function r2Arguments(build: ReleaseBuild, folder: string, output: string): string[] { + const assets = artifactFolder(folder, build.tag); + return build.pack + ? ['--add-pack', join(assets, packFileNames(build.version).zip), '--out', output] + : ['--add-launcher', assets, '--out', output]; +} + +function artifactFolder(folder: string, tag: string): string { + return join(folder, 'files', tag); +} + +async function withTemporaryFolder(prefix: string, work: (folder: string) => Promise): Promise { + const folder = await mkdtemp(join(RELEASES, prefix)); + try { + return await work(folder); + } finally { + await rm(folder, { recursive: true, force: true }); + } +} + +function taggedCommit(tag: string): string { + if (git(['status', '--porcelain'])) throw new Error('Use a clean checkout for VPS releases.'); + const commit = git(['rev-parse', '--verify', 'HEAD']); + if (git(['rev-parse', '--verify', `refs/tags/${tag}^{commit}`]) !== commit) { + throw new Error(`Check out the Gitea tag ${tag} before running this script.`); + } + return commit; +} + +function git(args: string[]): string { + return execFileSync('git', args, { cwd: REPOSITORY, encoding: 'utf8', env: buildEnv }).trim(); +} + +function npm(command: 'ci' | 'run typecheck' | 'run typecheck --workspace @wto/launcher' | + '--workspace @wto/launcher run package:win', env = buildEnv): void { + execSync(`npm ${command}`, { cwd: REPOSITORY, stdio: 'inherit', env }); +} + +function runNode(script: string, args: string[], env = buildEnv): void { + execFileSync(process.execPath, [join('scripts', script), ...args], { cwd: REPOSITORY, stdio: 'inherit', env }); +} + +function requiredEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) throw new Error(`Missing ${name} in the VPS release environment.`); + return value; +} + +await main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; +});