Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions src/lib/submission-checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* - `repo` 不存在 / 私有 / 无法核验 → **硬拦**(error)
* - 外链失败 → **默认只警告**,由评审人人工确认;
* 但「官方项目的全部外链」与「任何项目的演示站(homepage)」失败 → **硬拦**(error)
* - 例外(返工口径,见 ONE-449):外链返回 **HTTP 403** 时一律降级为 warning。
* CDN(Cloudflare Pages 等)的 bot 防护会拒绝 CI runner 出口 IP,403 说明站点在线、
* 只是不许探针访问,不构成「不可达」结论;输出保留站点名与状态码供人眼复核。
* 真不可达(DNS / 连接失败 / 超时)与 404 仍按上面的分级判 fail。
* - 截图不合规 → **硬拦**(error)
*
* 校验函数全部是「注入 fetch / 注入目录」的纯逻辑,磁盘与网络都在边界上,便于单测与演练。
Expand All @@ -25,6 +29,8 @@ export const SCREENSHOT_REQUIRED_EXT = '.webp';

export const DEFAULT_LINK_TIMEOUT_MS = 8_000;
export const DEFAULT_LINK_CONCURRENCY = 6;
/** CDN bot 防护拒绝 CI 探针时返回的状态码:不判「不可达」,降级为 warning */
export const BOT_PROTECTION_STATUS = 403;
export const DEFAULT_API_BASE = 'https://api.github.com';
const USER_AGENT = 'workerhub-hub-ci (+https://hub.oneboy.app)';

Expand Down Expand Up @@ -243,6 +249,8 @@ export function collectLinks(data: ProjectInput): ProjectLink[] {
* 外链失败时的严重级别(§7 原文):
* 「失败给 warning 不硬拦(评审人人工确认);官方项目与演示站链接失败则硬拦」。
* 即:`source=official` 的任何外链、以及任何项目的 `homepage`(官网/演示站)→ error。
*
* 注意:这只是基础分级;HTTP 403(bot 防护)的例外由 `resolveLinkFailureSeverity` 叠加。
*/
export const linkFailureSeverity = (data: ProjectInput, field: LinkField): Severity =>
data.source === 'official' || field === 'homepage' ? 'error' : 'warning';
Expand All @@ -251,8 +259,24 @@ export interface LinkProbeResult {
url: string;
ok: boolean;
detail: string;
/** HTTP 状态码;请求本身失败(DNS / 连接 / 超时)时为 undefined */
status?: number;
}

/** 是否为 CDN bot 防护产生的 403(站点在线、只是拒绝 CI 探针) */
export const isBotProtectionStatus = (status: number | undefined): boolean =>
status === BOT_PROTECTION_STATUS;

/**
* 外链失败后的最终严重级别:§7 基础分级之上叠加 403 例外。
* 403 → warning(不判 fail),其余状态一律沿用 `linkFailureSeverity`(真不可达 / 404 仍按 §7 判 fail)。
*/
export const resolveLinkFailureSeverity = (
data: ProjectInput,
field: LinkField,
status?: number,
): Severity => (isBotProtectionStatus(status) ? 'warning' : linkFailureSeverity(data, field));

/** 探测单条外链是否可达(2xx/3xx 视为可达;跟随重定向) */
export async function probeUrl(url: string, options: HttpOptions = {}): Promise<LinkProbeResult> {
const headers: Record<string, string> = {
Expand All @@ -267,9 +291,9 @@ export async function probeUrl(url: string, options: HttpOptions = {}): Promise<
}

if (response.status >= 200 && response.status < 400) {
return { url, ok: true, detail: `HTTP ${response.status}` };
return { url, ok: true, detail: `HTTP ${response.status}`, status: response.status };
}
return { url, ok: false, detail: `HTTP ${response.status}` };
return { url, ok: false, detail: `HTTP ${response.status}`, status: response.status };
}

/** 逐项目逐链接探测(并发受限),按 §7 分级产出 findings */
Expand All @@ -294,10 +318,12 @@ export async function checkLinks(
);
for (const { target, link, probe } of results) {
if (probe.ok) continue;
const severity = linkFailureSeverity(target.data, link.field);
const message = `外链不可达(${link.field},${probe.detail})${
severity === 'warning' ? ':投稿者可稍后修正,评审人需人工确认链接是否长期失效' : ''
}`;
const severity = resolveLinkFailureSeverity(target.data, link.field, probe.status);
const message = isBotProtectionStatus(probe.status)
? `站点 ${target.data.name} 的 ${link.field} 返回 HTTP ${probe.status}(CDN bot 防护拦截 CI 探针,站点在线、不判不可达):已降级为警告,需人工复核该链接`
: `外链不可达(${link.field},${probe.detail})${
severity === 'warning' ? ':投稿者可稍后修正,评审人需人工确认链接是否长期失效' : ''
}`;
findings.push(
severity === 'error'
? errorFinding('links', target, link.url, message)
Expand Down
106 changes: 106 additions & 0 deletions tests/submission-checks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@ import { join } from 'node:path';
import { test } from 'node:test';
import { projectSchema, type ProjectInput } from '../src/lib/project-schema.js';
import {
BOT_PROTECTION_STATUS,
SCREENSHOT_MAX_BYTES,
checkLinks,
checkRepoAccess,
checkRepos,
checkScreenshots,
collectLinks,
formatFindings,
isBotProtectionStatus,
linkFailureSeverity,
probeUrl,
resolveLinkFailureSeverity,
screenshotFileName,
summarize,
type CheckTarget,
Expand Down Expand Up @@ -236,6 +239,109 @@ test('§7 官方项目 / 演示站链接失败 → error(硬拦)', async ()
assert.ok(findings.every((finding) => finding.severity === 'error'));
});

test('ONE-449 HTTP 403(bot 防护)→ 官方演示站也降级为 warning,不判 fail', async () => {
const findings = await checkLinks(
[
target({
slug: 'enotify',
name: 'eNotify',
repo: 'WorkerHub/eNotify',
source: 'official',
tier: 'official',
homepage: 'https://enotify.oneboy.app',
}),
target({
slug: 'post',
name: 'post',
repo: 'WorkerHub/post',
source: 'official',
tier: 'official',
homepage: 'https://post.oneboy.app',
}),
],
{
fetchImpl: async () => new Response('forbidden', { status: 403 }),
retries: 0,
},
);

assert.equal(findings.length, 2);
assert.ok(findings.every((finding) => finding.severity === 'warning'));
assert.equal(summarize(findings).errors.length, 0);

const log = formatFindings(summarize(findings));
// 输出保留站点名与 403 状态码,供人眼复核
assert.match(log, /⚠ \[links\] enotify\.yaml(enotify).*eNotify.*403/);
assert.match(log, /⚠ \[links\] post\.yaml(post).*post.*403/);
});

test('ONE-449 403 例外只针对 403:真不可达与 404 依旧判 fail(fail 分支未被放宽)', async () => {
const officialHome = { slug: 'dead-home', homepage: 'https://dead.example.com' };

const refused = await checkLinks([target(officialHome)], {
retries: 0,
fetchImpl: async () => {
throw new TypeError('fetch failed');
},
});
assert.equal(refused.length, 1);
assert.equal(refused[0]!.severity, 'error');
assert.match(refused[0]!.message, /请求失败/);

const notFound = await checkLinks([target(officialHome)], {
retries: 0,
fetchImpl: async () => new Response('nope', { status: 404 }),
});
assert.equal(notFound.length, 1);
assert.equal(notFound[0]!.severity, 'error');
assert.match(notFound[0]!.message, /404/);

const serverError = await checkLinks([target(officialHome)], {
retries: 0,
fetchImpl: async () => new Response('boom', { status: 500 }),
});
assert.equal(serverError[0]!.severity, 'error');
});

test('resolveLinkFailureSeverity:仅 403 降级,其余沿用 §7 基础分级', () => {
const official = baseProject({
source: 'official',
repo: 'WorkerHub/eNotify',
tier: 'official',
});
assert.equal(BOT_PROTECTION_STATUS, 403);
assert.equal(isBotProtectionStatus(403), true);
assert.equal(isBotProtectionStatus(404), false);
assert.equal(isBotProtectionStatus(undefined), false);

assert.equal(resolveLinkFailureSeverity(official, 'homepage', 403), 'warning');
assert.equal(resolveLinkFailureSeverity(official, 'homepage', 404), 'error');
assert.equal(resolveLinkFailureSeverity(official, 'homepage'), 'error');
assert.equal(resolveLinkFailureSeverity(baseProject(), 'docs_url', 403), 'warning');
assert.equal(resolveLinkFailureSeverity(baseProject(), 'docs_url', 503), 'warning');

// 基础分级本身不变(§7 原文口径)
assert.equal(linkFailureSeverity(official, 'homepage'), 'error');
});

test('probeUrl:403 视为不可达但带上状态码,供上层降级判断', async () => {
const forbidden = await probeUrl('https://enotify.oneboy.app', {
fetchImpl: async () => new Response('forbidden', { status: 403 }),
});
assert.equal(forbidden.ok, false);
assert.equal(forbidden.status, 403);
assert.match(forbidden.detail, /403/);

const failed = await probeUrl('http://127.0.0.1:9/', {
retries: 0,
fetchImpl: async () => {
throw new TypeError('fetch failed');
},
});
assert.equal(failed.ok, false);
assert.equal(failed.status, undefined);
});

// ---------------------------------------------------------------------------
// 截图规格
// ---------------------------------------------------------------------------
Expand Down
80 changes: 79 additions & 1 deletion tests/submission-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
* 全部走真实 `tsx scripts/validate-submission.ts` 进程,只把网络与目录换成夹具/不可达地址。
*/
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { spawn, spawnSync } from 'node:child_process';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { join } from 'node:path';
import { test } from 'node:test';

Expand All @@ -29,6 +32,27 @@ const run = (args: string[], env: Record<string, string> = {}): RunResult => {
return { status: result.status, output: `${result.stdout ?? ''}${result.stderr ?? ''}` };
};

/** 异步版:需要本地 HTTP 服务在 CLI 子进程运行期间保持可响应时用(spawnSync 会堵死父进程事件循环) */
const runAsync = (args: string[], env: Record<string, string> = {}): Promise<RunResult> =>
new Promise((resolve, reject) => {
const child = spawn(
process.execPath,
['--import', 'tsx', 'scripts/validate-submission.ts', ...args],
{ cwd: ROOT, env: { ...process.env, GITHUB_TOKEN: '', ...env } },
);
let output = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk: string) => {
output += chunk;
});
child.stderr.on('data', (chunk: string) => {
output += chunk;
});
child.on('error', reject);
child.on('close', (status) => resolve({ status, output }));
});

test('§7 截图不合规 → CLI 失败并逐条点名原因(宽不足 / 超体积 / 假 webp)', () => {
const result = run(['--checks=screenshots'], {
HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'screenshots'),
Expand Down Expand Up @@ -78,6 +102,60 @@ test('§7 --fail-on-warnings 把外链警告升级为失败(维护者本地复
assert.match(result.output, /警告 2 项/);
});

test('ONE-449 官方演示站 403(bot 防护)→ CLI 退出码 0,日志可见站点名与 403', async () => {
// 本地服务固定回 403,模拟 Cloudflare bot 防护对 CI runner 出口 IP 的拒绝
const server = createServer((_request, response) => {
response.writeHead(403, { 'content-type': 'text/html; charset=utf-8' });
response.end('<html><body>error 403</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;

const projectsDir = join(ROOT, 'tests', '.tmp', 'bot-protected');
try {
mkdirSync(projectsDir, { recursive: true });
writeFileSync(
join(projectsDir, 'drill-bot-protected.yaml'),
[
'slug: drill-bot-protected',
'name: Drill Bot Protected',
'repo: WorkerHub/hub-drill-official',
'source: official',
'tagline_zh: 演练用官方条目,演示站被 bot 防护拦截。',
'description_zh: 第一条说明句。第二条说明句。',
'features:',
' - 特性一',
' - 特性二',
' - 特性三',
'tags:',
' - drill',
'category: notification',
`homepage: http://127.0.0.1:${port}/demo`,
'deploy:',
' method: docs-only',
'resources:',
' - d1',
'difficulty: 2',
'free_tier: yes',
'tier: official',
'added_at: 2026-10-26',
'',
].join('\n'),
'utf8',
);

const result = await runAsync(['--checks=links'], { HUB_PROJECTS_DIR: projectsDir });
assert.equal(result.status, 0, result.output);
assert.match(result.output, /警告 1 项/);
assert.match(result.output, /Drill Bot Protected/);
assert.match(result.output, /403/);
assert.match(result.output, /降级为警告/);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
rmSync(projectsDir, { recursive: true, force: true });
}
});

test('未知检查项 → 退出码 2(参数错误,不误报成数据错误)', () => {
const result = run(['--checks=nope'], {
HUB_PROJECTS_DIR: join(FIXTURES, 'submission', 'repos'),
Expand Down
Loading