diff --git a/.gitignore b/.gitignore index dbfc10f..18b8e05 100644 --- a/.gitignore +++ b/.gitignore @@ -25,10 +25,11 @@ __pycache__/ *.pyc .venv/ -# Saves, logs, local runtime data +# Saves, logs, local runtime data, local secrets /data/ /saves/ *.log +.env*.local # Editors / OS .vscode/ diff --git a/scripts/publish-r2-releases.ts b/scripts/publish-r2-releases.ts new file mode 100644 index 0000000..1800495 --- /dev/null +++ b/scripts/publish-r2-releases.ts @@ -0,0 +1,463 @@ +/** + * 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(); diff --git a/scripts/r2/download-page.ts b/scripts/r2/download-page.ts new file mode 100644 index 0000000..20b5986 --- /dev/null +++ b/scripts/r2/download-page.ts @@ -0,0 +1,465 @@ +/** + * Generates a self-contained bilingual (zh-CN / EN) static download page (`index.html`) + * from the GitHub-compatible release list served by the R2 distribution mirror. + */ +import { compareAppVersions, comparePackVersions, packVersionOfTag } from '@wto/patcher'; + +export interface ReleaseAssetEntry { + readonly name: string; + readonly browser_download_url: string; + readonly size?: number; + readonly sha256?: string; +} + +export interface ReleaseEntry { + readonly tag_name: string; + readonly name: string; + readonly draft: boolean; + readonly prerelease: boolean; + readonly published_at: string; + readonly body: string; + readonly game_versions?: readonly string[]; + readonly min_app_version?: string; + readonly assets: readonly ReleaseAssetEntry[]; +} + +export interface DownloadPageOptions { + readonly releases: readonly ReleaseEntry[]; + readonly publicUrl: string; + readonly repoUrl: string; + readonly generatedAt: string; +} + +export function renderDownloadPage(options: DownloadPageOptions): string { + const launchers = options.releases + .filter((entry) => !entry.draft && !entry.prerelease && entry.tag_name.startsWith('v')) + .sort((a, b) => compareAppVersions(b.tag_name.slice(1), a.tag_name.slice(1))); + + const packs = options.releases + .filter((entry) => !entry.draft && packVersionOfTag(entry.tag_name) !== null) + .sort((a, b) => comparePackVersions(packVersionOfTag(b.tag_name)!, packVersionOfTag(a.tag_name)!)); + + const latestLauncher = launchers[0] ?? null; + const latestPack = packs[0] ?? null; + const olderLaunchers = launchers.slice(1); + const olderPacks = packs.slice(1); + + return ` + + + + + WTOffline — Download / 下载站 + + + +
+
+
+

WTOffline

+

+ 官方分发镜像站 · 全部安装包与适配包均经 Ed25519 签名校验 + Official Release Mirror · All installers and adaptation packs are Ed25519 signed +

+
+ +
+ +
+ ${latestLauncher ? renderLatestLauncher(latestLauncher) : renderEmptyState('launcher')} +
+ +
+ ${latestPack ? renderLatestPack(latestPack) : renderEmptyState('pack')} +
+ + ${olderLaunchers.length > 0 || olderPacks.length > 0 ? renderHistory(olderLaunchers, olderPacks) : ''} + + +
+ + + +`; +} + +function renderLatestLauncher(release: ReleaseEntry): string { + const installer = release.assets.find((asset) => asset.name.endsWith('.exe')); + const portable = release.assets.find((asset) => asset.name.endsWith('-portable.zip')); + const date = release.published_at.slice(0, 10); + + return `
+
+

+ 启动器最新版 + Latest Launcher + ${escapeHtml(release.tag_name)} +

+ Windows x64 · ${escapeHtml(date)} +
+
+ ${installer ? renderDownloadBox(installer, '安装版(推荐)', 'Windows Installer (Recommended)', '下载安装版', 'Download Installer', false) : ''} + ${portable ? renderDownloadBox(portable, '便携压缩包(免安装)', 'Portable Archive (No Install)', '下载便携包', 'Download Portable', true) : ''} +
+
+ 已安装的启动器会在启动时自动从此镜像检查并验签更新;本程序不包含任何原版游戏文件,需配合你自己的客户端使用。 + Installed launchers check this mirror automatically and verify Ed25519 signatures. No stock game files are distributed; your own client is required. +
+ ${release.body.trim() ? `
${renderSimpleMarkdown(release.body)}
` : ''} +
`; +} + +function renderDownloadBox( + asset: ReleaseAssetEntry, + titleZh: string, + titleEn: string, + btnZh: string, + btnEn: string, + secondary: boolean, +): string { + const sizeLabel = asset.size !== undefined ? ` (${formatBytes(asset.size)})` : ''; + return `
+

+ ${escapeHtml(titleZh)} + ${escapeHtml(titleEn)} +

+ + ${escapeHtml(btnZh)}${escapeHtml(sizeLabel)} + ${escapeHtml(btnEn)}${escapeHtml(sizeLabel)} + +

${escapeHtml(asset.name)}

+ ${asset.sha256 ? `

SHA-256: ${escapeHtml(asset.sha256)}

` : ''} +
`; +} + +function renderLatestPack(release: ReleaseEntry): string { + const zip = release.assets.find((asset) => asset.name.endsWith('.zip')); + const date = release.published_at.slice(0, 10); + const games = release.game_versions?.join(', ') ?? ''; + const minApp = release.min_app_version ?? ''; + + return `
+
+

+ 最新游戏版本适配包 + Latest Adaptation Pack + ${escapeHtml(release.tag_name)} +

+ ${escapeHtml(date)} +
+

+ 正常情况下启动器会自动拉取并启用适配包,无需手动下载。 + The launcher fetches and activates adaptation packs automatically; manual download is normally unnecessary. +

+ ${games ? `

已核对客户端版本:Verified game versions: ${escapeHtml(games)}

` : ''} + ${minApp ? `

最低启动器版本:Minimum launcher version: v${escapeHtml(minApp)}

` : ''} + ${zip ? `

${escapeHtml(zip.name)}${zip.size !== undefined ? ` (${escapeHtml(formatBytes(zip.size))})` : ''}

` : ''} +
`; +} + +function renderEmptyState(kind: 'launcher' | 'pack'): string { + const zh = kind === 'launcher' ? '暂未发布启动器安装包。' : '暂未发布适配包。'; + const en = kind === 'launcher' ? 'No launcher releases published yet.' : 'No adaptation packs published yet.'; + return `

${zh}${en}

`; +} + +function renderHistory(launchers: readonly ReleaseEntry[], packs: readonly ReleaseEntry[]): string { + const rows = [...launchers, ...packs].map((release) => { + const links = release.assets + .filter((asset) => asset.name.endsWith('.exe') || asset.name.endsWith('.zip')) + .map((asset) => `${escapeHtml(asset.name)}`) + .join(''); + return ` + ${escapeHtml(release.tag_name)} + ${escapeHtml(release.published_at.slice(0, 10))} + ${links} + `; + }).join(''); + + return `
+ + 历史版本(${launchers.length + packs.length}) + Previous Releases (${launchers.length + packs.length}) + + + + + + + + + + ${rows} +
TagDateFiles
+
`; +} + +function renderSimpleMarkdown(source: string): string { + const lines = source.replace(/\r\n/g, '\n').split('\n'); + const html: string[] = []; + let inList = false; + + const closeList = (): void => { + if (inList) { + html.push(''); + inList = false; + } + }; + + for (const raw of lines) { + const line = raw.trim(); + if (!line) { + closeList(); + continue; + } + if (line.startsWith('### ')) { + closeList(); + html.push(`

${inlineMarkdown(line.slice(4))}

`); + continue; + } + if (line.startsWith('## ')) { + closeList(); + html.push(`

${inlineMarkdown(line.slice(3))}

`); + continue; + } + if (line.startsWith('- ') || line.startsWith('* ')) { + if (!inList) { + html.push('
    '); + inList = true; + } + html.push(`
  • ${inlineMarkdown(line.slice(2))}
  • `); + continue; + } + closeList(); + html.push(`

    ${inlineMarkdown(line)}

    `); + } + closeList(); + return html.join('\n'); +} + +function inlineMarkdown(text: string): string { + return escapeHtml(text) + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*([^*]+)\*\*/g, '$1'); +} + +function formatBytes(bytes: number): string { + if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${bytes} B`; +} + +function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} diff --git a/scripts/r2/sigv4.ts b/scripts/r2/sigv4.ts new file mode 100644 index 0000000..247dda0 --- /dev/null +++ b/scripts/r2/sigv4.ts @@ -0,0 +1,158 @@ +/** + * Minimal AWS Signature Version 4 S3 client for Cloudflare R2 (zero external dependencies). + * Supports HEAD, GET, and PUT against R2's path-style S3 endpoint. + */ +import { createHash, createHmac } from 'node:crypto'; + +export interface R2ClientConfig { + /** Account S3 API endpoint, e.g. `https://.r2.cloudflarestorage.com`. */ + readonly endpoint: string; + readonly bucket: string; + readonly accessKeyId: string; + readonly secretAccessKey: string; + readonly region?: string; +} + +export interface R2HeadResult { + readonly exists: boolean; + readonly contentLength: number | null; + readonly sha256Meta: string | null; +} + +export interface R2PutOptions { + readonly key: string; + readonly body: Uint8Array; + readonly contentType: string; + readonly cacheControl: string; + readonly sha256Hex?: string; +} + +const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; + +export class R2Client { + readonly #endpoint: URL; + readonly #bucket: string; + readonly #accessKeyId: string; + readonly #secretAccessKey: string; + readonly #region: string; + + constructor(config: R2ClientConfig) { + const endpoint = new URL(config.endpoint); + if (endpoint.protocol !== 'https:') throw new Error('R2_ENDPOINT must be an https:// URL.'); + this.#endpoint = endpoint; + this.#bucket = config.bucket; + this.#accessKeyId = config.accessKeyId; + this.#secretAccessKey = config.secretAccessKey; + this.#region = config.region ?? 'auto'; + } + + async headObject(key: string): Promise { + const response = await this.#send('HEAD', key, undefined, {}); + if (response.status === 404) return { exists: false, contentLength: null, sha256Meta: null }; + if (!response.ok) throw new Error(`R2 HEAD ${key} failed with HTTP ${response.status}.`); + const lengthHeader = response.headers.get('content-length'); + const contentLength = lengthHeader !== null && /^\d+$/.test(lengthHeader) ? Number(lengthHeader) : null; + return { + exists: true, + contentLength, + sha256Meta: response.headers.get('x-amz-meta-sha256'), + }; + } + + async getObjectText(key: string): Promise { + const response = await this.#send('GET', key, undefined, {}); + if (response.status === 404) return null; + if (!response.ok) throw new Error(`R2 GET ${key} failed with HTTP ${response.status}: ${await response.text()}`); + return response.text(); + } + + async putObject(options: R2PutOptions): Promise { + const sha256Hex = options.sha256Hex ?? sha256(options.body); + const extraHeaders: Record = { + 'content-type': options.contentType, + 'cache-control': options.cacheControl, + 'x-amz-meta-sha256': sha256Hex, + }; + const response = await this.#send('PUT', options.key, options.body, extraHeaders, sha256Hex); + if (!response.ok) { + throw new Error(`R2 PUT ${options.key} failed with HTTP ${response.status}: ${await response.text()}`); + } + } + + async #send( + method: 'HEAD' | 'GET' | 'PUT', + key: string, + body: Uint8Array | undefined, + extraHeaders: Record, + payloadHash = EMPTY_SHA256, + ): Promise { + const normalizedKey = key.replace(/^\/+/, ''); + const canonicalUri = `/${encodeSegment(this.#bucket)}/${normalizedKey.split('/').map(encodeSegment).join('/')}`; + const url = new URL(canonicalUri, this.#endpoint); + + const now = new Date(); + const amzDate = formatAmzDate(now); + const dateStamp = amzDate.slice(0, 8); + + const signedEntries: [string, string][] = [ + ['host', url.host], + ['x-amz-content-sha256', payloadHash], + ['x-amz-date', amzDate], + ]; + for (const [name, value] of Object.entries(extraHeaders)) { + const lower = name.toLowerCase(); + if (lower.startsWith('x-amz-')) signedEntries.push([lower, value.trim()]); + } + signedEntries.sort((a, b) => a[0].localeCompare(b[0])); + + const canonicalHeaders = signedEntries.map(([k, v]) => `${k}:${v}\n`).join(''); + const signedHeaders = signedEntries.map(([k]) => k).join(';'); + const canonicalRequest = [method, canonicalUri, '', canonicalHeaders, signedHeaders, payloadHash].join('\n'); + const credentialScope = `${dateStamp}/${this.#region}/s3/aws4_request`; + const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, sha256(canonicalRequest)].join('\n'); + + const signingKey = deriveSigningKey(this.#secretAccessKey, dateStamp, this.#region, 's3'); + const signature = hmacHex(signingKey, stringToSign); + const authorization = `AWS4-HMAC-SHA256 Credential=${this.#accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; + + const headers: Record = { + ...extraHeaders, + 'x-amz-date': amzDate, + 'x-amz-content-sha256': payloadHash, + authorization, + }; + + return fetch(url, { + method, + headers, + ...(body ? { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) } : {}), + }); + } +} + +export function sha256(data: string | Uint8Array): string { + return createHash('sha256').update(data).digest('hex'); +} + +function hmac(key: string | Buffer, data: string): Buffer { + return createHmac('sha256', key).update(data, 'utf8').digest(); +} + +function hmacHex(key: Buffer, data: string): string { + return createHmac('sha256', key).update(data, 'utf8').digest('hex'); +} + +function deriveSigningKey(secretKey: string, dateStamp: string, region: string, service: string): Buffer { + const kDate = hmac(`AWS4${secretKey}`, dateStamp); + const kRegion = hmac(kDate, region); + const kService = hmac(kRegion, service); + return hmac(kService, 'aws4_request'); +} + +function formatAmzDate(date: Date): string { + return date.toISOString().replace(/[:-]|\.\d{3}/g, ''); +} + +function encodeSegment(segment: string): string { + return encodeURIComponent(segment).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`); +}