Files
Reims-landing/worker/index.js
T

378 lines
13 KiB
JavaScript

const GITHUB_REPO_API = 'https://api.github.com/repos/Nwflower/Reims-Go';
const GITHUB_RELEASES_API = 'https://api.github.com/repos/Nwflower/Reims-Go/releases?per_page=25';
const EDGE_FRESH_MS = 300 * 1000; // 5 min fresh window before background SWR refresh
const EDGE_STORE_SECONDS = 3600; // 1 hour max cache lifetime in caches.default
const FALLBACK_CACHE_SECONDS = 60; // Negative-cache static fallback to avoid upstream storms
const UPSTREAM_TIMEOUT_MS = 4000;
const CANONICAL_RELEASES_URL = 'https://github.com/Nwflower/Reims-Go/releases/latest';
const API_SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Content-Security-Policy': "default-src 'none'",
};
const SKIP_SECTIONS = /^(下载|download|downloads|已知限制|known limitations|许可证|license|构建与许可证)/i;
// Isolate-level in-flight coalescing to prevent cache stampedes
let liveInflight = null;
function sanitizeGitHubUrl(raw) {
if (typeof raw !== 'string' || !raw.trim()) return null;
try {
const u = new URL(raw.trim());
if (u.protocol !== 'https:') return null;
const host = u.hostname.toLowerCase();
if (host === 'github.com' || host.endsWith('.githubusercontent.com')) {
return u.href;
}
return null;
} catch {
return null;
}
}
function normalizeTitle(raw) {
return String(raw || '')
.replace(/<[^>]+>/g, '')
.replace(/^#+\s*/, '')
.trim();
}
function parseSections(markdown) {
const lines = String(markdown || '').replace(/\r\n/g, '\n').split('\n');
const sections = [];
let current = null;
let skipping = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) continue;
const htmlHeading = line.match(/^<h[2-4][^>]*>(.*?)<\/h[2-4]>$/i);
const mdHeading = !htmlHeading ? line.match(/^#{2,4}\s+(.+)$/) : null;
if (htmlHeading || mdHeading) {
const title = normalizeTitle(htmlHeading ? htmlHeading[1] : mdHeading[1]);
if (!title || SKIP_SECTIONS.test(title)) {
skipping = true;
current = null;
} else {
skipping = false;
current = { title, items: [] };
sections.push(current);
}
continue;
}
if (skipping || /^\[中文\]\(#cn-/i.test(line) || line.startsWith('>')) continue;
const bullet = line.match(/^[-*]\s+(.+)$/);
if (bullet && bullet[1].trim()) {
if (!current) {
current = { title: '', items: [] };
sections.push(current);
}
current.items.push(bullet[1].trim());
}
}
return sections.filter((s) => s.items.length > 0);
}
function parseBilingualBody(body) {
const text = String(body || '').replace(/\r\n/g, '\n');
if (!text.trim()) return { 'zh-CN': [], 'en-US': [] };
const cn = text.match(/<h[2-4][^>]*\bid=["']cn-[^"']*["'][^>]*>/i);
const en = text.match(/<h[2-4][^>]*\bid=["']en-[^"']*["'][^>]*>/i);
if (cn && en && cn.index !== undefined && en.index !== undefined) {
const cnChunk = cn.index < en.index ? text.slice(cn.index, en.index) : text.slice(cn.index);
const enChunk = en.index > cn.index ? text.slice(en.index) : text.slice(en.index, cn.index);
const zhSections = parseSections(cnChunk);
const enSections = parseSections(enChunk);
return {
'zh-CN': zhSections.length ? zhSections : enSections,
'en-US': enSections.length ? enSections : zhSections,
};
}
const single = parseSections(text);
return { 'zh-CN': single, 'en-US': single };
}
function extractAssets(assets) {
const list = Array.isArray(assets) ? assets : [];
const exe = list.find((a) => typeof a?.name === 'string' && /windows-amd64\.exe$/i.test(a.name));
const zip = list.find((a) => typeof a?.name === 'string' && /windows-amd64\.zip$/i.test(a.name));
const sha = list.find((a) => typeof a?.name === 'string' && /^SHA256SUMS\.txt$/i.test(a.name));
const exeUrl = sanitizeGitHubUrl(exe?.browser_download_url);
const zipUrl = sanitizeGitHubUrl(zip?.browser_download_url);
const shaUrl = sanitizeGitHubUrl(sha?.browser_download_url);
const digestLines = [exe, zip]
.filter((a) => a?.name && a?.digest && /^sha256:[a-f0-9]{64}$/i.test(a.digest))
.map((a) => `${a.digest.replace(/^sha256:/i, '')} ${a.name}`);
return {
exe: exeUrl ? { name: exe.name, size: Number(exe.size) || 0, url: exeUrl } : null,
zip: zipUrl ? { name: zip.name, size: Number(zip.size) || 0, url: zipUrl } : null,
sha256_url: shaUrl,
sha256_sums: digestLines.join('\n'),
};
}
function classifyChannel(tag, prerelease) {
const lower = tag.toLowerCase();
if (lower === 'dev' || lower.includes('-dev')) return 'dev';
if (prerelease || lower.includes('alpha') || lower.includes('beta') || lower.includes('rc')) return 'alpha';
return 'stable';
}
function isClientTag(tag) {
if (!tag || /^runtime-/i.test(tag)) return false;
return /^v\d+\.\d+/i.test(tag) || /^dev$/i.test(tag) || /^alpha/i.test(tag);
}
async function fetchGitHubJson(url, token) {
const headers = {
Accept: 'application/vnd.github+json',
'User-Agent': 'Reims-Go-Landing-Worker/2.0 (+https://reims.dev)',
};
if (token) headers.Authorization = `Bearer ${token}`;
const init = { headers };
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
init.signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
}
const res = await fetch(url, init);
if (!res.ok) {
throw new Error(`GitHub HTTP ${res.status} for ${url}`);
}
return res.json();
}
async function buildLivePayload(env) {
const token = env?.GITHUB_TOKEN || '';
const [repoRes, releasesRes] = await Promise.allSettled([
fetchGitHubJson(GITHUB_REPO_API, token),
fetchGitHubJson(GITHUB_RELEASES_API, token),
]);
if (releasesRes.status !== 'fulfilled') {
throw releasesRes.reason instanceof Error ? releasesRes.reason : new Error(String(releasesRes.reason));
}
const repo = repoRes.status === 'fulfilled' ? repoRes.value : null;
const rawReleases = releasesRes.value;
const releasesArr = Array.isArray(rawReleases) ? rawReleases : [];
const mapped = [];
for (const r of releasesArr) {
if (!r || r.draft) continue;
const tag = String(r.tag_name || '').trim();
if (!isClientTag(tag)) continue;
const prerelease = Boolean(r.prerelease);
const channel = classifyChannel(tag, prerelease);
const published = r.published_at || r.created_at || '';
const assets = extractAssets(r.assets);
const safeHtmlUrl =
sanitizeGitHubUrl(r.html_url) ||
`https://github.com/Nwflower/Reims-Go/releases/tag/${encodeURIComponent(tag)}`;
mapped.push({
entry: {
tag,
name: String(r.name || `Reims-Go ${tag}`).trim(),
published_at: published,
date: published ? published.slice(0, 10) : '',
html_url: safeHtmlUrl,
prerelease,
channel,
exe: assets.exe,
zip: assets.zip,
sha256_url: assets.sha256_url,
sections: parseBilingualBody(r.body || ''),
},
sha256_sums: assets.sha256_sums,
});
}
mapped.sort((a, b) => {
if (a.entry.channel === 'stable' && b.entry.channel !== 'stable') return -1;
if (a.entry.channel !== 'stable' && b.entry.channel === 'stable') return 1;
return (b.entry.published_at || '').localeCompare(a.entry.published_at || '');
});
const entries = mapped.map((m) => m.entry);
const topStable = mapped.find((m) => m.entry.channel === 'stable') || mapped[0] || null;
const nowIso = new Date().toISOString();
const latest = {
synced_at: nowIso,
stars: typeof repo?.stargazers_count === 'number' ? repo.stargazers_count : 1868,
version: topStable?.entry.tag || 'v0.2.12',
published_at: topStable?.entry.published_at || nowIso,
html_url: topStable?.entry.html_url || CANONICAL_RELEASES_URL,
exe: topStable?.entry.exe || null,
zip: topStable?.entry.zip || null,
sha256_url: topStable?.entry.sha256_url || null,
sha256_sums: topStable?.sha256_sums || '',
};
return {
source: 'edge-api',
synced_at: nowIso,
latest,
entries,
};
}
function buildEdgeJsonResponse(payload) {
return new Response(JSON.stringify(payload), {
status: 200,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': `public, max-age=120, s-maxage=${EDGE_STORE_SECONDS}`,
'X-Reims-Cache': 'MISS',
'X-Reims-Source': 'edge-api',
'X-Reims-Fetched-At': String(Date.now()),
},
});
}
async function fetchAndCacheLive(cache, cacheKey, env) {
if (!liveInflight) {
liveInflight = buildLivePayload(env)
.then((payload) => {
const res = buildEdgeJsonResponse(payload);
return cache
.put(cacheKey, res.clone())
.catch(() => {})
.then(() => res);
})
.finally(() => {
liveInflight = null;
});
}
return liveInflight;
}
async function handleReleasesApi(request, env, ctx) {
const url = new URL(request.url);
const cacheKey = new Request(`${url.origin}/api/github/releases`, { method: 'GET' });
const cache = caches.default;
const isHead = request.method === 'HEAD';
const cached = await cache.match(cacheKey);
if (cached) {
const fetchedAt = Number(cached.headers.get('X-Reims-Fetched-At') || '0');
const isEdgeEntry = cached.headers.get('X-Reims-Source') === 'edge-api';
const isStale = isEdgeEntry && fetchedAt > 0 && Date.now() - fetchedAt > EDGE_FRESH_MS;
if (isStale) {
ctx.waitUntil(fetchAndCacheLive(cache, cacheKey, env).catch(() => {}));
}
const headers = new Headers(cached.headers);
headers.set('X-Reims-Cache', isStale ? 'STALE' : 'HIT');
return new Response(isHead ? null : cached.body, {
status: cached.status,
statusText: cached.statusText,
headers,
});
}
try {
const liveRes = await (liveInflight || buildLivePayload(env).then((payload) => buildEdgeJsonResponse(payload)));
// Cache live response via ctx.waitUntil so client gets an immediate response
const clonedForCache = liveRes.clone();
ctx.waitUntil(cache.put(cacheKey, clonedForCache).catch(() => {}));
if (isHead) {
return new Response(null, { status: liveRes.status, headers: liveRes.headers });
}
return liveRes;
} catch (err) {
console.warn(
JSON.stringify({
level: 'warn',
event: 'github_releases_fallback',
error: err instanceof Error ? err.message : String(err),
}),
);
if (env?.ASSETS) {
try {
const fallbackRes = await env.ASSETS.fetch(new Request(`${url.origin}/data/releases-bundle.json`));
if (fallbackRes.ok) {
const fallbackHeaders = {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': `public, max-age=${FALLBACK_CACHE_SECONDS}, s-maxage=${FALLBACK_CACHE_SECONDS}`,
'X-Reims-Cache': 'FALLBACK',
'X-Reims-Source': 'static-fallback',
'X-Reims-Fetched-At': String(Date.now()),
};
const out = new Response(fallbackRes.body, {
status: 200,
headers: fallbackHeaders,
});
// Negative-cache fallback for 60s to shield GitHub API during outages / rate limits
ctx.waitUntil(cache.put(cacheKey, out.clone()).catch(() => {}));
if (isHead) {
return new Response(null, { status: 200, headers: fallbackHeaders });
}
return out;
}
} catch (assetErr) {
console.warn(
JSON.stringify({
level: 'warn',
event: 'github_releases_assets_fallback_failed',
error: assetErr instanceof Error ? assetErr.message : String(assetErr),
}),
);
}
}
return new Response(isHead ? null : JSON.stringify({ error: 'Unable to fetch GitHub releases' }), {
status: 502,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
},
});
}
}
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (url.pathname === '/api/github/releases') {
if (request.method === 'GET' || request.method === 'HEAD') {
return handleReleasesApi(request, env, ctx);
}
return new Response(JSON.stringify({ error: 'Method Not Allowed' }), {
status: 405,
headers: {
...API_SECURITY_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
Allow: 'GET, HEAD',
},
});
}
if (env?.ASSETS) {
return env.ASSETS.fetch(request);
}
return new Response('Not Found', { status: 404 });
},
};