/** * Stage verified signed launcher releases and adaptation packs into a GitHub-compatible static * distribution directory (`releases`, `index.html`, `files//...`) and optionally upload * them to Cloudflare R2 via its S3-compatible API. * * Usage: * node scripts/publish-r2-releases.ts [options] * * Options: * --add-launcher Stage signed installer (and optional portable zip) from a build folder * --add-pack Stage signed adaptation pack(s) from a folder or a specific .zip file * --notes Release notes Markdown for --add-launcher (defaults to .github/release-notes/v.md) * --remove-tag Remove a tag from the release feed * --out Local staging directory (default: build/r2-dist) * --public-url Public mirror base URL (default: R2_PUBLIC_URL or primary_source from tuning) * --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 * --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 * * R2 credentials are read from environment variables or a gitignored `.env.r2.local` file: * R2_ENDPOINT, R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY */ import { createHash } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; import { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import { basename, dirname, extname, join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; import { compareAppVersions, comparePackVersions, packFileNames, packSigningPublicKey, packVersionOfTag, parseManifest, patchPackTuning, verifyEd25519, verifyPatchPack, } from '@wto/patcher'; 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'; import { renderDownloadPage, type ReleaseAssetEntry, type ReleaseEntry } from './r2/download-page.ts'; import { R2Client, sha256 } from './r2/sigv4.ts'; const REPOSITORY = resolve(import.meta.dirname, '..'); const DEFAULT_OUT = join(REPOSITORY, 'build', 'r2-dist'); const DEFAULT_REPO_URL = 'https://git.wto-project.net/Sh3ll_in_Sh3ll/WT-Offline'; const LOCAL_ENV_FILE = join(REPOSITORY, '.env.r2.local'); const CACHE_IMMUTABLE = 'public, max-age=31536000, immutable'; const CACHE_FEED = 'public, max-age=60, must-revalidate'; async function main(): Promise { loadLocalEnv(LOCAL_ENV_FILE); const { values } = parseArgs({ options: { 'add-launcher': { type: 'string', multiple: true }, 'add-pack': { type: 'string', multiple: true }, notes: { type: 'string' }, 'remove-tag': { type: 'string', multiple: true }, out: { type: 'string', default: DEFAULT_OUT }, 'public-url': { type: 'string' }, 'repo-url': { type: 'string' }, 'no-merge-remote': { type: 'boolean', default: false }, upload: { type: 'boolean', default: false }, force: { type: 'boolean', default: false }, 'dry-run': { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h', default: false }, }, }); if (values.help) { printUsage(); return; } 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(/\/+$/, ''); const outDir = resolve(values.out); const filesRoot = join(outDir, 'files'); const publicKey = packSigningPublicKey(); if (!publicKey) throw new Error('The committed project public key (packages/patcher/keys/) is missing.'); const r2 = values.upload ? createR2Client() : null; // Start from existing local staging feed (and optionally remote R2 feed when uploading). const byTag = new Map(); if (r2 && !values['no-merge-remote']) { const remoteText = await r2.getObjectText('releases'); if (remoteText) { for (const entry of parseExistingReleases(remoteText)) byTag.set(entry.tag_name, entry); console.info(`Loaded ${byTag.size} existing release(s) from R2.`); } } const localFeedPath = join(outDir, 'releases'); if (existsSync(localFeedPath)) { for (const entry of parseExistingReleases(await readFile(localFeedPath, 'utf8'))) byTag.set(entry.tag_name, entry); } await mkdir(filesRoot, { recursive: true }); for (const folder of values['add-launcher'] ?? []) { const entry = await stageLauncherRelease(resolve(folder), filesRoot, publicUrl, publicKey, values.notes); byTag.set(entry.tag_name, entry); console.info(`Staged launcher ${entry.tag_name} (${entry.assets.length} asset(s)).`); } for (const target of values['add-pack'] ?? []) { const entries = await stageAdaptationPacks(resolve(target), filesRoot, publicUrl, publicKey); for (const entry of entries) { byTag.set(entry.tag_name, entry); console.info(`Staged adaptation pack ${entry.tag_name} (${entry.assets.length} asset(s)).`); } } for (const tag of values['remove-tag'] ?? []) { if (byTag.delete(tag)) console.info(`Removed ${tag} from release list.`); } const releases = sortReleases([...byTag.values()]); const feedJson = JSON.stringify(releases, null, 2) + '\n'; const html = renderDownloadPage({ releases, publicUrl, repoUrl, generatedAt: new Date().toISOString(), }); if (!values['dry-run']) { await writeFile(localFeedPath, feedJson, 'utf8'); await writeFile(join(outDir, 'index.html'), html, 'utf8'); console.info(`Wrote ${localFeedPath} (${releases.length} release(s)) and ${join(outDir, 'index.html')}.`); } else { console.info(`[dry-run] Would write ${releases.length} release(s) to ${localFeedPath} and index.html.`); } if (r2) { await uploadToR2(r2, outDir, feedJson, html, values.force, values['dry-run']); } } async function stageLauncherRelease( sourceDir: string, filesRoot: string, publicUrl: string, publicKey: string, notesOverride: string | undefined, ): Promise { const entries = await readdir(sourceDir); const manifestName = entries.find((name) => /^wtoffline-launcher-.+-win-x64\.manifest\.json$/.test(name)); if (!manifestName) { throw new Error(`No signed launcher manifest (wtoffline-launcher-*-win-x64.manifest.json) found in ${sourceDir}. Run scripts/sign-launcher-release.ts first.`); } const manifestBytes = await readFile(join(sourceDir, manifestName)); const manifest = LauncherReleaseManifest.parse(JSON.parse(manifestBytes.toString('utf8'))); const files = launcherReleaseFiles(manifest.version); const signatureText = await readFile(join(sourceDir, files.signature), 'utf8'); if (!verifyEd25519(launcherSignaturePayload(manifestBytes), signatureText, publicKey)) { throw new Error(`Signature verification failed for ${files.manifest}.`); } const installerPath = join(sourceDir, files.installer); const digest = await installerDigest(installerPath, manifest.size); if (digest.size !== manifest.size || digest.sha256 !== manifest.sha256) { throw new Error(`Installer digest mismatch for ${files.installer}.`); } const tag = `v${manifest.version}`; const targetDir = join(filesRoot, tag); await mkdir(targetDir, { recursive: true }); const assets: ReleaseAssetEntry[] = []; assets.push(await copyAsset(installerPath, targetDir, tag, publicUrl, manifest.sha256)); assets.push(await copyAsset(join(sourceDir, files.manifest), targetDir, tag, publicUrl)); assets.push(await copyAsset(join(sourceDir, files.signature), targetDir, tag, publicUrl)); const portableFiles = portableLauncherReleaseFiles(manifest.version); const portableManifestPath = join(sourceDir, portableFiles.manifest); if (existsSync(portableManifestPath)) { const portableBytes = await readFile(portableManifestPath); const portableManifest = PortableReleaseManifest.parse(JSON.parse(portableBytes.toString('utf8'))); if (portableManifest.version !== manifest.version) { throw new Error(`Portable manifest version ${portableManifest.version} does not match installer version ${manifest.version}.`); } const portableSig = await readFile(join(sourceDir, portableFiles.signature), 'utf8'); if (!verifyEd25519(portableSignaturePayload(portableBytes), portableSig, publicKey)) { throw new Error(`Signature verification failed for ${portableFiles.manifest}.`); } const portableArchivePath = join(sourceDir, portableFiles.archive); const portableDigest = await installerDigest(portableArchivePath, portableManifest.size); if (portableDigest.size !== portableManifest.size || portableDigest.sha256 !== portableManifest.sha256) { throw new Error(`Portable archive digest mismatch for ${portableFiles.archive}.`); } assets.push(await copyAsset(portableArchivePath, targetDir, tag, publicUrl, portableManifest.sha256)); assets.push(await copyAsset(portableManifestPath, targetDir, tag, publicUrl)); assets.push(await copyAsset(join(sourceDir, portableFiles.signature), targetDir, tag, publicUrl)); } const notesPath = notesOverride ? resolve(notesOverride) : join(REPOSITORY, '.github', 'release-notes', `${tag}.md`); const body = existsSync(notesPath) ? await readFile(notesPath, 'utf8') : ''; return { tag_name: tag, name: `WTOffline Launcher ${tag}`, draft: false, prerelease: false, published_at: new Date().toISOString(), body, assets, }; } async function stageAdaptationPacks( targetPath: string, filesRoot: string, publicUrl: string, publicKey: string, ): Promise { const info = await stat(targetPath); const zipPaths: string[] = []; if (info.isFile()) { zipPaths.push(targetPath); } else { const names = await readdir(targetPath); for (const name of names) { if (/^wtoffline-patches-.+\.zip$/.test(name)) zipPaths.push(join(targetPath, name)); } } if (zipPaths.length === 0) throw new Error(`No adaptation pack zip files found at ${targetPath}.`); const staged: ReleaseEntry[] = []; for (const zipPath of zipPaths) { const folder = dirname(zipPath); const match = /^wtoffline-patches-(.+)\.zip$/.exec(basename(zipPath)); if (!match?.[1]) throw new Error(`Unexpected adaptation pack filename: ${zipPath}`); const version = match[1]; const files = packFileNames(version); const zipBytes = await readFile(zipPath); const sigText = await readFile(join(folder, files.signature), 'utf8'); if (!verifyPatchPack(zipBytes, sigText, publicKey)) { throw new Error(`Signature verification failed for ${files.zip}.`); } const manifestText = await readFile(join(folder, files.manifest), 'utf8'); const manifest = parseManifest(manifestText); if (manifest.version !== version) { throw new Error(`Manifest version ${manifest.version} does not match pack filename ${files.zip}.`); } const tag = `patches-${version}`; const targetDir = join(filesRoot, tag); await mkdir(targetDir, { recursive: true }); const zipSha = createHash('sha256').update(zipBytes).digest('hex'); const assets: ReleaseAssetEntry[] = [ await copyAsset(zipPath, targetDir, tag, publicUrl, zipSha), await copyAsset(join(folder, files.signature), targetDir, tag, publicUrl), await copyAsset(join(folder, files.manifest), targetDir, tag, publicUrl), ]; staged.push({ tag_name: tag, name: `Adaptation Pack ${version}`, draft: false, prerelease: true, published_at: manifest.createdAt, body: `Verified game versions: ${manifest.gameVersions.join(', ')}\nMinimum launcher version: v${manifest.minAppVersion}\n`, game_versions: manifest.gameVersions, min_app_version: manifest.minAppVersion, assets, }); } return staged; } async function copyAsset( sourcePath: string, targetDir: string, tag: string, publicUrl: string, knownSha256?: string, ): Promise { const name = basename(sourcePath); const destination = join(targetDir, name); if (resolve(sourcePath) !== resolve(destination)) await copyFile(sourcePath, destination); const info = await stat(destination); const entry: ReleaseAssetEntry = { name, browser_download_url: `${publicUrl}/files/${encodeURIComponent(tag)}/${encodeURIComponent(name)}`, size: info.size, ...(knownSha256 ? { sha256: knownSha256 } : {}), }; return entry; } async function uploadToR2( r2: R2Client, outDir: string, feedJson: string, html: string, force: boolean, dryRun: boolean, ): Promise { const filesRoot = join(outDir, 'files'); const assetFiles = existsSync(filesRoot) ? await collectFiles(filesRoot) : []; // Upload all versioned assets first so the feed never points to a missing file. for (const filePath of assetFiles) { const relative = filePath.slice(outDir.length + 1).replace(/\\/g, '/'); const bytes = await readFile(filePath); const digest = sha256(bytes); if (!force && !dryRun) { const head = await r2.headObject(relative); if (head.exists && head.contentLength === bytes.length && head.sha256Meta === digest) { console.info(`Skipped unchanged ${relative}`); continue; } } if (dryRun) { console.info(`[dry-run] PUT ${relative} (${bytes.length} bytes, ${contentTypeFor(relative)})`); continue; } console.info(`Uploading ${relative} (${(bytes.length / (1024 * 1024)).toFixed(2)} MB)...`); await r2.putObject({ key: relative, body: bytes, contentType: contentTypeFor(relative), cacheControl: CACHE_IMMUTABLE, sha256Hex: digest, }); } const feedBytes = Buffer.from(feedJson, 'utf8'); const htmlBytes = Buffer.from(html, 'utf8'); if (dryRun) { console.info(`[dry-run] PUT releases (${feedBytes.length} bytes, application/json)`); console.info(`[dry-run] PUT index.html (${htmlBytes.length} bytes, text/html)`); return; } await r2.putObject({ key: 'releases', body: feedBytes, contentType: 'application/json; charset=utf-8', cacheControl: CACHE_FEED, }); console.info('Uploaded releases'); await r2.putObject({ key: 'index.html', body: htmlBytes, contentType: 'text/html; charset=utf-8', cacheControl: CACHE_FEED, }); console.info('Uploaded index.html'); } async function collectFiles(dir: string): Promise { const entries = await readdir(dir, { withFileTypes: true }); const results: string[] = []; for (const entry of entries) { const full = join(dir, entry.name); if (entry.isDirectory()) results.push(...await collectFiles(full)); else if (entry.isFile()) results.push(full); } return results.sort(); } function contentTypeFor(key: string): string { switch (extname(key).toLowerCase()) { case '.json': return 'application/json; charset=utf-8'; case '.sig': return 'text/plain; charset=utf-8'; case '.zip': return 'application/zip'; case '.exe': return 'application/vnd.microsoft.portable-executable'; case '.html': return 'text/html; charset=utf-8'; default: return 'application/octet-stream'; } } function sortReleases(entries: ReleaseEntry[]): ReleaseEntry[] { return entries.sort((a, b) => { const aLauncher = a.tag_name.startsWith('v'); const bLauncher = b.tag_name.startsWith('v'); if (aLauncher && bLauncher) return compareAppVersions(b.tag_name.slice(1), a.tag_name.slice(1)); const aPack = packVersionOfTag(a.tag_name); const bPack = packVersionOfTag(b.tag_name); if (aPack && bPack) return comparePackVersions(bPack, aPack); return b.published_at.localeCompare(a.published_at); }); } function parseExistingReleases(text: string): ReleaseEntry[] { const parsed: unknown = JSON.parse(text); if (!Array.isArray(parsed)) throw new Error('Existing releases feed is not a JSON array.'); return parsed.filter((entry): entry is ReleaseEntry => typeof entry === 'object' && entry !== null && typeof (entry as Record)['tag_name'] === 'string'); } function createR2Client(): R2Client { const endpoint = requiredEnv('R2_ENDPOINT'); const bucket = requiredEnv('R2_BUCKET'); const accessKeyId = requiredEnv('R2_ACCESS_KEY_ID'); const secretAccessKey = requiredEnv('R2_SECRET_ACCESS_KEY'); return new R2Client({ endpoint, bucket, accessKeyId, secretAccessKey }); } function requiredEnv(name: string): string { const value = process.env[name]?.trim(); if (!value) throw new Error(`Missing ${name}. Set it in your environment or in .env.r2.local (gitignored).`); return value; } function loadLocalEnv(path: string): void { if (!existsSync(path)) return; const content = readFileSync(path, 'utf8'); for (const rawLine of content.replace(/\r\n/g, '\n').split('\n')) { const line = rawLine.trim(); if (!line || line.startsWith('#')) continue; const eq = line.indexOf('='); if (eq <= 0) continue; const key = line.slice(0, eq).trim(); let value = line.slice(eq + 1).trim(); if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } if (!(key in process.env)) process.env[key] = value; } } function printUsage(): void { console.info([ 'Usage: node scripts/publish-r2-releases.ts [options]', '', ' --add-launcher Stage signed installer/portable release from a build folder', ' --add-pack Stage signed adaptation pack(s) from a folder or .zip file', ' --notes Release notes Markdown file for --add-launcher', ' --remove-tag Remove a tag from the release feed', ' --out Local staging directory (default: build/r2-dist)', ' --public-url Public mirror URL (default: R2_PUBLIC_URL or tuning primary_source)', ' --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', ' --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')); } await main();