Compare commits

...
17 changed files with 836 additions and 242 deletions

No files matched your search

+2
View File
@@ -28,3 +28,5 @@
- 接入所需邮箱验证码,按用户2026-10-20长期授权,先用已登记的对应邮箱自行登录并只读取本次验证邮件;凭据仍走GemDocs统一字段入口,不改账号安全设置、不读取无关邮件。只有资料缺失、认证失败或必须人工完成的验证才请求用户协助;账号切换及网站访问边界继续适用。
本文件提供维护入口,不扩大当前任务授权,也不启动无人值守自动维护。
FUC独立导航公共域名与禁选状态统一按[DomainHub接入](docs/maintenance/NAVIGATION_DOMAINHUB.md)维护;不涉及XB核心。
+37
View File
@@ -0,0 +1,37 @@
# FUC独立导航的DomainHub接入
2026-11-09获准与DomainHub/FNA统一。只改项目专属导航素材、生成器和独立统计服务的公共读取/跳转入口,未改XB核心、主站业务、认证、支付、订阅或节点。唯一策略和任何聊天入口见[DomainHub公共域名](/Users/hellcat/Documents/GemCodes/atom/codex/output/docs/domainhub-public.md)。
公共候选由DomainHub生成;原`config/project-domains/fuc.json`保留为初始展示/历史兼容种子,不能用它覆盖DomainHub状态。线上实际清单和默认选择始终读取本机签名快照,页面启动不使用种子URL跳转。以后新域名通过统一register/enroll/status发布,导航每4小时拉取新版本,每天08:10完整拉取,页面每分钟刷新本机清单。原JSON不再是活动写入口,后续维护以运行快照导出为准。
`/_nav-routes`返回已登记公共下游及可公开的状态,不返回操作证据正文、私有配置或密钥。2026-11-09用户明确区分导航与广告:导航的需翻墙/疑似/被墙入口均可手动选择,显示“不测速”,只对合格入口发测速请求。适配器分别输出selectable和probe_enabled,保留原eligible为广告资格;不改DomainHub访问标记。停用、登记地址改变、未到启用时间仍不可选择。选择后走`/_nav-go?route=<固定代号>&code=<合法邀请码>`,服务器按同一手动选择规则校验;未登记/停用入口及任意URL参数410,合法已登记入口302并保留邀请码。静态无JS按钮仍走固定代号出口。
同步脚本/私有配置/水位在FUC服务器;root不运行常驻业务,fuc-nav-stats专用用户消费。`/var/lib/fuc-navigation-domainhub/state.json`及`.watermark`须一致且24小时内成功校验,异常拒绝选择。独立统计服务复用自己的环回端口18248,新增只读GET;原测速统计、日报数据库与TeleHub info权限保留。统计只接受已登记代号子集,匿名结果不改变域名访问状态。FNA负责统一广告无候选Critical,不重复在导航发同一告警。
专属Nginx仅新增两个精确API location与导航JS静态文件。浏览器只连接签名清单的HTTPS公共测速接口,发送omit credentials、无referrer、不跟随跳转;connect-src允许HTTPS以支持后续自动新增域名,script/style/default/frame策略保持。没有给XB面板或其他站点扩展CORS或路由。
本地回归覆盖禁选、即时点击撤销、邀请码、旧版本与过期、统计子集及历史报告兼容;发布从明确Git提交提取导航公开文件和ops,切独立current。当前发布/回执状态见下方回执。回退不得用旧硬编码导航绕开已知禁选;优先保持解析与保护,回退非策略界面。不得还原水位或删除状态历史。
## 2026-11-09已发布
导航Git提交`21ef7824f1018e56d909357b61610acb4ba0eec1`,前版本`bcdbfcad5a69ea99aa5d0af1345514393fdf3d44`;VPS-004:`/var/www/wwwroot/fuc-navigation/current`原子指向新release。专属配置/原SHA恢复点`/var/lib/fuc-deploy/domainhub-public-20261109/backup`。第一次就绪检查早于端口监听,已自动回退;确认无服务错误后加入最多5秒实际就绪轮询,重试成功。
DomainHub client4,production/navigation,版本35/applied。初次发布中fu99.cloud/fuuu.online合格,其余三个曾禁选;后续按下方用户纠正改为五个入口均可手动选择、仅两个参与测速。默认按最新正式启用入口,浏览器测速可在合格项中选最快;人工选择在重新检测时保留。运行时只读生成物`/var/lib/fuc-navigation-domainhub/fuc.json`带来源和版本;旧repo JSON不是状态写入口。
两只新增同步timer active,原统计服务及日报timer active;统计SQLite数据和原info调用权限保留。FUC主站仍为`4590fb547b5362f002ae6fd2f7f44511e9968664`,未随导航切换。白色机只在现有导航块增加application/json替换和五个已登记面板Location映射;未新增反代域名/改上游。恢复点`/root/codex-backups/domainhub-public-20261109/white-nav.before`,当前期望`white-nav.after`;回退前核对差异及后续变更,不用旧统计备份覆盖新版。
正式导航和既有fu-nav3.tomtojapan.online反代均服务器侧验证200页面/脚本/清单、无私有证据字段、两个合格入口、三个禁选入口410、邀请码302/no-store和精确反代Location。3项导航Python测试及6项共享消费测试通过;IAB本地交互通过。已完成服务器侧验收,未做线上页面验收。
2026-11-09用户进一步指定版本检查改为每4小时;开机90秒检查、每天北京时间08:10完整同步和统一命令变更后立即同步保持。仅从对应Git提交安装同步timer,应用代码版本沿用上述功能版本;备份及源提交回执在同服务器`/var/lib/fuc-deploy/domainhub-public-20261109/interval-4h/`。回退只恢复该timer后daemon-reload并重启timer,不重启业务进程。
2026-11-09 导航发布 `425f6a31215886d5b5d32980f5e6970429711531`,父提交 `21ef7824f1018e56d909357b61610acb4ba0eec1`。邮箱提示补充验证码邮件的自动回复说明,信封换成珊瑚红柔光感叹号,页面入口标签统一使用「地址」。正式福云的验证码发件和 Reply-To 地址均回读指向 fu@gemcook.net。生成器核对通过,正式导航与已登记反代的文案、图标、入口标签和运行清单均完成服务器侧回读。未做线上页面验收。回退见 site-jp01 `/var/lib/fuc-deploy/fuc-navigation-mail-reminder-20261109-425f6a3/rollback.json`。
## 导航手动选择与测速分离(2026-11-09)
用户要求导航所有已登记有效入口可手动选择,墙状态只影响自动测速;广告继续按DomainHub原资格过滤。本次修正适配器、固定跳转和前端,未改广告端、共享XB核心、域名状态或每4小时/每日08:10调度。保留山田的425f6a3邮箱说明、红色感叹号及“地址”文案。
最低延迟样式原本仍在,但DomainHub新脚本漏写data-fastest;现已恢复,手动选择慢线不改变最低延迟标记。同一地址与策略的每分钟清单刷新保留测速值和手动选择,修复停留后被重置为“—”;地址/策略改变才丢弃旧值,重新检测先清旧高亮,全部失败不高亮。脚本版本manual-select-fastest-1用于刷新旧缓存。
6项导航Python测试与2项执行真实脚本的DOM行为测试覆盖手动选择、跳转、访问状态不变、停止测速、停用/未知代号拒绝、过期快照、刷新保留、最快切换与失败;本地IAB已实际选择疑似被墙入口、重新检测并截图确认荧光绿。生产发布及回退回执位于site-jp01 `/var/lib/fuc-deploy/domainhub-public-20261109/manual-selection/`;只切独立导航current并重启专属统计服务,原配置、统计数据、日报及同步timer保持。回退指回previous-sha并重启该服务。
2026-11-09 导航发布 `e5d19abafe052700d2f6eb5e3c4cd89e73a5ee77`,将验证码邮件说明的末句改为「同样会自动回复最新地址」。生成器检查通过,正式导航与已登记反代均已从服务器侧回读,未做线上页面验收。回退指针见 site-jp01 `/var/lib/fuc-deploy/fuc-navigation-recovery-copy-20261109-e5d19ab/rollback.json`。
+5 -1
View File
@@ -1,6 +1,6 @@
# 项目域名清单与福云导航
项目面向用户的域名和用途维护在 [config/project-domains/](../../config/project-domains/)。每个项目使用独立的 JSON 文件,文件名为项目代号。DomainHub 继续维护 DNS、资源关系和地址发布台账;清单里的 `domainhub` 是对应记录代号,不包含凭据或私有入口。
项目面向用户的域名和用途维护在 [config/project-domains/](../../config/project-domains/)。每个项目使用独立的 JSON 文件,文件名为项目代号。DomainHub 维护地址发布与访问状态台账;DNS由原DNS系统维护;清单里的 `domainhub` 是对应记录代号,不包含凭据或私有入口。
- `role`:`primary` 永久主域名、`direct` 免翻墙域名、`navigation` 导航站域名。
- `access`:按需填写 `requires_proxy`(需翻墙)或 `suspected_blocked`(疑似被墙)。未填写表示没有登记额外限制,不表示做过当地线路测试。
@@ -22,3 +22,7 @@ node scripts/project-domains/manage.mjs check fuc
采集和日报在 site-jp01 执行。部署从 Git 同步导航资产和统计脚本,使用独立系统服务 `fuc-navigation-stats.service` 和 `fuc-navigation-report.timer`。日报凭据由后者通过 systemd 私有凭据读取。停止统计时先切回上一版导航,再撤销两端的统计入口并停用服务和定时器。保留统计库及已发回执。
发布只从指定 Git 提交提取 `public/brand/fuc-navigation/` 下的 `index.html`、`clipboard.mjs`、`logo.svg`,落在 `/var/www/wwwroot/fuc-navigation/releases/<SHA>`,再切换 `current`。静态清单不依赖面板或 DomainHub 在线。导航站的 CSP `connect-src` 放行五个面板域名及对应 tomtojapan 反代的测速接口,以及两个导航入口的统计地址。发布时分别核对两个导航域名发起的 CORS 请求,并回读 [导航根域](https://fu-nav3.com/)与已登记的 tomtojapan 反代。异常时将 `current` 指回上一次验收的版本,并恢复上一次导航 CSP。
2026-11-09起FUC导航活动清单由DomainHub签名快照生成,静态JSON只作初始/历史兼容;后续域名新增或禁选统一按[导航接入](NAVIGATION_DOMAINHUB.md)及其公共操作入口执行,不再直接编辑JSON作为线上状态。
2026-11-09当前导航手动选择与自动测速分开:已登记有效入口可手动选择;需翻墙、疑似/被墙显示“不测速”。仅合格入口参与测速/统计,最低延迟荧光绿;每分钟清单刷新保留同一地址的测量结果和手动选择。广告仍严格过滤访问状态。前述“五个入口全部测速”属于接入DomainHub前的历史,当前合同见[导航维护](NAVIGATION_DOMAINHUB.md)。
+27 -119
View File
@@ -56,10 +56,20 @@
font-size: 15px;
}
.email-notice-icon {
width: 19px;
height: 19px;
margin-top: 2px;
color: var(--accent);
display: inline-grid;
place-items: center;
width: 1.45em;
height: 1.45em;
margin-top: 1px;
border-radius: .45em;
color: #ff92ad;
background: linear-gradient(145deg, #ff779c39, transparent 150%);
box-shadow: 0 0 .55em #ff779c39, inset 0 0 0 1px #ff779c39;
}
.email-notice-icon svg {
width: 1.12em;
height: 1.12em;
filter: drop-shadow(0 0 .2em #ff779c39);
}
.email-notice p { margin: 0; }
.email-notice .email-detail { margin-top: 4px; color: var(--muted); font-size: 14px; line-height: 1.65; text-wrap: pretty; }
@@ -161,10 +171,11 @@
<main class="wrap">
<h1>福云地址导航</h1>
<aside class="email-notice" aria-label="备用网址获取方式">
<svg class="email-notice-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="2.5" y="5" width="19" height="14" rx="2"/>
<path d="m3.5 6.5 8.5 7 8.5-7"/>
</svg>
<span class="email-notice-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 5v9"/><circle cx="12" cy="18.5" r="1" fill="currentColor" stroke="none"/>
</svg>
</span>
<div>
<p>务必,请收藏我们的邮箱
<span class="copy-control">
@@ -178,6 +189,7 @@
</span>。
</p>
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
<p class="email-detail">如果忘记收藏邮箱,也可以找注册福云时发送验证码的邮箱,同样会自动回复最新地址。</p>
</div>
</aside>
<section class="entries" aria-labelledby="entry-title">
@@ -186,27 +198,27 @@
<!-- project-domains:start -->
<label class="entry" data-role="primary">
<input type="radio" name="route" value="https://xn--9kqy16h.com/" data-domainhub-code="fuc.main-cn">
<span class="entry-info"><strong>福云.com</strong><small>永久主域名(需翻墙)</small></span>
<span class="entry-info"><strong>福云.com</strong><small>永久主地址(需翻墙)</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="primary">
<input type="radio" name="route" value="https://fuuu.cloud/" data-domainhub-code="fuc.main-en">
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主域名(需翻墙)</small></span>
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主地址(需翻墙)</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://fu99.cloud/" data-domainhub-code="fuc.direct-current" checked>
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙域名</small></span>
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙地址</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://fuuu.online/" data-domainhub-code="fuc.fuuu-online">
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙域名</small></span>
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙地址</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://xn--123-9i9dj97q.com/" data-domainhub-code="fuc.direct-cn-backup">
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙域名(疑似被墙)</small></span>
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙地址(疑似被墙)</small></span>
<span class="latency">—</span>
</label>
<!-- project-domains:end -->
@@ -216,115 +228,11 @@
<button class="recheck" type="button">重新检测</button>
</div>
<div class="actions">
<a id="enter" class="enter" href="https://fu99.cloud/#/register">立即进入 →</a>
<a id="enter" class="enter" href="/_nav-go?route=fuc.direct-current">立即进入 →</a>
</div>
</section>
</main>
<script>
const panel = document.querySelector('.entries');
const routes = document.querySelector('.routes');
const status = document.querySelector('#route-status');
const enter = document.querySelector('#enter');
const recheck = document.querySelector('.recheck');
const invite = new URLSearchParams(location.search).get('code');
const entries = [...routes.querySelectorAll('input[name="route"]')].map(input => {
const row = input.closest('label');
return { input, row, result: row.querySelector('.latency') };
});
const isLocal = location.hostname === 'xb.loc';
const probePath = '/api/v1/guest/comm/config';
const probeTimeoutMs = 3000;
let manualSelection = false;
let testStatus = '';
function selectRoute() {
const selected = routes.querySelector('input:checked');
const origin = isLocal ? location.origin : new URL(selected.value).origin;
const code = invite && /^[A-Za-z0-9_-]{1,64}$/.test(invite) ? '?code=' + encodeURIComponent(invite) : '';
enter.href = origin + '/#/register' + code;
const name = selected.closest('label').querySelector('strong').textContent;
status.textContent = ['已选择 ' + name, testStatus].filter(Boolean).join(' · ');
}
async function measure(entry, sample) {
const url = new URL(probePath, isLocal ? location.origin : entry.input.value);
url.searchParams.set('nav_probe', sample);
const controller = new AbortController();
const started = performance.now();
const timeout = setTimeout(() => controller.abort(), probeTimeoutMs);
try {
const response = await fetch(url, {
mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error',
referrerPolicy: 'no-referrer', signal: controller.signal,
});
if (!response.ok) throw new Error('Probe failed');
const { data } = await response.json();
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
const elapsed = performance.now() - started;
entry.outcome = 'success';
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
return { entry, elapsed };
} catch {
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
return null;
} finally {
clearTimeout(timeout);
}
}
async function testRoutes() {
if (recheck.disabled) return;
recheck.disabled = true;
panel.setAttribute('aria-busy', 'true');
testStatus = isLocal ? '本地测速中…' : '正在测速…';
selectRoute();
for (const { result } of entries) {
result.removeAttribute('data-fastest');
result.textContent = '测速中…';
}
try {
const round = Date.now().toString(36);
const results = await Promise.all(entries.map((entry, index) => measure(entry, round + '-' + index)));
const ranked = results.filter(Boolean).sort((a, b) => a.elapsed - b.elapsed);
const measured = new Set(ranked.map(({ entry }) => entry));
const ordered = [...ranked.map(({ entry }) => entry), ...entries.filter(entry => !measured.has(entry))];
const focused = document.activeElement;
for (const { row } of ordered) {
if (row.dataset.role !== 'primary') routes.append(row);
}
if (routes.contains(focused) && document.activeElement !== focused) focused.focus({ preventScroll: true });
const fastest = ranked[0];
if (fastest) {
fastest.entry.result.setAttribute('data-fastest', '');
if (!manualSelection) fastest.entry.input.checked = true;
}
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
if (!isLocal) {
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
fetch('/_nav-stats', {
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
}).catch(() => {});
}
} finally {
recheck.disabled = false;
panel.removeAttribute('aria-busy');
selectRoute();
}
}
routes.addEventListener('click', event => {
if (event.target.matches('input[name="route"]')) manualSelection = true;
});
routes.addEventListener('change', () => {
manualSelection = true;
selectRoute();
});
recheck.addEventListener('click', testRoutes);
selectRoute();
testRoutes();
</script>
<script src="./navigation-domainhub.js?v=manual-select-fastest-1"></script>
<script type="module">
import { copyText } from './clipboard.mjs';
+124
View File
@@ -0,0 +1,124 @@
// Public routes come from this navigation server's verified DomainHub snapshot.
// Manual navigation does not change advertising eligibility or access status.
(() => {
const routes = document.querySelector('.routes');
const panel = document.querySelector('.entries');
const status = document.querySelector('#route-status');
const enter = document.querySelector('#enter');
const recheck = document.querySelector('.recheck');
const invite = new URLSearchParams(location.search).get('code') || '';
const isLocal = location.hostname === 'xb.loc';
let entries = [], manual = false, busy = false;
const roles = {primary: '永久主地址', direct_access: '免翻墙地址'};
const reasons = {requires_proxy: '需翻墙', suspected_blocked: '疑似被墙', blocked: '已标记被墙', unknown: '待确认', disabled: '已停用', service_unhealthy: '暂不可用', service_unknown: '待确认', registration_changed: '待确认', evidence_expired: '待确认'};
const selected = () => entries.find(e => e.input.checked && !e.input.disabled);
const ranked = () => entries.filter(e => e.probe_enabled && e.outcome === 'success' && Number.isFinite(e.elapsed)).sort((a, b) => a.elapsed - b.elapsed);
function highlightFastest() {
const fastest = ranked()[0]?.elapsed;
for (const entry of entries) {
entry.result.toggleAttribute('data-fastest', fastest !== undefined && entry.probe_enabled && entry.outcome === 'success' && entry.elapsed === fastest);
}
}
function update() {
const entry = selected();
if (!entry) {
enter.removeAttribute('href'); enter.setAttribute('aria-disabled', 'true');
status.textContent = '暂未找到可用入口'; return;
}
const params = new URLSearchParams({route: entry.code});
if (/^[A-Za-z0-9_-]{1,128}$/.test(invite)) params.set('code', invite);
enter.href = isLocal ? '/#/register' + (params.has('code') ? '?code=' + encodeURIComponent(invite) : '') : '/_nav-go?' + params;
enter.removeAttribute('aria-disabled'); status.textContent = '已选择 ' + entry.hostname;
}
function render(records) {
const previous = selected()?.code;
const measurements = new Map(entries.map(e => [e.code, e]));
routes.replaceChildren(); entries = [];
records.sort((a, b) => (a.role === 'primary' ? 0 : 1) - (b.role === 'primary' ? 0 : 1) || Number(b.probe_enabled) - Number(a.probe_enabled) || b.priority - a.priority || b.activated_at.localeCompare(a.activated_at));
for (const e of records.filter(e => e.role !== 'navigation')) {
const row = document.createElement('label'); row.className = 'entry'; row.dataset.role = e.role === 'primary' ? 'primary' : 'direct';
const input = document.createElement('input'); input.type = 'radio'; input.name = 'route'; input.value = e.url; input.dataset.domainhubCode = e.code; input.disabled = e.selectable !== true;
const info = document.createElement('span'); info.className = 'entry-info';
const strong = document.createElement('strong'); strong.textContent = e.display_name || e.hostname;
const small = document.createElement('small');
small.textContent = (roles[e.role] || '入口') + (e.probe_enabled ? '' : '(' + (reasons[['blocked', 'suspected_blocked', 'requires_proxy'].includes(e.access) ? e.access : e.reason] || '待确认') + ')');
info.append(strong, small);
const result = document.createElement('span'); result.className = 'latency'; result.textContent = input.disabled ? '暂不可用' : e.probe_enabled ? '—' : '不测速';
const entry = {...e, row, input, result};
const old = measurements.get(e.code);
// A routine catalog refresh must retain results and the manual selection.
// A URL or policy change invalidates measurements for that entry.
if (e.probe_enabled && old?.probe_enabled && old.url === e.url && old.outcome) {
entry.elapsed = old.elapsed; entry.outcome = old.outcome; result.textContent = old.result.textContent;
}
row.append(input, info, result); routes.append(row); entries.push(entry);
}
const available = entries.filter(e => e.selectable);
const ordered = available.filter(e => e.probe_enabled).sort((a, b) => (a.role === 'direct_access' ? 0 : 1) - (b.role === 'direct_access' ? 0 : 1) || b.priority - a.priority || b.activated_at.localeCompare(a.activated_at));
const chosen = (manual && available.find(e => e.code === previous)) || ranked()[0] || ordered[0] || available[0];
if (chosen) chosen.input.checked = true;
highlightFastest(); update();
}
async function refresh() {
if (isLocal) return;
const response = await fetch('/_nav-routes', {cache: 'no-store', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(5000)});
if (!response.ok) throw Error('unavailable');
const data = await response.json();
if (!Array.isArray(data.entries)) throw Error('invalid');
render(data.entries);
}
async function measure(entry) {
if (!entry.probe_enabled || !entry.selectable) return;
const started = performance.now(); entry.result.textContent = '测速中…';
try {
const url = new URL('/api/v1/guest/comm/config', isLocal ? location.origin : entry.url);
url.searchParams.set('nav_probe', Date.now());
const response = await fetch(url, {mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(3000)});
if (!response.ok || typeof (await response.json()).data?.app_name !== 'string') throw Error('failure');
entry.elapsed = Math.round(performance.now() - started); entry.outcome = 'success'; entry.result.textContent = entry.elapsed + ' ms';
} catch (error) {
entry.elapsed = null; entry.outcome = error.name === 'TimeoutError' ? 'timeout' : 'failure'; entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '未连通';
}
}
async function test() {
if (busy) return;
busy = true; recheck.disabled = true; panel.setAttribute('aria-busy', 'true');
try {
await refresh();
for (const entry of entries) {
delete entry.elapsed; delete entry.outcome; entry.result.removeAttribute('data-fastest');
}
await Promise.all(entries.map(measure));
const fastest = ranked()[0];
if (!manual && fastest) fastest.input.checked = true;
highlightFastest();
if (!isLocal) {
const results = Object.fromEntries(entries.filter(e => e.probe_enabled && e.outcome).map(e => [e.code, e.outcome]));
if (Object.keys(results).length) fetch('/_nav-stats', {method: 'POST', body: JSON.stringify(results), credentials: 'omit', keepalive: true, redirect: 'error', referrerPolicy: 'no-referrer'}).catch(() => {});
}
} catch { render([]); }
finally { busy = false; recheck.disabled = false; panel.removeAttribute('aria-busy'); update(); }
}
routes.addEventListener('change', () => { manual = true; update(); });
enter.addEventListener('click', event => { if (!selected()) event.preventDefault(); });
recheck.addEventListener('click', test);
if (isLocal) {
render([...routes.querySelectorAll('input')].map(input => {
const code = input.dataset.domainhubCode;
const access = code === 'fuc.direct-cn-backup' ? 'suspected_blocked' : ['fuc.main-cn', 'fuc.main-en'].includes(code) ? 'requires_proxy' : 'available';
return {code, url: input.value, hostname: input.closest('.entry').querySelector('strong').textContent, role: input.closest('.entry').dataset.role === 'primary' ? 'primary' : 'direct_access', selectable: true, probe_enabled: access === 'available', eligible: access === 'available', access, reason: access === 'available' ? null : access, priority: input.checked ? 1 : 0, activated_at: '2026-01-01'};
}));
} else {
for (const input of routes.querySelectorAll('input')) input.disabled = true;
enter.removeAttribute('href');
}
test();
setInterval(() => { if (!document.hidden && !busy) refresh().catch(() => render([])); }, 60000);
})();
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""The navigation server reads the same verified snapshot used by its pull job."""
import json
import os
import sys
import time
from urllib.parse import urlencode, urlsplit
from public_client import read, current, validate_manifest
CONFIG={'project':'fuc','environment':'production','instance':'navigation','providers':['fuc']}
def snapshot(path):
state=read(path)
if not current(state): raise ValueError('snapshot_missing_or_expired')
m=state['manifest']
watermark=read(str(path)+'.watermark',{})
if watermark.get('version')!=m.get('version') or not state.get('digest') or watermark.get('digest')!=state['digest']: raise ValueError('snapshot_rollback')
if any(m.get(k)!=CONFIG[k] for k in ('project','environment','instance')): raise ValueError('wrong_scope')
validate_manifest(m,CONFIG)
return state
def entries(path):
state=snapshot(path)
values=[]
for entry in state['manifest']['providers']['fuc']['entries']:
if entry['role']=='navigation': continue
entry=dict(entry)
entry['display_name']=entry['hostname'].encode('ascii').decode('idna')
if entry.get('valid_until'):
from datetime import datetime, timezone
if datetime.fromisoformat(entry['valid_until']).replace(tzinfo=timezone.utc).timestamp()<=time.time():
entry.update(eligible=False,reason='evidence_expired')
# Manual navigation and advertising have different audiences. A reachability
# warning suppresses automatic probes, but does not revoke a public link.
entry['selectable'] = entry.get('reason') in {None, 'requires_proxy', 'suspected_blocked', 'blocked', 'unknown', 'evidence_expired', 'service_unknown', 'service_unhealthy'}
entry['probe_enabled'] = entry['selectable'] and entry['eligible']
values.append(entry)
return state['manifest']['version'],values
def destination(path, code, invite=''):
_,values=entries(path)
item=next((e for e in values if e['code']==code and e['selectable']),None)
if not item: return None
import re
query='?'+urlencode({'code':invite}) if re.fullmatch('[A-Za-z0-9_-]{1,128}',invite) else ''
return item['url'].rstrip('/')+'/#/register'+query
def catalog(path):
return {e['code']:e['hostname'] for e in entries(path)[1]}
if __name__=='__main__':
try:
state=snapshot(sys.argv[1]); version=state['manifest']['version']
if version!=int(os.environ['DOMAINHUB_EXPECT_VERSION']): raise ValueError('wrong_version')
print(json.dumps({'version':version,'consumer':'fuc-navigation'}))
except Exception: sys.exit(1)
@@ -15,6 +15,8 @@ from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import HTTPRedirectHandler, Request, build_opener
from zoneinfo import ZoneInfo
from urllib.parse import urlsplit, parse_qs
import fuc_navigation_domains as domains
SHANGHAI = ZoneInfo("Asia/Shanghai")
ORIGINS = {
@@ -56,7 +58,7 @@ def initialize(db, now):
def count_round(db, catalog, origin, values, now):
if origin not in ORIGINS or not isinstance(values, dict) or set(values) != set(catalog):
if origin not in ORIGINS or not isinstance(values, dict) or not values or not set(values).issubset(set(catalog)):
raise ValueError("invalid sample")
if any(value not in OUTCOMES for value in values.values()):
raise ValueError("invalid outcome")
@@ -170,6 +172,31 @@ def serve(path, catalog, port):
class Handler(BaseHTTPRequestHandler):
timeout = 4
def do_GET(self):
parsed=urlsplit(self.path)
if parsed.path not in {'/_nav-routes','/_nav-go'}:
self.send_error(404); return
try:
state_path=os.environ['DOMAINHUB_PUBLIC_STATE']
if parsed.path=='/_nav-routes':
version, values=domains.entries(state_path)
public_fields={'code','url','hostname','display_name','role','priority','activated_at','eligible','reason','access','selectable','probe_enabled'}
body=json.dumps({'version':version,'entries':[{k:v for k,v in entry.items() if k in public_fields} for entry in values]},ensure_ascii=False).encode()
self.send_response(200); self.send_header('Content-Type','application/json; charset=utf-8')
else:
args=parse_qs(parsed.query,keep_blank_values=True)
if any(len(v)!=1 for v in args.values()) or not set(args).issubset({'route','code'}): raise ValueError('invalid parameters')
target=domains.destination(state_path,args.get('route',[''])[0],args.get('code',[''])[0])
if not target: raise ValueError('unavailable')
body=b''; self.send_response(302); self.send_header('Location',target)
except (ValueError,KeyError,OSError):
body='该入口暂不可用,请返回选择其他入口。'.encode()
self.send_response(410); self.send_header('Content-Type','text/plain; charset=utf-8')
self.send_header('Cache-Control','no-store, private')
self.send_header('X-Robots-Tag','noindex, nofollow')
self.send_header('Referrer-Policy','no-referrer')
self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
def do_POST(self):
if self.path != REPORT_ROUTE:
self.send_error(404)
@@ -181,7 +208,7 @@ def serve(path, catalog, port):
raise ValueError("invalid request")
values = json.loads(self.rfile.read(length))
with closing(connect(path)) as db:
count_round(db, catalog, origin, values, datetime.now(SHANGHAI))
count_round(db, domains.catalog(os.environ['DOMAINHUB_PUBLIC_STATE']) if os.environ.get('DOMAINHUB_PUBLIC_STATE') else catalog, origin, values, datetime.now(SHANGHAI))
except (ValueError, OSError, RecursionError):
self.send_error(400)
return
@@ -208,6 +235,9 @@ def main():
args = parser.parse_args()
catalog = {item["domainhub"]: item["domain"] for item in json.loads(args.catalog.read_text())["domains"]
if item["role"] in {"primary", "direct"}}
if os.environ.get('DOMAINHUB_PUBLIC_STATE'):
try: catalog=domains.catalog(os.environ['DOMAINHUB_PUBLIC_STATE'])
except (ValueError,OSError): pass # Historical reporting stays available during a hub outage.
now = datetime.now(SHANGHAI)
with closing(connect(args.database)) as db:
initialize(db, now)
+3 -2
View File
@@ -62,7 +62,7 @@ function renderNavigation(project, records, source) {
return [
' <label class="entry" data-role="' + role + '">',
' <input type="radio" name="route" value="' + escapeHtml(origin) + '"' + code + (recommended ? ' checked' : '') + '>',
' <span class="entry-info"><strong>' + escapeHtml(name) + '</strong><small>' + escapeHtml(label) + '</small></span>',
' <span class="entry-info"><strong>' + escapeHtml(name) + '</strong><small>' + escapeHtml(label.replace('域名', '地址')) + '</small></span>',
' <span class="latency">—</span>',
' </label>',
].join('\n');
@@ -81,7 +81,7 @@ function renderNavigation(project, records, source) {
const withLogo = replaceOnce(withDefault, /(id="brand-icon" rel="icon" href=")\.\/native\/images\/brand\/fuc-mark\.svg/g,
(_, start) => start + './logo.svg');
const withFallback = replaceOnce(withLogo, /(id="enter" class="enter" href=")\/#\/register"/g,
(_, start) => start + escapeHtml(recommended.origin) + '#/register"');
(_, start) => start + '/_nav-go?route=' + encodeURIComponent(recommended.domainhub) + '"');
return {
preview: withDefault,
standalone: withFallback.replace('<!doctype html>', '<!doctype html>\n<!-- 从 theme/Fuc/assets/connect.html 和项目域名清单生成。 -->'),
@@ -105,6 +105,7 @@ try {
['public/brand/fuc-navigation/index.html', Buffer.from(standalone)],
['public/brand/fuc-navigation/logo.svg', read('theme/Fuc/assets/native/images/brand/fuc-mark.svg')],
['public/brand/fuc-navigation/clipboard.mjs', read('theme/Fuc/assets/clipboard.mjs')],
['public/brand/fuc-navigation/navigation-domainhub.js', read('theme/Fuc/assets/navigation-domainhub.js')],
];
for (const [path, content] of files) {
if (action === 'build') writeFileSync(new URL('../../' + path, import.meta.url), content);
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Signed public-domain consumer. Run only on the owning project's server.
Canonical source: ATOM integrations/domainhub/public_client.py; copies are versioned.
"""
import argparse
import fcntl
import hashlib
import hmac
import json
import os
import re
import subprocess
import tempfile
import time
import uuid
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
from urllib.error import HTTPError
MAX_AGE = 86400
TERMINAL = {'sent', 'failed', 'uncertain', 'cancelled', 'rejected'}
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_a, **_k): return None
def read(path, default=None):
try: return json.loads(Path(path).read_text())
except (OSError, ValueError): return default
def atomic(path, data):
path=Path(path); path.parent.mkdir(parents=True, exist_ok=True)
fd,name=tempfile.mkstemp(prefix='.'+path.name, dir=path.parent)
try:
with os.fdopen(fd,'w') as out:
os.fchmod(out.fileno(),0o640)
json.dump(data,out,ensure_ascii=False,separators=(',',':'))
out.flush(); os.fsync(out.fileno())
os.replace(name,path)
directory=os.open(path.parent,os.O_RDONLY)
try: os.fsync(directory)
finally: os.close(directory)
finally:
if os.path.exists(name): os.unlink(name)
def request(url, key, data=None, extra=None):
headers={'Authorization':'Bearer '+key,'Accept':'application/json',**(extra or {})}
if data is not None: headers['Content-Type']='application/json'
req=Request(url,data=json.dumps(data,ensure_ascii=False,separators=(',',':')).encode() if data is not None else None,headers=headers)
with build_opener(NoRedirect()).open(req,timeout=12) as response:
body=response.read(1048577)
if len(body)>1048576: raise ValueError('response_too_large')
return response.headers,body
def signed(config, path, transport=request, now=None):
headers,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/'+path,config['key'])
stamp=headers.get('X-DomainHub-Timestamp',''); signature=headers.get('X-DomainHub-Signature','')
now=time.time() if now is None else now
if not stamp.isdigit() or abs(now-int(stamp))>120: raise ValueError('invalid_timestamp')
expected=hmac.new(config['key'].encode(),stamp.encode()+b'.'+body,hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected,signature): raise ValueError('invalid_signature')
data=json.loads(body)
if any(data.get(k)!=config[k] for k in ['project','environment','instance']): raise ValueError('wrong_scope')
if type(data.get('version')) is not int or data['version']<1: raise ValueError('invalid_version')
return data,body,headers
def validate_manifest(manifest, config):
if manifest.get('schema')!='domainhub.public.v1' or not isinstance(manifest.get('providers'),dict): raise ValueError('invalid_schema')
if set(manifest['providers'])!=set(config['providers']): raise ValueError('wrong_providers')
for provider in manifest['providers'].values():
entries=provider.get('entries')
if not isinstance(entries,list): raise ValueError('invalid_entries')
codes=set()
for entry in entries:
u=urlsplit(entry.get('url',''))
if u.scheme!='https' or not u.hostname or u.username or u.password or u.query or u.fragment or u.port not in (None,443) or any(c.isspace() for c in entry['url']): raise ValueError('invalid_public_url')
if entry.get('role') not in {'primary','navigation','direct_access'} or type(entry.get('eligible')) is not bool or entry.get('code') in codes: raise ValueError('invalid_entry')
codes.add(entry['code'])
if entry['eligible'] and (entry.get('access')!='available' or entry.get('reason') is not None): raise ValueError('invalid_eligibility')
selected=provider.get('selected')
if selected is not None and (selected not in entries or not selected['eligible']): raise ValueError('invalid_selection')
def current(state, now=None):
now=time.time() if now is None else now
return isinstance(state,dict) and 0<=now-state.get('checked_at',0)<=MAX_AGE
def available(state, provider, now=None):
if not current(state,now): return None
selected=state['manifest']['providers'].get(provider,{}).get('selected')
if not selected or not selected.get('eligible') or selected.get('access')!='available': return None
until=selected.get('valid_until')
if until:
from datetime import datetime, timezone
stamp=datetime.fromisoformat(until).replace(tzinfo=timezone.utc).timestamp()
if stamp <= (time.time() if now is None else now): return None
return selected
def runtime_check(config, version):
result=subprocess.run(config['validate_command'],env={**os.environ,'DOMAINHUB_EXPECT_VERSION':str(version)},capture_output=True,timeout=20)
if result.returncode: raise ValueError('runtime_verification_failed')
return json.loads(result.stdout or b'{}')
def sync(config, force=False, transport=request, verify=runtime_check, now=None):
now=int(time.time() if now is None else now)
path=Path(config['state_path']); state=read(path,{})
watermark=read(str(path)+'.watermark',{'version':0,'digest':''})
meta,_,_=signed(config,'version',transport,now)
if meta.get('schema')!='domainhub.public-version.v1' or not re.fullmatch('[a-f0-9]{64}',meta.get('digest','')): raise ValueError('invalid_version_response')
if meta['version']<watermark['version'] or (meta['version']==watermark['version'] and watermark['digest']!=meta['digest']): raise ValueError('rollback_or_conflict')
changed=state.get('digest')!=meta['digest'] or state.get('manifest',{}).get('version')!=meta['version']
if changed or force:
manifest,body,headers=signed(config,'snapshot',transport,now)
digest=hashlib.sha256(body).hexdigest()
if manifest['version']<meta['version'] or manifest['version']<watermark['version']: raise ValueError('stale_snapshot')
if manifest['version']==meta['version'] and digest!=meta['digest']: raise ValueError('snapshot_digest_mismatch')
validate_manifest(manifest,config)
if manifest['version']==watermark['version'] and digest!=watermark['digest']: raise ValueError('same_version_conflict')
state={'manifest':manifest,'digest':digest,'delivery':int(headers['X-DomainHub-Delivery']),'checked_at':now}
else:
validate_manifest(state['manifest'],config)
state={**state,'checked_at':now,'delivery':meta['delivery']}
atomic(str(path)+'.watermark',{'version':state['manifest']['version'],'digest':state['digest']})
atomic(path,state)
# ACK only after the consuming application's resolver reads the active file.
if config.get('catalog_path'):
provider=state['manifest']['providers'][config['catalog_provider']]
records=[]
candidates=sorted([e for e in provider['entries'] if e['eligible'] and e['role']!='navigation'], key=lambda e:(0 if e['role']=='direct_access' else 1,-e['priority'], -__import__('datetime').datetime.fromisoformat(e['activated_at']).timestamp(),e['code']))
preferred=candidates[0]['code'] if candidates else None
for e in provider['entries']:
item={'domain':e['hostname'],'role':'direct' if e['role']=='direct_access' else e['role'],'domainhub':e['code'],'eligible':e['eligible'],'recommended':e['code']==preferred}
if e['access']!='available': item['access']=e['access']
records.append(item)
atomic(config['catalog_path'],{'source':'domainhub.public.v1','version':state['manifest']['version'],'domains':records})
context=verify(config,state['manifest']['version'])
atomic(str(path)+'.runtime',context)
_,body=transport(config['hub_url'].rstrip('/')+'/api/v1/domainhub/public/deliveries/'+str(state['delivery'])+'/ack',config['key'],{'version':state['manifest']['version'],'digest':state['digest'],'status':'applied'})
if json.loads(body).get('status')!='applied': raise ValueError('invalid_ack')
return {'version':state['manifest']['version'],'changed':changed,'status':'applied'}
def incidents(config, state, journal, now):
active=journal.setdefault('active',{}); outbox=journal.setdefault('outbox',[])
context=read(config['state_path']+'.runtime',{})
for code in config['providers']:
selection=available(state,code,now)
if selection is None and code not in active:
incident=str(uuid.uuid4()); active[code]=incident
provider=(state or {}).get('manifest',{}).get('providers',{}).get(code,{})
reasons=';'.join(e['hostname']+': '+str(e.get('reason') or '不可用') for e in provider.get('entries',[]))
if not current(state,now): reasons='快照缺失或超过24小时未成功同步。'+reasons
text=f"【{config['label']} - {code}无可用广告域名】\n该服务商已暂停自动引流。\n原因:{reasons}\n版本:{(state or {}).get('manifest',{}).get('version','无')}\n投放状态:{json.dumps(context,ensure_ascii=False)}\n请补充可用入口或核实后明确恢复域名。"
outbox.append({'key':'domainhub.'+incident+'.critical','bot':'critical','text':text,'status':'pending','receipt':None,'retry_at':0,'attempts':0})
elif selection is not None and code in active:
incident=active.pop(code)
outbox.append({'key':'domainhub.'+incident+'.recovery','bot':'notification','text':f"【{config['label']} - {code}广告域名恢复】\n当前选用:{selection['url']}\n版本:{state['manifest']['version']}\n仍遵守原投放开关和暂避风头模式。",'status':'pending','receipt':None,'retry_at':0,'attempts':0})
def alerts(config, now=None, transport=request):
if not config.get('alerts_enabled'): return
now=int(time.time() if now is None else now); path=config['state_path']+'.alerts'
journal=read(path,{'active':{},'outbox':[]})
incidents(config,read(config['state_path']),journal,now)
atomic(path,journal)
for message in [m for m in journal['outbox'] if m['status'] not in TERMINAL and m['retry_at']<=now][:5]:
message['attempts']+=1; delay=min(21600,900*(2**min(message['attempts']-1,5)))
try:
endpoint=config['telehub_url'].rstrip('/')+'/api/v1/messages'
if message['receipt']: _,body=transport(endpoint+'/'+message['receipt'],config['telehub_key'])
else: _,body=transport(endpoint,config['telehub_key'],{'bot':message['bot'],'target':'base','text':message['text']},{'Idempotency-Key':message['key']})
receipt=json.loads(body)['data']
if (not re.fullmatch('[a-f0-9-]{36}',receipt.get('id','')) or receipt.get('status') not in TERMINAL|{'queued','sending'} or receipt.get('bot_code')!=message['bot'] or receipt.get('target_code')!='base' or (message['receipt'] and message['receipt']!=receipt['id'])): raise ValueError('invalid_receipt')
message.update(receipt=receipt['id'],status=receipt['status'],error=None)
except HTTPError as exc:
message['error']='http_'+str(exc.code)
if exc.code==429: delay=max(delay,int(exc.headers.get('Retry-After','0')) if exc.headers.get('Retry-After','0').isdigit() else 0)
elif 400<=exc.code<500: message['status']='rejected'
except (OSError,ValueError,KeyError,TimeoutError): message['error']='transport_or_receipt'
message['retry_at']=now+delay; atomic(path,journal)
def main():
parser=argparse.ArgumentParser();parser.add_argument('--config',required=True);parser.add_argument('--full',action='store_true');args=parser.parse_args()
config=read(args.config)
if not config or config.get('environment')!='production' or not re.fullmatch('dhc_[a-f0-9]{64}',config.get('key','')): raise SystemExit('invalid_private_configuration')
if urlsplit(config['hub_url']).scheme!='https': raise SystemExit('invalid_hub_url')
path=Path(config['state_path']); path.parent.mkdir(parents=True,exist_ok=True)
with open(str(path)+'.lock','a') as lock:
try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError: return
try: print(json.dumps(sync(config,args.full)))
except Exception as exc: print(json.dumps({'status':'sync_failed','error':type(exc).__name__}))
alerts(config)
if __name__=='__main__': main()
@@ -0,0 +1,18 @@
[Unit]
Description=FUC navigation daily full public domain reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=fuc-nav-stats
Group=fuc-nav-stats
UMask=0027
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/public_client.py --config /etc/fuc-navigation-domainhub/config.json --full
TimeoutStartSec=240
NoNewPrivileges=true
ProtectSystem=strict
StateDirectory=fuc-navigation-domainhub
StateDirectoryMode=0700
ReadWritePaths=/var/lib/fuc-navigation-domainhub
ProtectHome=true
PrivateTmp=true
@@ -0,0 +1,7 @@
[Unit]
Description=FUC navigation daily complete domain snapshot at 08:10 Shanghai
[Timer]
OnCalendar=*-*-* 08:10:00 Asia/Shanghai
Persistent=true
[Install]
WantedBy=timers.target
@@ -0,0 +1,18 @@
[Unit]
Description=FUC navigation signed public domain reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=fuc-nav-stats
Group=fuc-nav-stats
UMask=0027
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/public_client.py --config /etc/fuc-navigation-domainhub/config.json
TimeoutStartSec=240
NoNewPrivileges=true
ProtectSystem=strict
StateDirectory=fuc-navigation-domainhub
StateDirectoryMode=0700
ReadWritePaths=/var/lib/fuc-navigation-domainhub
ProtectHome=true
PrivateTmp=true
@@ -0,0 +1,8 @@
[Unit]
Description=FUC navigation public domain changes every four hours
[Timer]
OnBootSec=90
OnUnitActiveSec=4h
Persistent=true
[Install]
WantedBy=timers.target
@@ -0,0 +1,66 @@
import json, tempfile, time, unittest, sqlite3
from pathlib import Path
import fuc_navigation_domains as d
import fuc_navigation_stats as stats
class NavigationTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.path=Path(self.tmp.name)/'state.json'
def entry(code,eligible,access):return dict(code=code,url='https://'+code+'.example.com/',hostname=code+'.example.com',role='direct_access',eligible=eligible,access=access,reason=None if eligible else access)
self.entries=[entry('good',True,'available'),entry('bad',False,'blocked')]
self.state={'digest':'a'*64,'checked_at':int(time.time()),'manifest':{'schema':'domainhub.public.v1','project':'fuc','environment':'production','instance':'navigation','version':1,'providers':{'fuc':{'entries':self.entries,'selected':self.entries[0]}}}}
self.save()
def save(self):
self.path.write_text(json.dumps(self.state))
Path(str(self.path)+'.watermark').write_text(json.dumps({'version':1,'digest':'a'*64}))
def test_redirect_rechecks_current_status_and_retains_only_valid_invitation(self):
self.assertEqual('https://good.example.com/#/register?code=abc_1',d.destination(self.path,'good','abc_1'))
self.assertEqual('https://bad.example.com/#/register',d.destination(self.path,'bad'))
self.assertIsNone(d.destination(self.path,'https://evil.example.com'))
self.assertEqual('https://good.example.com/#/register',d.destination(self.path,'good','https://evil'))
self.entries[0].update(eligible=False,access='blocked',reason='blocked');self.state['manifest']['providers']['fuc']['selected']=None;self.save()
self.assertEqual('https://good.example.com/#/register',d.destination(self.path,'good'))
values=d.entries(self.path)[1]
self.assertTrue(all(e['selectable'] for e in values))
self.assertTrue(all(not e['probe_enabled'] for e in values))
from public_client import available
self.assertIsNone(available(self.state,'fuc'))
def test_access_warnings_allow_manual_navigation_without_probes(self):
from public_client import available
for access in ['requires_proxy','suspected_blocked','blocked','unknown']:
self.entries[1].update(access=access,reason=access)
self.save()
entry=d.entries(self.path)[1][1]
self.assertTrue(entry['selectable'])
self.assertFalse(entry['probe_enabled'])
self.assertFalse(entry['eligible'])
self.assertEqual('https://bad.example.com/#/register',d.destination(self.path,'bad'))
self.assertEqual('https://good.example.com/',available(self.state,'fuc')['url'])
self.assertNotIn('selectable',self.state['manifest']['providers']['fuc']['entries'][1])
def test_registration_revocation_still_prevents_navigation(self):
for reason in ['disabled','registration_changed','not_active_yet','future_policy']:
self.entries[1].update(reason=reason)
self.save()
self.assertIsNone(d.destination(self.path,'bad'))
self.assertFalse(d.entries(self.path)[1][1]['selectable'])
def test_expired_reachability_evidence_is_not_probed(self):
self.entries[0]['valid_until']='2020-01-01 00:00:00'
self.save()
entry=d.entries(self.path)[1][0]
self.assertTrue(entry['selectable'])
self.assertFalse(entry['probe_enabled'])
self.assertEqual('evidence_expired',entry['reason'])
def test_expired_or_wrong_scope_snapshot_is_not_used(self):
self.state['checked_at']-=86401;self.save()
with self.assertRaises(ValueError):d.entries(self.path)
self.state['checked_at']=int(time.time());self.state['manifest']['project']='other';self.save()
with self.assertRaises(ValueError):d.entries(self.path)
def test_stats_accept_subset_without_mutating_domain_access(self):
db=sqlite3.connect(':memory:');now=stats.datetime.now(stats.SHANGHAI);stats.initialize(db,now)
stats.count_round(db,d.catalog(self.path),'https://fu-nav3.com',{'good':'success'},now)
self.assertEqual(1,db.execute('select success from totals').fetchone()[0])
self.assertEqual('https://bad.example.com/#/register',d.destination(self.path,'bad'))
with self.assertRaises(ValueError):stats.count_round(db,d.catalog(self.path),'https://fu-nav3.com',{'unknown':'success'},now)
with self.assertRaises(ValueError):stats.count_round(db,d.catalog(self.path),'https://fu-nav3.com',{},now)
if __name__=='__main__':unittest.main()
@@ -0,0 +1,91 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {runInNewContext} from 'node:vm';
import test from 'node:test';
// Small DOM adapter: execute the shipped script unchanged, without network access.
async function fixture() {
const elements = [];
class Element {
constructor(tag) { this.tag = tag; this.children = []; this.dataset = {}; this.attrs = new Map(); this.listeners = {}; elements.push(this); }
append(...nodes) { this.children.push(...nodes); }
replaceChildren() { this.children = []; }
querySelectorAll(tag) { return this.children.flatMap(e => [e, ...e.querySelectorAll(tag)]).filter(e => e.tag === tag); }
setAttribute(k, v) { this.attrs.set(k, v); }
removeAttribute(k) { this.attrs.delete(k); }
toggleAttribute(k, on) { if (on) this.attrs.set(k, ''); else this.attrs.delete(k); }
addEventListener(name, fn) { this.listeners[name] = fn; }
set checked(on) { if (on) for (const e of elements) if (e.tag === 'input' && e.name === this.name) e._checked = false; this._checked = on; }
get checked() { return !!this._checked; }
}
const routes = new Element('fieldset'), panel = new Element('section'), status = new Element('span'), enter = new Element('a'), recheck = new Element('button');
const selectors = {'.routes': routes, '.entries': panel, '#route-status': status, '#enter': enter, '.recheck': recheck};
const record = (code, access) => ({code, hostname: code + '.example.com', url: 'https://' + code + '.example.com/', role: 'direct_access', priority: 0, activated_at: '2026-01-01', selectable: true, probe_enabled: access === 'available', eligible: access === 'available', access, reason: access === 'available' ? null : access});
const state = {records: [record('slow', 'available'), record('fast', 'available'), record('blocked', 'blocked'), record('suspected', 'suspected_blocked'), record('proxy', 'requires_proxy')], pending: [], reports: [], now: 0};
const flush = () => new Promise(resolve => setImmediate(resolve));
runInNewContext(readFileSync(new URL('../../theme/Fuc/assets/navigation-domainhub.js', import.meta.url), 'utf8'), {
document: {querySelector: key => selectors[key], createElement: tag => new Element(tag), hidden: false},
location: {hostname: 'navigation.example.com', search: '?code=invite_1', origin: 'https://navigation.example.com'},
URL, URLSearchParams, AbortSignal, Date, performance: {now: () => state.now},
setInterval: fn => { state.refresh = fn; },
fetch: async (url, options = {}) => {
const value = new URL(url, 'https://navigation.example.com');
if (value.pathname === '/_nav-routes') return {ok: true, json: async () => ({entries: structuredClone(state.records)})};
if (value.pathname === '/_nav-stats') { state.reports.push(JSON.parse(options.body)); return {ok: true}; }
return new Promise((resolve, reject) => state.pending.push({host: value.hostname, resolve, reject}));
},
});
await flush();
const row = code => routes.children.find(e => e.children[0].dataset.domainhubCode === code);
async function complete(code, now, ok = true) {
const index = state.pending.findIndex(e => e.host === code + '.example.com'); assert.notEqual(index, -1);
const request = state.pending.splice(index, 1)[0]; state.now = now;
if (ok) request.resolve({ok: true, json: async () => ({data: {app_name: 'FUC'}})});
else request.reject(Error('unreachable'));
await flush();
}
return {state, row, routes, recheck, enter, complete, flush};
}
test('manual warning routes stay selectable without probes; fastest highlight survives selection and refresh', async () => {
const f = await fixture();
assert.deepEqual(f.state.pending.map(e => e.host).sort(), ['fast.example.com', 'slow.example.com']);
for (const code of ['blocked', 'suspected', 'proxy']) {
assert.equal(f.row(code).children[0].disabled, false);
assert.equal(f.row(code).children[2].textContent, '不测速');
}
await f.complete('fast', 100); await f.complete('slow', 300);
assert.equal(f.row('fast').children[2].attrs.has('data-fastest'), true);
assert.equal(f.row('slow').children[2].attrs.has('data-fastest'), false);
f.row('blocked').children[0].checked = true; f.routes.listeners.change();
assert.equal(f.enter.href, '/_nav-go?route=blocked&code=invite_1');
f.state.refresh(); await f.flush();
assert.equal(f.row('blocked').children[0].checked, true);
assert.equal(f.row('fast').children[2].textContent, '100 ms');
assert.equal(f.row('fast').children[2].attrs.has('data-fastest'), true);
assert.deepEqual(f.state.reports[0], {slow: 'success', fast: 'success'});
f.recheck.listeners.click(); await f.flush();
assert.equal(f.row('fast').children[2].attrs.has('data-fastest'), false);
await f.complete('slow', 450); await f.complete('fast', 500);
assert.equal(f.row('slow').children[2].attrs.has('data-fastest'), true);
assert.equal(f.row('blocked').children[0].checked, true);
});
test('policy and URL changes clear old highlights; failures do not gain fastest status', async () => {
const f = await fixture(); await f.complete('fast', 100); await f.complete('slow', 300);
Object.assign(f.state.records.find(e => e.code === 'fast'), {eligible: false, probe_enabled: false, access: 'blocked', reason: 'blocked'});
f.state.refresh(); await f.flush();
assert.equal(f.row('fast').children[0].disabled, false);
assert.equal(f.row('fast').children[2].textContent, '不测速');
assert.equal(f.row('fast').children[2].attrs.has('data-fastest'), false);
assert.equal(f.row('slow').children[2].attrs.has('data-fastest'), true);
Object.assign(f.state.records.find(e => e.code === 'fast'), {selectable: false, reason: 'disabled'});
f.state.refresh(); await f.flush();
assert.equal(f.row('fast').children[0].disabled, true);
Object.assign(f.state.records.find(e => e.code === 'slow'), {url: 'https://new.example.com/', hostname: 'new.example.com'});
f.state.refresh(); await f.flush();
assert.equal(f.row('slow').children[2].textContent, '—');
assert.equal(f.row('slow').children[2].attrs.has('data-fastest'), false);
f.recheck.listeners.click(); await f.flush(); await f.complete('new', 400, false);
assert.equal(f.routes.children.some(e => e.children[2].attrs.has('data-fastest')), false);
});
+26 -118
View File
@@ -55,10 +55,20 @@
font-size: 15px;
}
.email-notice-icon {
width: 19px;
height: 19px;
margin-top: 2px;
color: var(--accent);
display: inline-grid;
place-items: center;
width: 1.45em;
height: 1.45em;
margin-top: 1px;
border-radius: .45em;
color: #ff92ad;
background: linear-gradient(145deg, #ff779c39, transparent 150%);
box-shadow: 0 0 .55em #ff779c39, inset 0 0 0 1px #ff779c39;
}
.email-notice-icon svg {
width: 1.12em;
height: 1.12em;
filter: drop-shadow(0 0 .2em #ff779c39);
}
.email-notice p { margin: 0; }
.email-notice .email-detail { margin-top: 4px; color: var(--muted); font-size: 14px; line-height: 1.65; text-wrap: pretty; }
@@ -160,10 +170,11 @@
<main class="wrap">
<h1>福云地址导航</h1>
<aside class="email-notice" aria-label="备用网址获取方式">
<svg class="email-notice-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="2.5" y="5" width="19" height="14" rx="2"/>
<path d="m3.5 6.5 8.5 7 8.5-7"/>
</svg>
<span class="email-notice-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 5v9"/><circle cx="12" cy="18.5" r="1" fill="currentColor" stroke="none"/>
</svg>
</span>
<div>
<p>务必,请收藏我们的邮箱
<span class="copy-control">
@@ -177,6 +188,7 @@
</span>。
</p>
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
<p class="email-detail">如果忘记收藏邮箱,也可以找注册福云时发送验证码的邮箱,同样会自动回复最新地址。</p>
</div>
</aside>
<section class="entries" aria-labelledby="entry-title">
@@ -185,27 +197,27 @@
<!-- project-domains:start -->
<label class="entry" data-role="primary">
<input type="radio" name="route" value="https://xn--9kqy16h.com/" data-domainhub-code="fuc.main-cn">
<span class="entry-info"><strong>福云.com</strong><small>永久主域名(需翻墙)</small></span>
<span class="entry-info"><strong>福云.com</strong><small>永久主地址(需翻墙)</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="primary">
<input type="radio" name="route" value="https://fuuu.cloud/" data-domainhub-code="fuc.main-en">
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主域名(需翻墙)</small></span>
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主地址(需翻墙)</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://fu99.cloud/" data-domainhub-code="fuc.direct-current" checked>
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙域名</small></span>
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙地址</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://fuuu.online/" data-domainhub-code="fuc.fuuu-online">
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙域名</small></span>
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙地址</small></span>
<span class="latency">—</span>
</label>
<label class="entry" data-role="direct">
<input type="radio" name="route" value="https://xn--123-9i9dj97q.com/" data-domainhub-code="fuc.direct-cn-backup">
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙域名(疑似被墙)</small></span>
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙地址(疑似被墙)</small></span>
<span class="latency">—</span>
</label>
<!-- project-domains:end -->
@@ -219,111 +231,7 @@
</div>
</section>
</main>
<script>
const panel = document.querySelector('.entries');
const routes = document.querySelector('.routes');
const status = document.querySelector('#route-status');
const enter = document.querySelector('#enter');
const recheck = document.querySelector('.recheck');
const invite = new URLSearchParams(location.search).get('code');
const entries = [...routes.querySelectorAll('input[name="route"]')].map(input => {
const row = input.closest('label');
return { input, row, result: row.querySelector('.latency') };
});
const isLocal = location.hostname === 'xb.loc';
const probePath = '/api/v1/guest/comm/config';
const probeTimeoutMs = 3000;
let manualSelection = false;
let testStatus = '';
function selectRoute() {
const selected = routes.querySelector('input:checked');
const origin = isLocal ? location.origin : new URL(selected.value).origin;
const code = invite && /^[A-Za-z0-9_-]{1,64}$/.test(invite) ? '?code=' + encodeURIComponent(invite) : '';
enter.href = origin + '/#/register' + code;
const name = selected.closest('label').querySelector('strong').textContent;
status.textContent = ['已选择 ' + name, testStatus].filter(Boolean).join(' · ');
}
async function measure(entry, sample) {
const url = new URL(probePath, isLocal ? location.origin : entry.input.value);
url.searchParams.set('nav_probe', sample);
const controller = new AbortController();
const started = performance.now();
const timeout = setTimeout(() => controller.abort(), probeTimeoutMs);
try {
const response = await fetch(url, {
mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error',
referrerPolicy: 'no-referrer', signal: controller.signal,
});
if (!response.ok) throw new Error('Probe failed');
const { data } = await response.json();
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
const elapsed = performance.now() - started;
entry.outcome = 'success';
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
return { entry, elapsed };
} catch {
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
return null;
} finally {
clearTimeout(timeout);
}
}
async function testRoutes() {
if (recheck.disabled) return;
recheck.disabled = true;
panel.setAttribute('aria-busy', 'true');
testStatus = isLocal ? '本地测速中…' : '正在测速…';
selectRoute();
for (const { result } of entries) {
result.removeAttribute('data-fastest');
result.textContent = '测速中…';
}
try {
const round = Date.now().toString(36);
const results = await Promise.all(entries.map((entry, index) => measure(entry, round + '-' + index)));
const ranked = results.filter(Boolean).sort((a, b) => a.elapsed - b.elapsed);
const measured = new Set(ranked.map(({ entry }) => entry));
const ordered = [...ranked.map(({ entry }) => entry), ...entries.filter(entry => !measured.has(entry))];
const focused = document.activeElement;
for (const { row } of ordered) {
if (row.dataset.role !== 'primary') routes.append(row);
}
if (routes.contains(focused) && document.activeElement !== focused) focused.focus({ preventScroll: true });
const fastest = ranked[0];
if (fastest) {
fastest.entry.result.setAttribute('data-fastest', '');
if (!manualSelection) fastest.entry.input.checked = true;
}
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
if (!isLocal) {
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
fetch('/_nav-stats', {
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
}).catch(() => {});
}
} finally {
recheck.disabled = false;
panel.removeAttribute('aria-busy');
selectRoute();
}
}
routes.addEventListener('click', event => {
if (event.target.matches('input[name="route"]')) manualSelection = true;
});
routes.addEventListener('change', () => {
manualSelection = true;
selectRoute();
});
recheck.addEventListener('click', testRoutes);
selectRoute();
testRoutes();
</script>
<script src="./navigation-domainhub.js?v=manual-select-fastest-1"></script>
<script type="module">
import { copyText } from './clipboard.mjs';
+124
View File
@@ -0,0 +1,124 @@
// Public routes come from this navigation server's verified DomainHub snapshot.
// Manual navigation does not change advertising eligibility or access status.
(() => {
const routes = document.querySelector('.routes');
const panel = document.querySelector('.entries');
const status = document.querySelector('#route-status');
const enter = document.querySelector('#enter');
const recheck = document.querySelector('.recheck');
const invite = new URLSearchParams(location.search).get('code') || '';
const isLocal = location.hostname === 'xb.loc';
let entries = [], manual = false, busy = false;
const roles = {primary: '永久主地址', direct_access: '免翻墙地址'};
const reasons = {requires_proxy: '需翻墙', suspected_blocked: '疑似被墙', blocked: '已标记被墙', unknown: '待确认', disabled: '已停用', service_unhealthy: '暂不可用', service_unknown: '待确认', registration_changed: '待确认', evidence_expired: '待确认'};
const selected = () => entries.find(e => e.input.checked && !e.input.disabled);
const ranked = () => entries.filter(e => e.probe_enabled && e.outcome === 'success' && Number.isFinite(e.elapsed)).sort((a, b) => a.elapsed - b.elapsed);
function highlightFastest() {
const fastest = ranked()[0]?.elapsed;
for (const entry of entries) {
entry.result.toggleAttribute('data-fastest', fastest !== undefined && entry.probe_enabled && entry.outcome === 'success' && entry.elapsed === fastest);
}
}
function update() {
const entry = selected();
if (!entry) {
enter.removeAttribute('href'); enter.setAttribute('aria-disabled', 'true');
status.textContent = '暂未找到可用入口'; return;
}
const params = new URLSearchParams({route: entry.code});
if (/^[A-Za-z0-9_-]{1,128}$/.test(invite)) params.set('code', invite);
enter.href = isLocal ? '/#/register' + (params.has('code') ? '?code=' + encodeURIComponent(invite) : '') : '/_nav-go?' + params;
enter.removeAttribute('aria-disabled'); status.textContent = '已选择 ' + entry.hostname;
}
function render(records) {
const previous = selected()?.code;
const measurements = new Map(entries.map(e => [e.code, e]));
routes.replaceChildren(); entries = [];
records.sort((a, b) => (a.role === 'primary' ? 0 : 1) - (b.role === 'primary' ? 0 : 1) || Number(b.probe_enabled) - Number(a.probe_enabled) || b.priority - a.priority || b.activated_at.localeCompare(a.activated_at));
for (const e of records.filter(e => e.role !== 'navigation')) {
const row = document.createElement('label'); row.className = 'entry'; row.dataset.role = e.role === 'primary' ? 'primary' : 'direct';
const input = document.createElement('input'); input.type = 'radio'; input.name = 'route'; input.value = e.url; input.dataset.domainhubCode = e.code; input.disabled = e.selectable !== true;
const info = document.createElement('span'); info.className = 'entry-info';
const strong = document.createElement('strong'); strong.textContent = e.display_name || e.hostname;
const small = document.createElement('small');
small.textContent = (roles[e.role] || '入口') + (e.probe_enabled ? '' : '(' + (reasons[['blocked', 'suspected_blocked', 'requires_proxy'].includes(e.access) ? e.access : e.reason] || '待确认') + ')');
info.append(strong, small);
const result = document.createElement('span'); result.className = 'latency'; result.textContent = input.disabled ? '暂不可用' : e.probe_enabled ? '—' : '不测速';
const entry = {...e, row, input, result};
const old = measurements.get(e.code);
// A routine catalog refresh must retain results and the manual selection.
// A URL or policy change invalidates measurements for that entry.
if (e.probe_enabled && old?.probe_enabled && old.url === e.url && old.outcome) {
entry.elapsed = old.elapsed; entry.outcome = old.outcome; result.textContent = old.result.textContent;
}
row.append(input, info, result); routes.append(row); entries.push(entry);
}
const available = entries.filter(e => e.selectable);
const ordered = available.filter(e => e.probe_enabled).sort((a, b) => (a.role === 'direct_access' ? 0 : 1) - (b.role === 'direct_access' ? 0 : 1) || b.priority - a.priority || b.activated_at.localeCompare(a.activated_at));
const chosen = (manual && available.find(e => e.code === previous)) || ranked()[0] || ordered[0] || available[0];
if (chosen) chosen.input.checked = true;
highlightFastest(); update();
}
async function refresh() {
if (isLocal) return;
const response = await fetch('/_nav-routes', {cache: 'no-store', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(5000)});
if (!response.ok) throw Error('unavailable');
const data = await response.json();
if (!Array.isArray(data.entries)) throw Error('invalid');
render(data.entries);
}
async function measure(entry) {
if (!entry.probe_enabled || !entry.selectable) return;
const started = performance.now(); entry.result.textContent = '测速中…';
try {
const url = new URL('/api/v1/guest/comm/config', isLocal ? location.origin : entry.url);
url.searchParams.set('nav_probe', Date.now());
const response = await fetch(url, {mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(3000)});
if (!response.ok || typeof (await response.json()).data?.app_name !== 'string') throw Error('failure');
entry.elapsed = Math.round(performance.now() - started); entry.outcome = 'success'; entry.result.textContent = entry.elapsed + ' ms';
} catch (error) {
entry.elapsed = null; entry.outcome = error.name === 'TimeoutError' ? 'timeout' : 'failure'; entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '未连通';
}
}
async function test() {
if (busy) return;
busy = true; recheck.disabled = true; panel.setAttribute('aria-busy', 'true');
try {
await refresh();
for (const entry of entries) {
delete entry.elapsed; delete entry.outcome; entry.result.removeAttribute('data-fastest');
}
await Promise.all(entries.map(measure));
const fastest = ranked()[0];
if (!manual && fastest) fastest.input.checked = true;
highlightFastest();
if (!isLocal) {
const results = Object.fromEntries(entries.filter(e => e.probe_enabled && e.outcome).map(e => [e.code, e.outcome]));
if (Object.keys(results).length) fetch('/_nav-stats', {method: 'POST', body: JSON.stringify(results), credentials: 'omit', keepalive: true, redirect: 'error', referrerPolicy: 'no-referrer'}).catch(() => {});
}
} catch { render([]); }
finally { busy = false; recheck.disabled = false; panel.removeAttribute('aria-busy'); update(); }
}
routes.addEventListener('change', () => { manual = true; update(); });
enter.addEventListener('click', event => { if (!selected()) event.preventDefault(); });
recheck.addEventListener('click', test);
if (isLocal) {
render([...routes.querySelectorAll('input')].map(input => {
const code = input.dataset.domainhubCode;
const access = code === 'fuc.direct-cn-backup' ? 'suspected_blocked' : ['fuc.main-cn', 'fuc.main-en'].includes(code) ? 'requires_proxy' : 'available';
return {code, url: input.value, hostname: input.closest('.entry').querySelector('strong').textContent, role: input.closest('.entry').dataset.role === 'primary' ? 'primary' : 'direct_access', selectable: true, probe_enabled: access === 'available', eligible: access === 'available', access, reason: access === 'available' ? null : access, priority: input.checked ? 1 : 0, activated_at: '2026-01-01'};
}));
} else {
for (const input of routes.querySelectorAll('input')) input.disabled = true;
enter.removeAttribute('href');
}
test();
setInterval(() => { if (!document.hidden && !busy) refresh().catch(() => render([])); }, 60000);
})();