Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
800a9f5fcf | ||
|
|
fa6e6e0509 | ||
|
|
e5d19abafe | ||
|
|
f8a5ab9bfc | ||
|
|
d202a217df | ||
|
|
84e6808432 | ||
|
|
425f6a3121 | ||
|
|
7b155b7092 | ||
|
|
be54f7b992 | ||
|
|
21ef7824f1 | ||
|
|
d4c3958c50 | ||
|
|
bcdbfcad5a | ||
|
|
e35b61b3db | ||
|
|
a5d3cf5cd7 |
No files matched your search
@@ -28,3 +28,5 @@
|
||||
- 接入所需邮箱验证码,按用户2026-10-20长期授权,先用已登记的对应邮箱自行登录并只读取本次验证邮件;凭据仍走GemDocs统一字段入口,不改账号安全设置、不读取无关邮件。只有资料缺失、认证失败或必须人工完成的验证才请求用户协助;账号切换及网站访问边界继续适用。
|
||||
|
||||
本文件提供维护入口,不扩大当前任务授权,也不启动无人值守自动维护。
|
||||
|
||||
FUC独立导航公共域名与禁选状态统一按[DomainHub接入](docs/maintenance/NAVIGATION_DOMAINHUB.md)维护;不涉及XB核心。
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"domains": [
|
||||
{ "domain": "福云.com", "role": "primary", "access": "requires_proxy", "domainhub": "fuc.main-cn" },
|
||||
{ "domain": "fuuu.cloud", "role": "primary", "access": "requires_proxy", "domainhub": "fuc.main-en" },
|
||||
{ "domain": "福云123.com", "role": "direct", "access": "suspected_blocked", "domainhub": "fuc.direct-cn-backup" },
|
||||
{ "domain": "fuuu.online", "role": "direct", "domainhub": "fuc.fuuu-online" },
|
||||
{ "domain": "fu99.cloud", "role": "direct", "domainhub": "fuc.direct-current", "recommended": true },
|
||||
{ "domain": "fu-nav3.com", "role": "navigation", "domainhub": "fuc.navigation" }
|
||||
]
|
||||
}
|
||||
@@ -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`。
|
||||
@@ -0,0 +1,28 @@
|
||||
# 项目域名清单与福云导航
|
||||
|
||||
项目面向用户的域名和用途维护在 [config/project-domains/](../../config/project-domains/)。每个项目使用独立的 JSON 文件,文件名为项目代号。DomainHub 维护地址发布与访问状态台账;DNS由原DNS系统维护;清单里的 `domainhub` 是对应记录代号,不包含凭据或私有入口。
|
||||
|
||||
- `role`:`primary` 永久主域名、`direct` 免翻墙域名、`navigation` 导航站域名。
|
||||
- `access`:按需填写 `requires_proxy`(需翻墙)或 `suspected_blocked`(疑似被墙)。未填写表示没有登记额外限制,不表示做过当地线路测试。
|
||||
- `recommended`:最多一个,只用于未标注限制的免翻墙域名。
|
||||
|
||||
```sh
|
||||
node scripts/project-domains/manage.mjs list
|
||||
node scripts/project-domains/manage.mjs list fuc
|
||||
node scripts/project-domains/manage.mjs build fuc
|
||||
node scripts/project-domains/manage.mjs check fuc
|
||||
```
|
||||
|
||||
[比利版福云导航](http://xb.loc/theme/Fuc/assets/connect.html)的设计源为 [connect.html](../../theme/Fuc/assets/connect.html)。调整设计或 [FUC 清单](../../config/project-domains/fuc.json)后重新生成,生成器同步本地预览的入口列表,并从同一设计源生成独立导航站的 HTML 和资源。测速前默认选中 fu99.cloud。两条永久主域名固定在最前,其余入口在每轮测速后按耗时从低到高排列,未测通的放在末尾。福云123.com 的「疑似被墙」是清单标注。导航站本身只登记为导航入口。
|
||||
|
||||
打开页面或点「重新检测」时,浏览器并行请求五个入口的 `/api/v1/guest/comm/config`,确认是 XB 访客响应后显示耗时。每次请求最多 3 秒,不带登录态和邀请码。成功时优先选中最快的入口,手动选择保留;全部失败保留当前选项。只有点击「立即进入」才跳转,邀请码随注册链接传递。本地预览的测速和注册均使用 xb.loc,用于验证交互和本地请求。
|
||||
|
||||
每轮测速结束后,正式导航和反代分别向同源 `POST /_nav-stats` 提交一次五条结果。统计只存按日期、导航来源和域名汇总的成功、超时、其他失败计数。统计量是提交成功的测速轮次,用户在测速结束前离开不计入。北京时间每天 08:00 统计过去 24 小时,并通过 TeleHub 的 `info` 发往 `base`。首期注明开始采集时间。日报正文和回执保存在独立 SQLite,同一天的重试沿用原幂等键。
|
||||
|
||||
采集和日报在 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)。
|
||||
@@ -1,48 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="dark">
|
||||
<!-- 从 theme/Fuc/assets/connect.html 和项目域名清单生成。 -->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>福云地址导航</title>
|
||||
<link rel="icon" href="./logo.svg" type="image/svg+xml">
|
||||
<link id="brand-icon" rel="icon" href="./logo.svg?v=2" type="image/svg+xml" sizes="any">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page: #f5f3fb;
|
||||
--panel: #fff;
|
||||
--ink: #211b39;
|
||||
--muted: #625a76;
|
||||
--line: #e7e1f2;
|
||||
--accent: #5941bf;
|
||||
--action: #6045ce;
|
||||
--tint: #f0ebff;
|
||||
--glow: #e4dcff;
|
||||
--shadow: rgb(49 31 102 / 9%);
|
||||
color-scheme: dark;
|
||||
--page: #171426;
|
||||
--page-wash: #241b3a;
|
||||
--panel: #201c34;
|
||||
--ink: #f6f1ff;
|
||||
--muted: #bbb2d0;
|
||||
--line: #38304d;
|
||||
--accent: #c6b7ff;
|
||||
--fastest: #b6ff40;
|
||||
--notice-warm-tone: #f4d36c;
|
||||
--action: #7256df;
|
||||
--tint: #332851;
|
||||
--shadow: rgb(0 0 0 / 20%);
|
||||
font: 16px/1.55 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--page: #171426;
|
||||
--panel: #201c34;
|
||||
--ink: #f6f1ff;
|
||||
--muted: #bbb2d0;
|
||||
--line: #38304d;
|
||||
--accent: #c6b7ff;
|
||||
--action: #7256df;
|
||||
--tint: #332851;
|
||||
--glow: #2d214a;
|
||||
--shadow: rgb(0 0 0 / 20%);
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
background: radial-gradient(ellipse at 16% 30%, var(--glow), transparent 50%), var(--page);
|
||||
background: linear-gradient(180deg, var(--page-wash), var(--page) 360px);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
@@ -50,43 +39,40 @@
|
||||
:is(a, button):focus-visible,
|
||||
.entry:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
|
||||
.wrap { width: min(1120px, calc(100% - 64px)); margin-inline: auto; }
|
||||
.wrap { width: min(740px, calc(100% - 48px)); margin-inline: auto; }
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding-block: 26px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.brand { display: flex; align-items: center; gap: 12px; font-size: 20px; font-weight: 750; }
|
||||
.brand img { width: 38px; height: 38px; object-fit: contain; }
|
||||
.theme {
|
||||
main { padding-block: clamp(32px, 6vw, 64px) 40px; }
|
||||
h1 { margin: 0 0 24px; font-size: clamp(32px, 5vw, 48px); line-height: 1.18; letter-spacing: -.04em; }
|
||||
.email-notice {
|
||||
display: grid;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
place-items: center;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--panel);
|
||||
background: color-mix(in srgb, var(--notice-warm-tone) 5%, var(--page));
|
||||
font-size: 15px;
|
||||
}
|
||||
.theme:hover { color: var(--accent); border-color: var(--accent); }
|
||||
.theme svg { width: 19px; height: 19px; }
|
||||
[data-theme="dark"] .theme .moon, [data-theme="light"] .theme .sun { display: none; }
|
||||
|
||||
main {
|
||||
display: grid;
|
||||
grid-template-columns: .86fr 1fr;
|
||||
align-items: center;
|
||||
gap: clamp(28px, 6vw, 80px);
|
||||
min-height: min(680px, calc(100svh - 100px));
|
||||
padding-block: 64px;
|
||||
.email-notice-icon {
|
||||
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;
|
||||
}
|
||||
|
||||
h1 { margin: 0 0 16px; font-size: clamp(38px, 6.5vw, 70px); line-height: 1.12; letter-spacing: -.045em; }
|
||||
.intro p { max-width: 23em; margin: 0; color: var(--muted); }
|
||||
.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; }
|
||||
.copy-control { position: relative; display: inline-block; }
|
||||
.copy-email {
|
||||
display: inline-flex;
|
||||
@@ -94,13 +80,12 @@
|
||||
gap: 5px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: var(--accent);
|
||||
background: none;
|
||||
font-weight: 650;
|
||||
text-decoration: underline dotted;
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.copy-email:hover { text-decoration-style: solid; }
|
||||
.copy-email:hover { text-decoration: underline; }
|
||||
.copy-feedback {
|
||||
position: absolute;
|
||||
inset-inline-end: 0;
|
||||
@@ -111,7 +96,6 @@
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
color: var(--accent);
|
||||
background: var(--panel);
|
||||
box-shadow: 0 4px 12px var(--shadow);
|
||||
font-size: 12px;
|
||||
@@ -120,157 +104,135 @@
|
||||
.copy-feedback:empty { opacity: 0; }
|
||||
|
||||
.entries {
|
||||
padding: clamp(16px, 3vw, 28px);
|
||||
padding: clamp(16px, 4vw, 28px);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 24px;
|
||||
border-radius: 18px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 22px 64px var(--shadow);
|
||||
box-shadow: 0 18px 48px var(--shadow);
|
||||
}
|
||||
|
||||
.entries h2 { margin: 0 0 16px; font-size: 18px; }
|
||||
.routes { display: grid; gap: 8px; margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 60px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: border-color .16s ease, background-color .16s ease;
|
||||
}
|
||||
|
||||
.entry:hover { background: color-mix(in srgb, var(--tint) 50%, var(--panel)); }
|
||||
.entry:has(input:checked) { background: var(--tint); border-color: var(--accent); }
|
||||
.entry input { grid-area: 1 / 3; width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
|
||||
.entry-info { grid-area: 1 / 1; display: flex; align-items: baseline; gap: 12px; }
|
||||
.entry .latency { grid-area: 1 / 2; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.entry .latency[data-fastest] { color: var(--fastest); font-weight: 700; }
|
||||
|
||||
.entry strong { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.entry small { color: var(--muted); font-size: 13px; }
|
||||
.entry:has(input:checked) small { color: var(--accent); }
|
||||
|
||||
.panel-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
margin-block: 12px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.entries h2 { margin: 0 0 14px; font-size: 16px; }
|
||||
.routes { display: grid; gap: 10px; margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
.recheck { border: 0; background: none; padding: 6px 0; color: var(--accent); white-space: nowrap; }
|
||||
.recheck:hover { text-decoration: underline; }
|
||||
.recheck:disabled { opacity: .55; cursor: wait; }
|
||||
.enter { display: grid; place-items: center; min-height: 46px; border-radius: 9px; font-size: 14px; }
|
||||
.enter { padding-inline: 12px; color: #fff; background: var(--action); font-weight: 700; }
|
||||
.enter:hover { filter: brightness(1.1); }
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: 20px minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 80px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
cursor: pointer;
|
||||
transition: border-color .16s ease, background-color .16s ease;
|
||||
@media (max-width: 520px) {
|
||||
.wrap { width: calc(100% - 32px); }
|
||||
h1 { margin-bottom: 18px; }
|
||||
.entry { gap: 10px; padding: 10px 12px; }
|
||||
.entry-info { flex-direction: column; gap: 1px; }
|
||||
}
|
||||
|
||||
.entry:has(input:checked), .entry:hover { background: var(--tint); border-color: var(--accent); }
|
||||
.entry input { width: 17px; height: 17px; margin: 0; accent-color: var(--accent); }
|
||||
|
||||
.entry strong, .entry small { display: block; }
|
||||
.entry strong { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.entry small { margin-top: 2px; color: var(--muted); font-size: 12px; }
|
||||
|
||||
.panel-footer { min-height: 40px; margin-block: 12px 10px; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.entry { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="wrap">
|
||||
<a class="brand" href="/"><img src="./logo.svg" alt="">福云</a>
|
||||
<button class="theme" type="button" aria-label="切换到浅色">
|
||||
<svg class="sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.4 1.4m11.2 11.2L19 19M5 19l1.4-1.4m11.2-11.2L19 5"/></svg>
|
||||
<svg class="moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M20.9 13.3A9 9 0 0 1 10.7 3.1a9 9 0 1 0 10.2 10.2Z"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
<main class="wrap">
|
||||
<section class="intro" aria-labelledby="page-title">
|
||||
<h1 id="page-title">福云地址导航</h1>
|
||||
<p>务必,请收藏我们的邮箱
|
||||
<span class="copy-control">
|
||||
<button class="copy-email" type="button" aria-label="复制邮箱地址 fu@gemcook.net">
|
||||
[email protected]
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
|
||||
<path d="M8 8h9l3 3v10H8V8Z M15 8V3H3v13h5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="copy-feedback" role="status"></span>
|
||||
</span>。导航地址被墙时,可发送任意邮件至我们的邮箱,会自动回复最新地址。
|
||||
</p>
|
||||
</section>
|
||||
<h1>福云地址导航</h1>
|
||||
<aside class="email-notice" aria-label="备用网址获取方式">
|
||||
<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">
|
||||
<button class="copy-email" type="button" aria-label="复制邮箱地址 [email protected]">
|
||||
[email protected]
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
|
||||
<path d="M8 8h9l3 3v10H8V8Z M15 8V3H3v13h5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="copy-feedback" role="status"></span>
|
||||
</span>。
|
||||
</p>
|
||||
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
|
||||
<p class="email-detail">如果忘记收藏邮箱,也可以找注册福云时发送验证码的邮箱,同样会自动回复最新地址。</p>
|
||||
</div>
|
||||
</aside>
|
||||
<section class="entries" aria-labelledby="entry-title">
|
||||
<h2 id="entry-title">访问入口</h2>
|
||||
<fieldset class="routes" aria-labelledby="entry-title">
|
||||
<label class="entry">
|
||||
<input type="radio" name="route" value="https://fu99.cloud/" data-domainhub-code="fuc.direct-current" checked>
|
||||
<span><strong>fu99.cloud</strong><small>免翻墙入口 · 推荐</small></span>
|
||||
</label>
|
||||
<label class="entry">
|
||||
<input type="radio" name="route" value="https://xn--123-9i9dj97q.com/" data-domainhub-code="fuc.direct-cn-backup">
|
||||
<span><strong>福云123.com</strong><small>备用入口</small></span>
|
||||
</label>
|
||||
<label class="entry">
|
||||
<!-- 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><strong>福云.com</strong><small>中文主域名</small></span>
|
||||
<span class="entry-info"><strong>福云.com</strong><small>永久主地址(需翻墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry">
|
||||
<label class="entry" data-role="primary">
|
||||
<input type="radio" name="route" value="https://fuuu.cloud/" data-domainhub-code="fuc.main-en">
|
||||
<span><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="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="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="latency">—</span>
|
||||
</label>
|
||||
<!-- project-domains:end -->
|
||||
</fieldset>
|
||||
<div class="panel-footer">
|
||||
<span id="route-status" role="status">已选择 fu99.cloud</span>
|
||||
<button class="recheck" type="button">重新检测</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<a id="enter" class="enter" href="https://fu99.cloud/#/register">立即进入 →</a>
|
||||
<button class="countdown" type="button">开始 8 秒跳转</button>
|
||||
<a id="enter" class="enter" href="/_nav-go?route=fuc.direct-current">立即进入 →</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const theme = document.querySelector('.theme');
|
||||
const routes = document.querySelector('.routes');
|
||||
const status = document.querySelector('#route-status');
|
||||
const enter = document.querySelector('#enter');
|
||||
const countdown = document.querySelector('.countdown');
|
||||
const invite = new URLSearchParams(location.search).get('code');
|
||||
const seconds = 8;
|
||||
let remaining = seconds;
|
||||
let timer;
|
||||
|
||||
function selectRoute() {
|
||||
const selected = routes.querySelector('input:checked');
|
||||
const 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;
|
||||
status.textContent = '已选择 ' + selected.closest('label').querySelector('strong').textContent;
|
||||
}
|
||||
|
||||
function pauseCountdown() {
|
||||
clearInterval(timer);
|
||||
timer = undefined;
|
||||
countdown.textContent = remaining === seconds ? '开始 8 秒跳转' : '继续跳转 ' + remaining + ' 秒';
|
||||
}
|
||||
|
||||
theme.addEventListener('click', () => {
|
||||
const dark = document.documentElement.dataset.theme === 'dark';
|
||||
document.documentElement.dataset.theme = dark ? 'light' : 'dark';
|
||||
theme.setAttribute('aria-label', dark ? '切换到深色' : '切换到浅色');
|
||||
});
|
||||
routes.addEventListener('change', () => {
|
||||
remaining = seconds;
|
||||
pauseCountdown();
|
||||
selectRoute();
|
||||
});
|
||||
countdown.addEventListener('click', () => {
|
||||
if (timer !== undefined) {
|
||||
pauseCountdown();
|
||||
return;
|
||||
}
|
||||
countdown.textContent = '暂停跳转 ' + remaining + ' 秒';
|
||||
timer = setInterval(() => {
|
||||
remaining -= 1;
|
||||
if (remaining === 0) {
|
||||
clearInterval(timer);
|
||||
timer = undefined;
|
||||
location.assign(enter.href);
|
||||
} else {
|
||||
countdown.textContent = '暂停跳转 ' + remaining + ' 秒';
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
selectRoute();
|
||||
</script>
|
||||
<script src="./navigation-domainhub.js?v=manual-select-fastest-1"></script>
|
||||
<script type="module">
|
||||
import { copyText } from './clipboard.mjs';
|
||||
|
||||
|
||||
+124
@@ -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)
|
||||
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Count browser probe outcomes and deliver the FUC navigation digest."""
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from datetime import date, datetime, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
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 = {
|
||||
"https://fu-nav3.com": "正式导航",
|
||||
"https://fu-nav3.tomtojapan.online": "反代导航",
|
||||
}
|
||||
OUTCOMES = ("success", "timeout", "failure")
|
||||
TERMINAL = {"sent", "failed", "uncertain", "cancelled", "rejected"}
|
||||
REPORT_ENDPOINT = "https://telehub.gemcook.net/api/v1/messages"
|
||||
REPORT_ROUTE = "/_nav-stats"
|
||||
|
||||
|
||||
def current_end(now):
|
||||
return (now - timedelta(hours=8)).date() + timedelta(days=1)
|
||||
|
||||
|
||||
def connect(path):
|
||||
db = sqlite3.connect(path, timeout=4)
|
||||
db.row_factory = sqlite3.Row
|
||||
return db
|
||||
|
||||
|
||||
def initialize(db, now):
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS totals (
|
||||
day TEXT NOT NULL, source TEXT NOT NULL, domain TEXT NOT NULL,
|
||||
success INTEGER NOT NULL, timeout INTEGER NOT NULL, failure INTEGER NOT NULL,
|
||||
PRIMARY KEY (day, source, domain)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
day TEXT PRIMARY KEY, text TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
receipt TEXT, retry_at INTEGER NOT NULL DEFAULT 0, error TEXT
|
||||
);
|
||||
""")
|
||||
with db:
|
||||
db.execute("INSERT OR IGNORE INTO metadata VALUES ('started', ?)", (now.isoformat(),))
|
||||
|
||||
|
||||
def count_round(db, catalog, origin, values, now):
|
||||
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")
|
||||
rows = [
|
||||
(str(current_end(now)), origin, domain, *(outcome == status for status in OUTCOMES))
|
||||
for domain, outcome in values.items()
|
||||
]
|
||||
with db:
|
||||
db.executemany("""
|
||||
INSERT INTO totals VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(day, source, domain) DO UPDATE SET
|
||||
success = success + excluded.success,
|
||||
timeout = timeout + excluded.timeout,
|
||||
failure = failure + excluded.failure
|
||||
""", rows)
|
||||
|
||||
|
||||
def format_report(db, catalog, day):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
first = day - timedelta(days=1)
|
||||
lines = ["【福云 - 导航测速日报】", f"{first} 08:00 至 {day} 08:00(北京时间)"]
|
||||
if day == current_end(started):
|
||||
lines.append(f"本期从 {started:%m-%d %H:%M} 开始采集")
|
||||
rows = db.execute("SELECT * FROM totals WHERE day = ?", (str(day),))
|
||||
totals = {(row["source"], row["domain"]): row for row in rows}
|
||||
for origin, title in ORIGINS.items():
|
||||
lines.extend(("", title))
|
||||
if not any((origin, key) in totals for key in catalog):
|
||||
lines.append("暂无样本")
|
||||
continue
|
||||
for key, name in catalog.items():
|
||||
row = totals.get((origin, key))
|
||||
counts = [row[value] if row else 0 for value in OUTCOMES]
|
||||
total = sum(counts)
|
||||
if not total:
|
||||
lines.append(f"{name}:暂无样本")
|
||||
continue
|
||||
parts = [f"{label} {count / total:.1%}({count})"
|
||||
for label, count in zip(("成功", "超时", "其他失败"), counts)]
|
||||
lines.append(f"{name}:{total} 次," + ",".join(parts))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def telehub_request(token, report):
|
||||
if not re.fullmatch(r"telehub_[a-f0-9]{64}", token):
|
||||
raise ValueError("invalid TeleHub credential format")
|
||||
headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
|
||||
if report["receipt"]:
|
||||
req = Request(REPORT_ENDPOINT + "/" + report["receipt"], headers=headers)
|
||||
else:
|
||||
headers.update({
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": "fuc.navigation.latency." + report["day"],
|
||||
})
|
||||
body = json.dumps({"bot": "info", "target": "base", "text": report["text"]}, ensure_ascii=False).encode()
|
||||
req = Request(REPORT_ENDPOINT, data=body, headers=headers)
|
||||
with build_opener(NoRedirect()).open(req, timeout=8) as result:
|
||||
return json.load(result)["data"]
|
||||
|
||||
|
||||
def deliver(db, catalog, now, send):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
day = current_end(started)
|
||||
latest = current_end(now) - timedelta(days=1)
|
||||
while day <= latest:
|
||||
if not db.execute("SELECT 1 FROM reports WHERE day=?", (str(day),)).fetchone():
|
||||
with db:
|
||||
db.execute("INSERT INTO reports (day,text) VALUES (?,?)", (str(day), format_report(db, catalog, day)))
|
||||
day += timedelta(days=1)
|
||||
timestamp = int(now.timestamp())
|
||||
reports = db.execute("""
|
||||
SELECT * FROM reports WHERE status IN ('pending','queued','sending') AND retry_at <= ? ORDER BY day LIMIT 4
|
||||
""", (timestamp,)).fetchall()
|
||||
for report in reports:
|
||||
receipt, status, delay, error = report["receipt"], report["status"], 900, None
|
||||
try:
|
||||
response = send(report)
|
||||
if not isinstance(response, dict):
|
||||
raise ValueError("invalid TeleHub response")
|
||||
new_receipt = response.get("id", "")
|
||||
new_status = response.get("status")
|
||||
if (not isinstance(new_receipt, str)
|
||||
or not re.fullmatch(r"[a-f0-9-]{36}", new_receipt)
|
||||
or (receipt and receipt != new_receipt)
|
||||
or new_status not in TERMINAL | {"queued", "sending"}
|
||||
or response.get("bot_code") != "info" or response.get("target_code") != "base"):
|
||||
raise ValueError("invalid TeleHub receipt")
|
||||
receipt, status = new_receipt, new_status
|
||||
except HTTPError as exc:
|
||||
error = "telehub_http_" + str(exc.code)
|
||||
if exc.code == 429:
|
||||
retry = exc.headers.get("Retry-After", "")
|
||||
if retry.isdigit():
|
||||
delay = max(delay, int(retry))
|
||||
elif 400 <= exc.code < 500:
|
||||
status = "rejected"
|
||||
except (ValueError, KeyError, OSError, URLError):
|
||||
error = "telehub_transport_or_response"
|
||||
with db:
|
||||
db.execute("UPDATE reports SET receipt=?, status=?, retry_at=?, error=? WHERE day=?",
|
||||
(receipt, status, timestamp + delay, error, report["day"]))
|
||||
print(report["day"], status, receipt or "-", error or "-", flush=True)
|
||||
|
||||
|
||||
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)
|
||||
return
|
||||
try:
|
||||
origin = self.headers.get("Origin")
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if origin not in ORIGINS or not 1 <= length <= 1024:
|
||||
raise ValueError("invalid request")
|
||||
values = json.loads(self.rfile.read(length))
|
||||
with closing(connect(path)) as db:
|
||||
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
|
||||
except sqlite3.Error:
|
||||
self.send_error(503)
|
||||
return
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--database", type=Path, required=True)
|
||||
parser.add_argument("--catalog", type=Path, required=True)
|
||||
sub = parser.add_subparsers(dest="mode", required=True)
|
||||
sub.add_parser("serve").add_argument("--port", type=int, default=18248)
|
||||
sub.add_parser("report")
|
||||
sub.add_parser("preview").add_argument("day", type=date.fromisoformat)
|
||||
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)
|
||||
if args.mode == "preview":
|
||||
print(format_report(db, catalog, args.day))
|
||||
elif args.mode == "report":
|
||||
credential = Path(os.environ["CREDENTIALS_DIRECTORY"])/"telehub-token"
|
||||
token = credential.read_text().strip()
|
||||
with args.database.with_suffix(".report.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
deliver(db, catalog, now, lambda report: telehub_request(token, report))
|
||||
if args.mode == "serve":
|
||||
serve(args.database, catalog, args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { domainToASCII, domainToUnicode } from 'node:url';
|
||||
|
||||
const configs = new URL('../../config/project-domains/', import.meta.url);
|
||||
const roles = new Map([
|
||||
['primary', '永久主域名'],
|
||||
['direct', '免翻墙域名'],
|
||||
['navigation', '导航站域名'],
|
||||
]);
|
||||
const accessLabels = new Map([
|
||||
['requires_proxy', '需翻墙'],
|
||||
['suspected_blocked', '疑似被墙'],
|
||||
]);
|
||||
|
||||
function load(project) {
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(project)) throw new Error('无效项目代号');
|
||||
const { domains } = JSON.parse(readFileSync(new URL(project + '.json', configs), 'utf8'));
|
||||
if (!Array.isArray(domains) || !domains.length) throw new Error(project + ' 未配置域名');
|
||||
const seenHosts = new Set();
|
||||
const seenCodes = new Set();
|
||||
const records = domains.map(({ domain, role, access, domainhub, recommended = false }) => {
|
||||
const fail = () => { throw new Error(project + ' 域名记录无效:' + domain); };
|
||||
if (typeof domain !== 'string' || /[\s:/@?#%\\]/u.test(domain)) fail();
|
||||
const host = domainToASCII(domain);
|
||||
const labels = host.split('.');
|
||||
if (host.length > 253 || labels.length < 2 || !/[a-z]/.test(labels.at(-1))
|
||||
|| labels.some(label => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))
|
||||
|| seenHosts.has(host)) fail();
|
||||
if (!roles.has(role) || (access !== undefined && !accessLabels.has(access))
|
||||
|| typeof recommended !== 'boolean' || (recommended && (role !== 'direct' || access))) fail();
|
||||
if (domainhub !== undefined) {
|
||||
if (typeof domainhub !== 'string' || !/^[a-z0-9][a-z0-9.-]*$/.test(domainhub)
|
||||
|| !domainhub.startsWith(project + '.') || seenCodes.has(domainhub)) fail();
|
||||
seenCodes.add(domainhub);
|
||||
}
|
||||
seenHosts.add(host);
|
||||
return {
|
||||
name: domainToUnicode(host), origin: 'https://' + host + '/', role, access, domainhub, recommended,
|
||||
label: roles.get(role) + (access ? '(' + accessLabels.get(access) + ')' : ''),
|
||||
};
|
||||
});
|
||||
if (records.filter(record => record.recommended).length > 1) throw new Error(project + ' 有多个默认推荐域名');
|
||||
return records;
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
const entities = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return value.replace(/[&<>"']/g, char => entities[char]);
|
||||
}
|
||||
|
||||
function renderNavigation(project, records, source) {
|
||||
const recommended = records.find(record => record.recommended);
|
||||
if (!recommended || records.filter(record => record.role === 'navigation').length !== 1) {
|
||||
throw new Error(project + ' 导航需要一个导航域名和一个默认推荐域名');
|
||||
}
|
||||
const panels = records.filter(record => record.role !== 'navigation');
|
||||
const priority = ({ recommended, role, access }) => role === 'primary' ? 0
|
||||
: recommended ? 1 : access === 'suspected_blocked' ? 3 : 2;
|
||||
panels.sort((a, b) => priority(a) - priority(b));
|
||||
const options = panels.map(({ origin, name, label, recommended, domainhub, role }) => {
|
||||
const code = domainhub ? ' data-domainhub-code="' + escapeHtml(domainhub) + '"' : '';
|
||||
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.replace('域名', '地址')) + '</small></span>',
|
||||
' <span class="latency">—</span>',
|
||||
' </label>',
|
||||
].join('\n');
|
||||
}).join('\n');
|
||||
function replaceOnce(html, pattern, replacement) {
|
||||
if ([...html.matchAll(pattern)].length !== 1) throw new Error('导航源标记不唯一:' + pattern);
|
||||
return html.replace(pattern, replacement);
|
||||
}
|
||||
|
||||
const preview = replaceOnce(source, /<!-- project-domains:start -->[\s\S]*?<!-- project-domains:end -->/g,
|
||||
() => '<!-- project-domains:start -->\n' + options + '\n <!-- project-domains:end -->');
|
||||
const withDefault = replaceOnce(preview, /(<span id="route-status" role="status">)[^<]*(<\/span>)/g,
|
||||
(_, start, end) => start + '已选择 ' + escapeHtml(recommended.name) + end);
|
||||
|
||||
// The standalone release serves its own logo and does not require the XB theme path.
|
||||
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 + '/_nav-go?route=' + encodeURIComponent(recommended.domainhub) + '"');
|
||||
return {
|
||||
preview: withDefault,
|
||||
standalone: withFallback.replace('<!doctype html>', '<!doctype html>\n<!-- 从 theme/Fuc/assets/connect.html 和项目域名清单生成。 -->'),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const [action, project, ...rest] = process.argv.slice(2);
|
||||
if (action === 'list' && rest.length === 0) {
|
||||
const projects = project ? [project] : readdirSync(configs)
|
||||
.filter(name => /^[a-z][a-z0-9-]*\.json$/.test(name)).sort().map(name => name.slice(0, -5));
|
||||
for (const key of projects) {
|
||||
for (const record of load(key)) console.log([key, record.name, record.label, record.domainhub ?? ''].join('\t'));
|
||||
}
|
||||
} else if (['build', 'check'].includes(action) && project === 'fuc' && rest.length === 0) {
|
||||
const source = new URL('../../theme/Fuc/assets/connect.html', import.meta.url);
|
||||
const read = path => readFileSync(new URL('../../' + path, import.meta.url));
|
||||
const { preview, standalone } = renderNavigation(project, load(project), readFileSync(source, 'utf8'));
|
||||
const files = [
|
||||
['theme/Fuc/assets/connect.html', Buffer.from(preview)],
|
||||
['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);
|
||||
else if (!read(path).equals(content)) throw new Error(path + ' 已过期,请重新生成');
|
||||
}
|
||||
} else {
|
||||
throw new Error('用法:manage.mjs list [项目代号] | build fuc | check fuc');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -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,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily TeleHub report
|
||||
After=network-online.target fuc-navigation-stats.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
LoadCredential=telehub-token:/etc/fuc-navigation-stats/telehub-token
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 report
|
||||
TimeoutStartSec=55
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily report and receipt checks
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:00/15:00 Asia/Shanghai
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation probe counters
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 serve
|
||||
Restart=on-failure
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.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);
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>福云地址导航</title>
|
||||
<link id="brand-icon" rel="icon" href="./native/images/brand/fuc-mark.svg?v=2" type="image/svg+xml" sizes="any">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #171426;
|
||||
--page-wash: #241b3a;
|
||||
--panel: #201c34;
|
||||
--ink: #f6f1ff;
|
||||
--muted: #bbb2d0;
|
||||
--line: #38304d;
|
||||
--accent: #c6b7ff;
|
||||
--fastest: #b6ff40;
|
||||
--notice-warm-tone: #f4d36c;
|
||||
--action: #7256df;
|
||||
--tint: #332851;
|
||||
--shadow: rgb(0 0 0 / 20%);
|
||||
font: 16px/1.55 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
background: linear-gradient(180deg, var(--page-wash), var(--page) 360px);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
button { color: inherit; font: inherit; cursor: pointer; }
|
||||
:is(a, button):focus-visible,
|
||||
.entry:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
|
||||
.wrap { width: min(740px, calc(100% - 48px)); margin-inline: auto; }
|
||||
|
||||
main { padding-block: clamp(32px, 6vw, 64px) 40px; }
|
||||
h1 { margin: 0 0 24px; font-size: clamp(32px, 5vw, 48px); line-height: 1.18; letter-spacing: -.04em; }
|
||||
.email-notice {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--notice-warm-tone) 5%, var(--page));
|
||||
font-size: 15px;
|
||||
}
|
||||
.email-notice-icon {
|
||||
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; }
|
||||
.copy-control { position: relative; display: inline-block; }
|
||||
.copy-email {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.copy-email:hover { text-decoration: underline; }
|
||||
.copy-feedback {
|
||||
position: absolute;
|
||||
inset-inline-end: 0;
|
||||
inset-block-end: calc(100% + 6px);
|
||||
z-index: 1;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 4px 12px var(--shadow);
|
||||
font-size: 12px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.copy-feedback:empty { opacity: 0; }
|
||||
|
||||
.entries {
|
||||
padding: clamp(16px, 4vw, 28px);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 18px 48px var(--shadow);
|
||||
}
|
||||
|
||||
.entries h2 { margin: 0 0 16px; font-size: 18px; }
|
||||
.routes { display: grid; gap: 8px; margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 60px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: border-color .16s ease, background-color .16s ease;
|
||||
}
|
||||
|
||||
.entry:hover { background: color-mix(in srgb, var(--tint) 50%, var(--panel)); }
|
||||
.entry:has(input:checked) { background: var(--tint); border-color: var(--accent); }
|
||||
.entry input { grid-area: 1 / 3; width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
|
||||
.entry-info { grid-area: 1 / 1; display: flex; align-items: baseline; gap: 12px; }
|
||||
.entry .latency { grid-area: 1 / 2; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.entry .latency[data-fastest] { color: var(--fastest); font-weight: 700; }
|
||||
|
||||
.entry strong { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.entry small { color: var(--muted); font-size: 13px; }
|
||||
.entry:has(input:checked) small { color: var(--accent); }
|
||||
|
||||
.panel-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
margin-block: 12px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.recheck { border: 0; background: none; padding: 6px 0; color: var(--accent); white-space: nowrap; }
|
||||
.recheck:hover { text-decoration: underline; }
|
||||
.recheck:disabled { opacity: .55; cursor: wait; }
|
||||
.enter { display: grid; place-items: center; min-height: 46px; border-radius: 9px; font-size: 14px; }
|
||||
.enter { padding-inline: 12px; color: #fff; background: var(--action); font-weight: 700; }
|
||||
.enter:hover { filter: brightness(1.1); }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.wrap { width: calc(100% - 32px); }
|
||||
h1 { margin-bottom: 18px; }
|
||||
.entry { gap: 10px; padding: 10px 12px; }
|
||||
.entry-info { flex-direction: column; gap: 1px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.entry { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap">
|
||||
<h1>福云地址导航</h1>
|
||||
<aside class="email-notice" aria-label="备用网址获取方式">
|
||||
<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">
|
||||
<button class="copy-email" type="button" aria-label="复制邮箱地址 [email protected]">
|
||||
[email protected]
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
|
||||
<path d="M8 8h9l3 3v10H8V8Z M15 8V3H3v13h5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="copy-feedback" role="status"></span>
|
||||
</span>。
|
||||
</p>
|
||||
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
|
||||
<p class="email-detail">如果忘记收藏邮箱,也可以找注册福云时发送验证码的邮箱,同样会自动回复最新地址。</p>
|
||||
</div>
|
||||
</aside>
|
||||
<section class="entries" aria-labelledby="entry-title">
|
||||
<h2 id="entry-title">访问入口</h2>
|
||||
<fieldset class="routes" aria-labelledby="entry-title">
|
||||
<!-- 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="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="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="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="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="latency">—</span>
|
||||
</label>
|
||||
<!-- project-domains:end -->
|
||||
</fieldset>
|
||||
<div class="panel-footer">
|
||||
<span id="route-status" role="status">已选择 fu99.cloud</span>
|
||||
<button class="recheck" type="button">重新检测</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<a id="enter" class="enter" href="/#/register">立即进入 →</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script src="./navigation-domainhub.js?v=manual-select-fastest-1"></script>
|
||||
<script type="module">
|
||||
import { copyText } from './clipboard.mjs';
|
||||
|
||||
const email = document.querySelector('.copy-email');
|
||||
const feedback = document.querySelector('.copy-feedback');
|
||||
let feedbackTimer;
|
||||
email.addEventListener('click', async () => {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedback.textContent = '';
|
||||
try {
|
||||
await copyText(email.textContent.trim());
|
||||
feedback.textContent = '已复制';
|
||||
feedbackTimer = setTimeout(() => { feedback.textContent = ''; }, 1600);
|
||||
} catch {
|
||||
feedback.textContent = '复制失败,请选中邮箱地址手动复制。';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+124
@@ -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);
|
||||
})();
|
||||
Reference in new issue
Block a user