feat(repo): add R2 release staging, download page, and S3 publish script

Add scripts/publish-r2-releases.ts with a zero-dependency SigV4 R2 client and bilingual static index.html generator. Staged launcher releases and adaptation packs are verified against the committed Ed25519 public key and SHA-256 digests before publishing, assets are uploaded ahead of the releases feed with SHA-256 skip checks, and .env*.local is gitignored for local R2 credentials. Verified with root typecheck, local staging, and live R2 upload.
This commit is contained in:
N0VAN0M4LY committed 2026-12-03 03:03:14 +08:00
1 parent 240ee81712
commit de967dd993
4 files changed
+1088 -1

No files matched your search

+465
View File
@@ -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 `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WTOffline — Download / 下载站</title>
<style>
:root {
color-scheme: dark;
--bg: #0d1117;
--panel: #161b22;
--panel-2: #1c222b;
--border: #30363d;
--text: #e6edf3;
--muted: #8b949e;
--accent: #d97706;
--accent-hover: #f59e0b;
--ok: #3fb950;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--sans: system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: var(--sans);
background: radial-gradient(circle at 20% 0%, #1b2230 0%, var(--bg) 55%);
color: var(--text);
line-height: 1.6;
min-height: 100vh;
}
.wrap { max-width: 960px; margin: 0 auto; padding: 32px 20px 64px; }
header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 16px;
padding-bottom: 24px;
border-bottom: 1px solid var(--border);
}
.brand h1 { margin: 0; font-size: 28px; letter-spacing: 0.04em; }
.brand p { margin: 4px 0 0; color: var(--muted); font-size: 14px; }
.top-actions { display: flex; align-items: center; gap: 10px; }
.btn-ghost {
display: inline-flex;
align-items: center;
padding: 8px 14px;
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
background: var(--panel);
text-decoration: none;
font-size: 13px;
cursor: pointer;
}
.btn-ghost:hover { border-color: var(--accent); color: #fff; }
section { margin-top: 28px; }
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 10px;
padding: 22px;
}
.card-header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 8px;
margin-bottom: 14px;
}
.card-header h2 { margin: 0; font-size: 20px; }
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 12px;
font-family: var(--mono);
background: rgba(217, 119, 6, 0.16);
color: #fbbf24;
border: 1px solid rgba(217, 119, 6, 0.4);
margin-left: 8px;
vertical-align: middle;
}
.meta { color: var(--muted); font-size: 13px; }
.dl-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 14px;
margin-top: 14px;
}
.dl-box {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
padding: 16px;
display: flex;
flex-direction: column;
gap: 10px;
}
.dl-box h3 { margin: 0; font-size: 15px; }
.dl-btn {
display: inline-flex;
justify-content: center;
align-items: center;
min-height: 44px;
padding: 10px 16px;
border-radius: 6px;
background: var(--accent);
color: #111;
font-weight: 600;
text-decoration: none;
font-size: 14px;
text-align: center;
white-space: nowrap;
}
.dl-btn:hover { background: var(--accent-hover); }
.dl-btn.secondary { background: #2b3441; color: var(--text); }
.dl-btn.secondary:hover { background: #374354; }
.file-name {
font-family: var(--mono);
font-size: 12px;
color: var(--text);
word-break: break-all;
margin: 0;
}
.hash {
font-family: var(--mono);
font-size: 11px;
color: var(--muted);
word-break: break-all;
margin: 0;
}
.notes {
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid var(--border);
font-size: 14px;
}
.notes h3, .notes h4 { margin: 12px 0 6px; font-size: 15px; }
.notes ul { margin: 6px 0; padding-left: 20px; }
.notes li { margin: 4px 0; }
.notes code {
font-family: var(--mono);
font-size: 12px;
background: #0d1117;
padding: 1px 5px;
border-radius: 4px;
}
.tip {
margin-top: 14px;
padding: 12px 14px;
border-radius: 8px;
background: rgba(63, 185, 80, 0.08);
border: 1px solid rgba(63, 185, 80, 0.3);
font-size: 13px;
color: #c9f2cf;
}
details {
margin-top: 14px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
}
summary { cursor: pointer; font-weight: 600; font-size: 14px; }
table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: 13px; }
th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid var(--border); }
td a { color: #fbbf24; text-decoration: none; margin-right: 10px; }
td a:hover { text-decoration: underline; }
footer {
margin-top: 40px;
padding-top: 16px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 12px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 10px;
}
footer a { color: var(--muted); }
[data-lang="en"] .lang-zh { display: none; }
[data-lang="zh"] .lang-en { display: none; }
</style>
</head>
<body data-lang="zh">
<div class="wrap">
<header>
<div class="brand">
<h1>WTOffline</h1>
<p>
<span class="lang-zh">官方分发镜像站 · 全部安装包与适配包均经 Ed25519 签名校验</span>
<span class="lang-en">Official Release Mirror · All installers and adaptation packs are Ed25519 signed</span>
</p>
</div>
<div class="top-actions">
<a class="btn-ghost" href="${escapeHtml(options.repoUrl)}" target="_blank" rel="noopener">
<span class="lang-zh">源码仓库</span>
<span class="lang-en">Source Repository</span>
</a>
<a class="btn-ghost" href="${escapeHtml(options.repoUrl)}/releases" target="_blank" rel="noopener">
<span class="lang-zh">历史归档</span>
<span class="lang-en">Release Archive</span>
</a>
<button class="btn-ghost" id="lang-toggle" type="button">English / 中文</button>
</div>
</header>
<section>
${latestLauncher ? renderLatestLauncher(latestLauncher) : renderEmptyState('launcher')}
</section>
<section>
${latestPack ? renderLatestPack(latestPack) : renderEmptyState('pack')}
</section>
${olderLaunchers.length > 0 || olderPacks.length > 0 ? renderHistory(olderLaunchers, olderPacks) : ''}
<footer>
<span>
<span class="lang-zh">启动器自动更新接口:</span>
<span class="lang-en">Launcher update feed: </span>
<a href="${escapeHtml(options.publicUrl.replace(/\/$/, ''))}/releases">${escapeHtml(options.publicUrl.replace(/\/$/, ''))}/releases</a>
</span>
<span>Updated ${escapeHtml(options.generatedAt.slice(0, 19).replace('T', ' '))} UTC</span>
</footer>
</div>
<script>
(function () {
var saved = localStorage.getItem('wto-dl-lang');
var initial = saved || ((navigator.language || '').toLowerCase().startsWith('zh') ? 'zh' : 'en');
document.body.setAttribute('data-lang', initial);
document.getElementById('lang-toggle').addEventListener('click', function () {
var next = document.body.getAttribute('data-lang') === 'zh' ? 'en' : 'zh';
document.body.setAttribute('data-lang', next);
localStorage.setItem('wto-dl-lang', next);
});
})();
</script>
</body>
</html>
`;
}
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 `<div class="card">
<div class="card-header">
<h2>
<span class="lang-zh">启动器最新版</span>
<span class="lang-en">Latest Launcher</span>
<span class="badge">${escapeHtml(release.tag_name)}</span>
</h2>
<span class="meta">Windows x64 · ${escapeHtml(date)}</span>
</div>
<div class="dl-grid">
${installer ? renderDownloadBox(installer, '安装版(推荐)', 'Windows Installer (Recommended)', '下载安装版', 'Download Installer', false) : ''}
${portable ? renderDownloadBox(portable, '便携压缩包(免安装)', 'Portable Archive (No Install)', '下载便携包', 'Download Portable', true) : ''}
</div>
<div class="tip">
<span class="lang-zh">已安装的启动器会在启动时自动从此镜像检查并验签更新;本程序不包含任何原版游戏文件,需配合你自己的客户端使用。</span>
<span class="lang-en">Installed launchers check this mirror automatically and verify Ed25519 signatures. No stock game files are distributed; your own client is required.</span>
</div>
${release.body.trim() ? `<div class="notes">${renderSimpleMarkdown(release.body)}</div>` : ''}
</div>`;
}
function renderDownloadBox(
asset: ReleaseAssetEntry,
titleZh: string,
titleEn: string,
btnZh: string,
btnEn: string,
secondary: boolean,
): string {
const sizeLabel = asset.size !== undefined ? ` (${formatBytes(asset.size)})` : '';
return `<div class="dl-box">
<h3>
<span class="lang-zh">${escapeHtml(titleZh)}</span>
<span class="lang-en">${escapeHtml(titleEn)}</span>
</h3>
<a class="dl-btn${secondary ? ' secondary' : ''}" href="${escapeHtml(asset.browser_download_url)}">
<span class="lang-zh">${escapeHtml(btnZh)}${escapeHtml(sizeLabel)}</span>
<span class="lang-en">${escapeHtml(btnEn)}${escapeHtml(sizeLabel)}</span>
</a>
<p class="file-name">${escapeHtml(asset.name)}</p>
${asset.sha256 ? `<p class="hash">SHA-256: ${escapeHtml(asset.sha256)}</p>` : ''}
</div>`;
}
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 `<div class="card">
<div class="card-header">
<h2>
<span class="lang-zh">最新游戏版本适配包</span>
<span class="lang-en">Latest Adaptation Pack</span>
<span class="badge">${escapeHtml(release.tag_name)}</span>
</h2>
<span class="meta">${escapeHtml(date)}</span>
</div>
<p class="meta">
<span class="lang-zh">正常情况下启动器会自动拉取并启用适配包,无需手动下载。</span>
<span class="lang-en">The launcher fetches and activates adaptation packs automatically; manual download is normally unnecessary.</span>
</p>
${games ? `<p class="meta"><span class="lang-zh">已核对客户端版本:</span><span class="lang-en">Verified game versions: </span><code>${escapeHtml(games)}</code></p>` : ''}
${minApp ? `<p class="meta"><span class="lang-zh">最低启动器版本:</span><span class="lang-en">Minimum launcher version: </span><code>v${escapeHtml(minApp)}</code></p>` : ''}
${zip ? `<p><a class="btn-ghost" href="${escapeHtml(zip.browser_download_url)}">${escapeHtml(zip.name)}${zip.size !== undefined ? ` (${escapeHtml(formatBytes(zip.size))})` : ''}</a></p>` : ''}
</div>`;
}
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 `<div class="card"><p class="meta"><span class="lang-zh">${zh}</span><span class="lang-en">${en}</span></p></div>`;
}
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) => `<a href="${escapeHtml(asset.browser_download_url)}">${escapeHtml(asset.name)}</a>`)
.join('');
return `<tr>
<td><code>${escapeHtml(release.tag_name)}</code></td>
<td>${escapeHtml(release.published_at.slice(0, 10))}</td>
<td>${links}</td>
</tr>`;
}).join('');
return `<details>
<summary>
<span class="lang-zh">历史版本(${launchers.length + packs.length})</span>
<span class="lang-en">Previous Releases (${launchers.length + packs.length})</span>
</summary>
<table>
<thead>
<tr>
<th>Tag</th>
<th>Date</th>
<th>Files</th>
</tr>
</thead>
<tbody>${rows}</tbody>
</table>
</details>`;
}
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('</ul>');
inList = false;
}
};
for (const raw of lines) {
const line = raw.trim();
if (!line) {
closeList();
continue;
}
if (line.startsWith('### ')) {
closeList();
html.push(`<h4>${inlineMarkdown(line.slice(4))}</h4>`);
continue;
}
if (line.startsWith('## ')) {
closeList();
html.push(`<h3>${inlineMarkdown(line.slice(3))}</h3>`);
continue;
}
if (line.startsWith('- ') || line.startsWith('* ')) {
if (!inList) {
html.push('<ul>');
inList = true;
}
html.push(`<li>${inlineMarkdown(line.slice(2))}</li>`);
continue;
}
closeList();
html.push(`<p>${inlineMarkdown(line)}</p>`);
}
closeList();
return html.join('\n');
}
function inlineMarkdown(text: string): string {
return escapeHtml(text)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
}
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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
+158
View File
@@ -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://<account-id>.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<R2HeadResult> {
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<string | null> {
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<void> {
const sha256Hex = options.sha256Hex ?? sha256(options.body);
const extraHeaders: Record<string, string> = {
'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<string, string>,
payloadHash = EMPTY_SHA256,
): Promise<Response> {
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<string, string> = {
...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()}`);
}