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:
1 parent
240ee81712
commit
de967dd993
4 files changed
+1088
-1
No files matched your search
+2
-1
@@ -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/
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
/**
|
||||
* Stage verified signed launcher releases and adaptation packs into a GitHub-compatible static
|
||||
* distribution directory (`releases`, `index.html`, `files/<tag>/...`) and optionally upload
|
||||
* them to Cloudflare R2 via its S3-compatible API.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/publish-r2-releases.ts [options]
|
||||
*
|
||||
* Options:
|
||||
* --add-launcher <dir> Stage signed installer (and optional portable zip) from a build folder
|
||||
* --add-pack <path> Stage signed adaptation pack(s) from a folder or a specific .zip file
|
||||
* --notes <file> Release notes Markdown for --add-launcher (defaults to .github/release-notes/v<ver>.md)
|
||||
* --remove-tag <tag> Remove a tag from the release feed
|
||||
* --out <dir> Local staging directory (default: build/r2-dist)
|
||||
* --public-url <url> Public mirror base URL (default: R2_PUBLIC_URL or primary_source from tuning)
|
||||
* --repo-url <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<void> {
|
||||
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<string, ReleaseEntry>();
|
||||
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<ReleaseEntry> {
|
||||
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<ReleaseEntry[]> {
|
||||
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<ReleaseAssetEntry> {
|
||||
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<void> {
|
||||
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<string[]> {
|
||||
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<string, unknown>)['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 <dir> Stage signed installer/portable release from a build folder',
|
||||
' --add-pack <path> Stage signed adaptation pack(s) from a folder or .zip file',
|
||||
' --notes <file> Release notes Markdown file for --add-launcher',
|
||||
' --remove-tag <tag> Remove a tag from the release feed',
|
||||
' --out <dir> Local staging directory (default: build/r2-dist)',
|
||||
' --public-url <url> Public mirror URL (default: R2_PUBLIC_URL or tuning primary_source)',
|
||||
' --repo-url <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();
|
||||
@@ -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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
@@ -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()}`);
|
||||
}
|
||||
Reference in new issue
Block a user