feat: v0.12.2 —— 跨域只读支持(面板可部署在别处)

用户诉求:管理端与前端完全分离,本地探针只跑 /admin,前端部署到 GitHub Pages
并硬编码管理地址,探测仍在本地常驻。用户自己搭隧道给本地套 HTTPS。

硬限制(务必先看):GitHub Pages 强制 HTTPS,而浏览器「混合内容」策略禁止
HTTPS 页面 fetch HTTP 资源 —— 这与 CORS 无关,改设置也没用。
因此 settings.dataUrl 必须与面板页面同为 HTTPS。

服务端
- 只读接口(/api/status、/api/monitors、/api/events、/api/v2/getMonitors、
  /api/refresh)按 settings.corsOrigins 白名单回显 Access-Control-Allow-Origin
- /api/admin/* 一律不放行跨域,预检直接 403 —— 外部页面既读不到也改不了
- 绝不使用 '*':白名单里写 '*' 不放行任何来源

前端
- settings.dataUrl 存在时,所有 api/ 相对路径自动改写到该地址
- 数据源标记为「远程探针(跨域)」,页脚可区分
- 管理界面新增两项配置:跨域数据源地址、允许跨域的页面地址(改完立即生效)

关键设计:origin 匹配必须考虑端口
origin 是「协议 + 主机 + 端口」的完整组合。最初白名单存 http://localhost(无端口),
导致本地前端跑在 localhost:5173 时被拒 —— 浏览器实测 Failed to fetch 而 curl 能过。
修法:回环主机(localhost / 127.0.0.1)忽略端口放行,其余要求完整 origin 精确匹配。

测试:verify-security 25→40 项,新增 [D3] CORS 白名单 14 条 + [D4] '*' 写法 1 条。
全项目 8 套 334 项通过。

附记一个测试上的教训:跨域 fetch 时 JS 读不到 Access-Control-Allow-Origin
(CORS 规范规定只有同源能读),所以断言「是否放行」要看 fetch 有没有拿到数据,
不能看响应头 —— 我一开始用 headers.get() 判断,拿到 null 误以为失败。
This commit is contained in:
tamakyi
2026-10-14 16:19:31 +08:00
parent f345626840
commit 6b0a23c38e
16 changed files with 835 additions and 575 deletions
+22 -1
View File
@@ -522,6 +522,27 @@ node prober/node/index.js
> ⚠️ 注意:打开后同一端口上的公开面板(`/` 与 `/api/status`)也会跟着对外可达。它们本身是只读的,但目标名称、地址与可用率会一并暴露。如果不希望这样,请在你自己那层(反向代理/隧道)按路径收窄。 > ⚠️ 注意:打开后同一端口上的公开面板(`/` 与 `/api/status`)也会跟着对外可达。它们本身是只读的,但目标名称、地址与可用率会一并暴露。如果不希望这样,请在你自己那层(反向代理/隧道)按路径收窄。
### 面板部署在别处(跨域只读)
面板与探针可以放在两台机器上:面板放 GitHub Pages / Cloudflare(静态托管),探针放你家里或内网的机器上持续探测。两项配置:
| 配置 | 作用 |
| --- | --- |
| `settings.dataUrl` | 面板去哪里取数据,例 `https://monitor.example.com`。留空表示与探针同源 |
| `settings.corsOrigins` | 允许跨域读取的**页面地址**,逗号分隔的完整 origin,如 `https://you.github.io` |
两者都在管理界面里填(改完立即生效)。
**硬限制(务必先看)**:GitHub Pages 强制 HTTPS,而浏览器的**混合内容**策略禁止 HTTPS 页面 `fetch` HTTP 资源 —— 这与 CORS 无关,改设置也没用。**因此 `dataUrl` 必须与面板页面同为 HTTPS**(你自己搭隧道给本地探针套 HTTPS 即可)。
安全设计:
- **绝不使用 `Access-Control-Allow-Origin: *`** —— 那等于让任意网站都能读走你的监控数据。默认只放行本机回环地址(`localhost` / `127.0.0.1`,**忽略端口**,因为本地前端常跑在 5173 这类端口)
- 白名单里的 origin 必须**精确匹配**,`https://you.github.io.evil.com` 这种前缀伪造会被拒
- 回显具体 origin 并带 `Vary: Origin`,避免中间缓存串味
- **管理端永不放行跨域**:`/admin` 与 `/api/admin/*` 不带任何 `Access-Control-*` 头,外部页面无法读取也无法写入
- 跨域读到的配置同样经过密钥剥离
### 部署形态与可写能力 ### 部署形态与可写能力
| 部署形态 | 面板可读 | 探测 | 通知/维护窗口/事件 | 管理端(2FA) | | 部署形态 | 面板可读 | 探测 | 通知/维护窗口/事件 | 管理端(2FA) |
@@ -814,7 +835,7 @@ NODE_PATH=<playwright 的 node_modules> node scripts/verify-views.cjs # 视
NODE_PATH=<playwright 的 node_modules> node scripts/verify-layout.cjs # 13 视口 × 2 视图零横向溢出 + 行高一致(26 项) NODE_PATH=<playwright 的 node_modules> node scripts/verify-layout.cjs # 13 视口 × 2 视图零横向溢出 + 行高一致(26 项)
NODE_PATH=<playwright 的 node_modules> node scripts/verify-admin.cjs # 管理端 2FA 全流程(102 项:RFC 向量 / 绑定 / 会话 / 限流 / 接口 / 页面) NODE_PATH=<playwright 的 node_modules> node scripts/verify-admin.cjs # 管理端 2FA 全流程(102 项:RFC 向量 / 绑定 / 会话 / 限流 / 接口 / 页面)
node scripts/verify-worker.cjs # Cloudflare Worker(40 项:UR 映射 / 探测范围 / 失败降级 / 管理端拒绝 / 密钥泄露) node scripts/verify-worker.cjs # Cloudflare Worker(40 项:UR 映射 / 探测范围 / 失败降级 / 管理端拒绝 / 密钥泄露)
node scripts/verify-security.cjs # banner 探测 / 脱敏 / 私有分层 / 刷新限流 / 配置接口密钥泄露(25 项) node scripts/verify-security.cjs # banner 探测 / 脱敏 / 私有分层 / 刷新限流 / 密钥泄露 / CORS 白名单(40 项)
node scripts/verify-notify.cjs # 通知与证书(44 项:假 SMTP / 假 MeoW / 去抖 / 恢复 / 维护窗口 / 真实证书) node scripts/verify-notify.cjs # 通知与证书(44 项:假 SMTP / 假 MeoW / 去抖 / 恢复 / 维护窗口 / 真实证书)
UPTIMEROBOT_API_KEY=ur... node scripts/verify-uptimerobot.cjs # UR 映射/兼容接口/失败路径/冒烟(18 项) UPTIMEROBOT_API_KEY=ur... node scripts/verify-uptimerobot.cjs # UR 映射/兼容接口/失败路径/冒烟(18 项)
``` ```
+17
View File
@@ -180,6 +180,23 @@ v0.12.0 起,所有会改配置的操作都放在 `/admin`,**必须绑定并
`/api/monitors` 与 Worker 上的同名接口都**无鉴权**,因此对外响应一律剥离 `uptimeRobot.apiKey`(保留 `enabled` 等非敏感字段供面板读取)。探针内部同步 UptimeRobot 仍使用完整配置,剥离只作用于 HTTP 出口。`/api/status` 与静态 `monitors.json` 同样不含私有层内容。 `/api/monitors` 与 Worker 上的同名接口都**无鉴权**,因此对外响应一律剥离 `uptimeRobot.apiKey`(保留 `enabled` 等非敏感字段供面板读取)。探针内部同步 UptimeRobot 仍使用完整配置,剥离只作用于 HTTP 出口。`/api/status` 与静态 `monitors.json` 同样不含私有层内容。
### 跨域只读白名单(CORS)
面板部署在别处(GitHub Pages / Cloudflare)、探针在另一台机器时,需要让指定页面跨域读取状态与配置。配置项:`settings.dataUrl`(面板去哪里取数据)与 `settings.corsOrigins`(允许哪些页面读取)。
核心风险是「任意网站都能读走监控数据」,措施:
| 风险 | 措施 |
| --- | --- |
| 开放成 `*` 导致任意网站可读 | **代码里不存在 `*` 分支**:白名单里写 `*` 不会放行任何来源(已加断言) |
| 本机回环被任意端口冒用 | 默认只放行 `localhost` / `127.0.0.1` 且**忽略端口**(本地前端常跑 5173);其余必须精确匹配完整 origin |
| 前缀伪造域名(`https://you.github.io.evil.com`) | 精确字符串匹配,不做子串判断(已加断言) |
| 协议降级(`https://localhost` 冒用 http 的默认项) | 协议必须一致才走回环豁免(已加断言) |
| 中间缓存串味(把 A 的响应给 B) | 回显具体 origin 并带 `Vary: Origin` |
| **外部页面读取或改写管理端** | `/admin` 与 `/api/admin/*` **一律不带 `Access-Control-*` 头**,预检直接 403(已加断言) |
| 外部页面借 CORS 触发有副作用的调用 | `/api/admin/*` 完全不放行;`/api/refresh` 另有 `refreshDecision` 的限流与 `refreshLocalOnly` 兜底 |
| 跨域读到密钥 | 跨域响应与同源响应走同一套剥离逻辑,`uptimeRobot.apiKey` 不会回吐(已加断言) |
### 威胁模型与对应措施 ### 威胁模型与对应措施
| 威胁 | 措施 | | 威胁 | 措施 |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 452 KiB

After

Width:  |  Height:  |  Size: 452 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 264 KiB

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

After

Width:  |  Height:  |  Size: 215 KiB

+1 -1
View File
@@ -16,7 +16,7 @@
import { connect } from 'cloudflare:sockets'; import { connect } from 'cloudflare:sockets';
import { fetchUptimeRobotMonitors } from './uptimerobot.js'; import { fetchUptimeRobotMonitors } from './uptimerobot.js';
const VERSION = '0.12.1'; const VERSION = '0.12.2';
const HISTORY_LIMIT = 48; const HISTORY_LIMIT = 48;
const UPTIME_DAYS = 90; const UPTIME_DAYS = 90;
const USER_AGENT = 'shiroko-monitor/0.3 (lightweight uptime panel)'; const USER_AGENT = 'shiroko-monitor/0.3 (lightweight uptime panel)';
+64 -7
View File
@@ -39,7 +39,7 @@ const CONCURRENCY = 8;
const WRITE_DEBOUNCE_MS = 300; const WRITE_DEBOUNCE_MS = 300;
const DEFAULT_INTERVAL_SEC = 60; const DEFAULT_INTERVAL_SEC = 60;
const PORT = Number(process.env.PORT || 8787); const PORT = Number(process.env.PORT || 8787);
const VERSION = '0.12.1'; const VERSION = '0.12.2';
const UR_DEFAULT_POLL_SEC = 300; const UR_DEFAULT_POLL_SEC = 300;
const UR_MIN_REFRESH_GAP_MS = 60000; const UR_MIN_REFRESH_GAP_MS = 60000;
@@ -875,6 +875,56 @@ function sendJson(res, data, { status = 200, headers = {} } = {}) {
res.end(JSON.stringify(data)); res.end(JSON.stringify(data));
} }
/* ---------- 跨域只读(前端可部署在别处,数据源指向本机) ---------- */
// 允许跨域读取的前端来源。默认放行本机:本地开发时前端页面与探针常常跑在不同端口上
// (例如 Vite 的 5173),而 origin 是「协议 + 主机 + 端口」的完整组合,
// 因此默认项按「忽略端口」匹配,主机相同即放行。
// 部署在 GitHub Pages / Cloudflare 等其它域名时,在 settings.corsOrigins 里显式列出
// 完整 origin(含协议与端口,如 https://you.github.io)。绝不使用 '*':
// 那等于让任意网站都能读走监控数据。
function corsOrigins(config) {
const extra = Array.isArray(config.settings?.corsOrigins)
? config.settings.corsOrigins.map((s) => String(s).trim()).filter(Boolean)
: [];
return { exact: new Set(extra), loopbackHosts: new Set(['127.0.0.1', 'localhost', '[::1]']) };
}
// 请求的 origin 是否在白名单内。主机是本机回环地址时忽略端口(本地开发常见形态),
// 其余情况要求完整 origin 精确匹配。
function originAllowed(reqOrigin, config) {
let u;
try { u = new URL(reqOrigin); } catch { return false; }
const { exact, loopbackHosts } = corsOrigins(config);
if (exact.has(reqOrigin)) return true;
return u.protocol === 'http:' && loopbackHosts.has(u.hostname);
}
// 返回跨域响应头;origin 不在白名单时返回空对象(请求本身照常处理,只是浏览器读不到响应)
function corsHeaders(req, config) {
const origin = req.headers.origin;
if (!origin || !originAllowed(origin, config)) return {};
return {
'access-control-allow-origin': origin, // 回显具体 origin,由白名单保证安全
'access-control-allow-methods': 'GET, POST, OPTIONS',
'access-control-allow-headers': 'content-type',
'access-control-max-age': '86400',
vary: 'Origin', // 缓存必须区分 Origin,否则会串味
};
}
// 只读接口的预检响应。写接口(/api/refresh、/api/admin/*)不放行 OPTIONS,
// 因此外部页面无法用简单请求之外的方式触发有副作用的调用。
function handlePreflight(req, res, config) {
const headers = corsHeaders(req, config);
if (!headers['access-control-allow-origin']) {
res.writeHead(403);
return res.end('origin not allowed');
}
res.writeHead(204, headers);
res.end();
}
/* ---------- /api/refresh 滥用防护 ---------- */ /* ---------- /api/refresh 滥用防护 ---------- */
// 仅信任 socket 的对端地址,不解析 X-Forwarded-For(可被伪造);若前方挂了反向代理,请改用 allowRefresh:false // 仅信任 socket 的对端地址,不解析 X-Forwarded-For(可被伪造);若前方挂了反向代理,请改用 allowRefresh:false
@@ -985,15 +1035,22 @@ function createServer(runtime) {
res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-store' }); res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-store' });
return void fs.createReadStream(file).pipe(res); return void fs.createReadStream(file).pipe(res);
} }
if (url.pathname === '/api/status') return sendJson(res, snapshot(runtime)); // 预检:只对只读接口与 /api/refresh 放行(/api/admin/* 一律不放行,管理端必须同源访问)。
if (url.pathname === '/api/monitors') return sendJson(res, publicConfig(config)); // /api/refresh 虽然有副作用,但已有 refreshDecision 的限流与 refreshLocalOnly 兜底,
// 且它不带自定义头时属于「简单请求」——浏览器无论如何都会把它发出去,
// 加跨域头只影响响应能否被 JS 读到(前端据此退回只读),不影响安全性。
if (req.method === 'OPTIONS' && (url.pathname === '/api/status' || url.pathname === '/api/monitors' || url.pathname === '/api/events' || url.pathname === '/api/refresh' || url.pathname === '/api/v2/getMonitors' || url.pathname === '/v2/getMonitors')) {
return handlePreflight(req, res, config);
}
if (url.pathname === '/api/status') return sendJson(res, snapshot(runtime), { headers: corsHeaders(req, config) });
if (url.pathname === '/api/monitors') return sendJson(res, publicConfig(config), { headers: corsHeaders(req, config) });
if (url.pathname === '/api/refresh') { if (url.pathname === '/api/refresh') {
const decide = refreshDecision(config, req.socket.remoteAddress); const decide = refreshDecision(config, req.socket.remoteAddress);
if (!decide.ok) { if (!decide.ok) {
// 只回错误码,不回显目标地址与内部细节 // 只回错误码,不回显目标地址与内部细节
return sendJson(res, { error: decide.error }, { return sendJson(res, { error: decide.error }, {
status: decide.status, status: decide.status,
headers: decide.retryAfter ? { 'retry-after': String(decide.retryAfter) } : {}, headers: { ...(decide.retryAfter ? { 'retry-after': String(decide.retryAfter) } : {}), ...corsHeaders(req, config) },
}); });
} }
// scope=external:只同步 UptimeRobot,不跑本地探测轮次(面板在「只看 UR」模式下用) // scope=external:只同步 UptimeRobot,不跑本地探测轮次(面板在「只看 UR」模式下用)
@@ -1010,19 +1067,19 @@ function createServer(runtime) {
]); ]);
// 浏览器中断请求(切页/关标签)是常态:等待期间连接可能已断开,此时不能再写响应 // 浏览器中断请求(切页/关标签)是常态:等待期间连接可能已断开,此时不能再写响应
if (res.writableEnded || res.destroyed) return; if (res.writableEnded || res.destroyed) return;
return sendJson(res, snapshot(runtime)); return sendJson(res, snapshot(runtime), { headers: corsHeaders(req, config) });
} }
// UptimeRobot 兼容的只读接口(GET/POST 均可):已有脚本/看板可直接消费本服务数据。 // UptimeRobot 兼容的只读接口(GET/POST 均可):已有脚本/看板可直接消费本服务数据。
// 不做鉴权,因为其暴露内容与公开面板一致;如需鉴权请在其前方加代理。 // 不做鉴权,因为其暴露内容与公开面板一致;如需鉴权请在其前方加代理。
if (url.pathname === '/api/v2/getMonitors' || url.pathname === '/v2/getMonitors') { if (url.pathname === '/api/v2/getMonitors' || url.pathname === '/v2/getMonitors') {
return sendJson(res, toUptimeRobotResponse(runtime)); return sendJson(res, toUptimeRobotResponse(runtime), { headers: corsHeaders(req, config) });
} }
// 事件时间线:面板「事件」视图取这里(含通知去抖前的全部状态翻转记录) // 事件时间线:面板「事件」视图取这里(含通知去抖前的全部状态翻转记录)
if (url.pathname === '/api/events') { if (url.pathname === '/api/events') {
const list = [...(runtime.events ?? [])].reverse(); const list = [...(runtime.events ?? [])].reverse();
return sendJson(res, { total: list.length, events: list.slice(0, 200) }); return sendJson(res, { total: list.length, events: list.slice(0, 200) }, { headers: corsHeaders(req, config) });
} }
let rel = decodeURIComponent(url.pathname); let rel = decodeURIComponent(url.pathname);
+37
View File
@@ -139,6 +139,8 @@ export function createAdminRouter({ auth, localConfigPath, reloadConfig, runtime
notifyEnabled: notifyConfig(cfg).enabled, notifyEnabled: notifyConfig(cfg).enabled,
tlsEnabled: tlsConfig(cfg).enabled, tlsEnabled: tlsConfig(cfg).enabled,
adminUrl: s.adminUrl ?? '', adminUrl: s.adminUrl ?? '',
dataUrl: s.dataUrl ?? '',
corsOrigins: Array.isArray(s.corsOrigins) ? s.corsOrigins : [],
}, },
maintenance: Array.isArray(s.maintenance) ? s.maintenance : [], maintenance: Array.isArray(s.maintenance) ? s.maintenance : [],
monitors: cfg.monitors.map((m) => ({ monitors: cfg.monitors.map((m) => ({
@@ -325,6 +327,41 @@ export function createAdminRouter({ auth, localConfigPath, reloadConfig, runtime
return sendJson(res, { ok: true, adminUrl: raw }); return sendJson(res, { ok: true, adminUrl: raw });
} }
if (p === '/api/admin/remote' && req.method === 'POST') {
const parsed = await readJsonBody(req, res);
if (!parsed.ok) return;
const body = parsed.value;
// 跨域数据源:允许省略协议(默认 https),省得使用者每次都写全
const rawUrl = String(body.dataUrl ?? '').trim();
let dataUrl = '';
if (rawUrl) {
let u;
try { u = new URL(/^https?:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`); } catch {
return sendJson(res, { error: 'invalid-url', hint: '不是合法的地址' }, { status: 400 });
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
return sendJson(res, { error: 'invalid-url', hint: '只支持 http/https' }, { status: 400 });
}
dataUrl = u.origin + u.pathname.replace(/\/+$/, '');
}
// CORS 白名单:只收完整的 origin,且拒绝 '*'
const origins = Array.isArray(body.corsOrigins)
? body.corsOrigins.map((s) => String(s).trim()).filter(Boolean)
: String(body.corsOrigins ?? '').split(',').map((s) => s.trim()).filter(Boolean);
const bad = origins.filter((o) => o === '*' || !/^https?:\/\/[^\s/]+(:\d+)?$/.test(o));
if (bad.length) {
return sendJson(res, { error: 'invalid-origin', hint: `这些写法不合法(必须是完整来源,且不允许 *):${bad.join(', ')}` }, { status: 400 });
}
savePrivateConfig(localConfigPath, (local) => {
local.settings = { ...(local.settings ?? {}), dataUrl, corsOrigins: origins };
return local;
});
reloadConfig();
scheduleWrite(runtime);
console.log(`[admin] 跨域设置已保存:dataUrl=${dataUrl || '(空)'},corsOrigins=${origins.length ? origins.join(' ') : '(默认)'}`);
return sendJson(res, { ok: true, dataUrl, corsOrigins: origins });
}
if (p === '/api/admin/probe-now' && req.method === 'POST') { if (p === '/api/admin/probe-now' && req.method === 'POST') {
await Promise.race([forceRound(runtime), new Promise((r) => setTimeout(r, forcedMaxWaitMs))]); await Promise.race([forceRound(runtime), new Promise((r) => setTimeout(r, forcedMaxWaitMs))]);
if (res.writableEnded || res.destroyed) return; if (res.writableEnded || res.destroyed) return;
+17
View File
@@ -134,6 +134,23 @@
面板不做任何假设。 面板不做任何假设。
</p> </p>
</div> </div>
<div class="admin-field">
<label for="data-url">跨域数据源地址</label>
<input type="url" id="data-url" placeholder="https://monitor.example.com" autocomplete="off">
<p class="admin-hint">
仅当<b>面板部署在别处</b>(GitHub Pages / Cloudflare)而探针在另一台机器时才需要填。
填了之后面板会去这个地址取数据,因此<b>该地址必须与页面同为 HTTPS</b> ——
HTTPS 页面读 HTTP 会被浏览器以「混合内容」为由直接拦截,与跨域设置无关。
</p>
</div>
<div class="admin-field">
<label for="cors-origins">允许跨域读取的页面地址</label>
<input type="text" id="cors-origins" placeholder="https://you.github.io, https://monitor.example.com" autocomplete="off">
<p class="admin-hint">
逗号分隔,<b>必须是完整来源(含协议与端口)</b>。只有这里列出的页面才能跨域读走监控数据;
默认只放行 <code>http://127.0.0.1</code> 与 <code>http://localhost</code>。管理端本身永远不同源开放。
</p>
</div>
<div class="admin-row"> <div class="admin-row">
<button type="button" class="admin-btn" id="probe-now">立即重新探测</button> <button type="button" class="admin-btn" id="probe-now">立即重新探测</button>
<button type="button" class="admin-btn" id="notify-test">发送通知自检</button> <button type="button" class="admin-btn" id="notify-test">发送通知自检</button>
+17
View File
@@ -382,6 +382,8 @@ function renderConsole(d) {
$('data-filter').value = d.settings?.dataFilter ?? 'both'; $('data-filter').value = d.settings?.dataFilter ?? 'both';
$('admin-url').value = d.settings?.adminUrl ?? ''; $('admin-url').value = d.settings?.adminUrl ?? '';
$('admin-url').dataset.saved = $('admin-url').value; $('admin-url').dataset.saved = $('admin-url').value;
$('data-url').value = d.settings?.dataUrl ?? '';
$('cors-origins').value = (d.settings?.corsOrigins ?? []).join(', ');
// 维护窗口目标下拉 // 维护窗口目标下拉
const sel = $('mw-id'); const sel = $('mw-id');
@@ -559,6 +561,21 @@ $('admin-url').addEventListener('change', async (e) => {
} }
}); });
async function saveRemoteSettings() {
const dataUrl = $('data-url').value.trim();
const corsOrigins = $('cors-origins').value.split(',').map((s) => s.trim()).filter(Boolean);
const r = await api('/remote', { method: 'POST', body: { dataUrl, corsOrigins } });
if (r.ok) {
msg($('action-msg'), dataUrl ? `跨域数据源:${r.data.dataUrl};已放行 ${r.data.corsOrigins.length} 个来源` : '已清空跨域数据源', 'ok');
refresh();
} else {
msg($('action-msg'), errText(r.data?.error, r.data?.hint), 'err');
}
}
$('data-url').addEventListener('change', saveRemoteSettings);
$('cors-origins').addEventListener('change', saveRemoteSettings);
$('probe-now').addEventListener('click', async () => { $('probe-now').addEventListener('click', async () => {
const btn = $('probe-now'); const btn = $('probe-now');
btn.disabled = true; btn.disabled = true;
+29 -8
View File
@@ -1,4 +1,4 @@
const VERSION = '0.12.1'; const VERSION = '0.12.2';
const HB_LIMIT = 48; const HB_LIMIT = 48;
const UPTIME_DAYS = 90; const UPTIME_DAYS = 90;
const BROWSER_CONCURRENCY = 6; const BROWSER_CONCURRENCY = 6;
@@ -28,6 +28,7 @@ const $ = (id) => document.getElementById(id);
const SOURCE_LABEL = { const SOURCE_LABEL = {
api: '边缘 API(实时)', api: '边缘 API(实时)',
remote: '远程探针(跨域)',
static: '静态快照', static: '静态快照',
browser: '浏览器直连', browser: '浏览器直连',
}; };
@@ -36,7 +37,10 @@ const ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;
const escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ESC[c]); const escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ESC[c]);
async function fetchJson(url, timeoutMs = 8000) { async function fetchJson(url, timeoutMs = 8000) {
const res = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) }); // 相对路径 + 存在远程数据源时,自动改写到该地址(跨域读取由对方开放 CORS)
const base = remoteBase();
const full = base && url.startsWith('api/') ? `${base}/${url}` : url;
const res = await fetch(full, { cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) });
if (!res.ok) { if (!res.ok) {
const err = new Error(`HTTP ${res.status}`); const err = new Error(`HTTP ${res.status}`);
err.status = res.status; err.status = res.status;
@@ -83,9 +87,26 @@ function setSource(s) {
$('source-badge').textContent = `数据源:${SOURCE_LABEL[s] ?? s}`; $('source-badge').textContent = `数据源:${SOURCE_LABEL[s] ?? s}`;
} }
// 跨域数据源:settings.dataUrl 指向另一台机器上的探针(通常是本机,但页面部署在别处)。
// 例:"https://monitor.example.com" —— 前端会从 https://monitor.example.com/api/status 取数据。
// 该地址必须与本页同为 HTTPS,否则浏览器会以「混合内容」为由拦截(与 CORS 无关)。
function remoteBase() {
const raw = String(state.config?.settings?.dataUrl ?? '').trim();
if (!raw) return '';
try {
const u = new URL(raw);
return u.protocol === 'http:' || u.protocol === 'https:' ? u.origin + u.pathname.replace(/\/+$/, '') : '';
} catch {
return '';
}
}
async function resolveSource() { async function resolveSource() {
const forced = new URLSearchParams(location.search).get('source'); const forced = new URLSearchParams(location.search).get('source');
const mode = forced || state.config.settings?.dataSource || 'auto'; const mode = forced || state.config.settings?.dataSource || 'auto';
// 配置了远程数据源时,「api」与「auto」都优先尝试远程地址
const remote = remoteBase();
const apiUrl = remote ? `${remote}/api/status` : 'api/status';
if (mode === 'browser') return setSource('browser'); if (mode === 'browser') return setSource('browser');
if (mode === 'static') { if (mode === 'static') {
try { try {
@@ -97,17 +118,17 @@ async function resolveSource() {
} }
if (mode === 'api') { if (mode === 'api') {
try { try {
await fetchJson('api/status', 5000); await fetchJson(apiUrl, 6000);
return setSource('api'); return setSource(remote ? 'remote' : 'api');
} catch { } catch {
return setSource('browser'); return setSource('browser');
} }
} }
// auto:优先边缘 API,其次静态快照,最后浏览器直连 // auto:优先远程/边缘 API,其次静态快照,最后浏览器直连
try { try {
await fetchJson('api/status', 3000); await fetchJson(apiUrl, 4000);
return setSource('api'); return setSource(remote ? 'remote' : 'api');
} catch { /* 无边缘 API */ } } catch { /* 无边缘/远程 API */ }
try { try {
await fetchJson('status.json', 3000); await fetchJson('status.json', 3000);
return setSource('static'); return setSource('static');
+1 -1
View File
@@ -76,7 +76,7 @@
<span id="updated-at" class="footer-item">–</span> <span id="updated-at" class="footer-item">–</span>
<span id="countdown" class="footer-item">–</span> <span id="countdown" class="footer-item">–</span>
<a id="admin-link" class="footer-item admin-link" hidden>管理</a> <a id="admin-link" class="footer-item admin-link" hidden>管理</a>
<span class="footer-item version">shiroko-monitor v0.12.1</span> <span class="footer-item version">shiroko-monitor v0.12.2</span>
</footer> </footer>
<script type="module" src="assets/app.js"></script> <script type="module" src="assets/app.js"></script>
+2
View File
@@ -10,6 +10,8 @@
"refreshInterval": 300, "refreshInterval": 300,
"dataSource": "auto", "dataSource": "auto",
"adminUrl": "", "adminUrl": "",
"dataUrl": "",
"corsOrigins": [],
"uptimeRobot": { "uptimeRobot": {
"enabled": false, "enabled": false,
"apiKey": "", "apiKey": "",
+557 -557
View File
File diff suppressed because it is too large Load Diff
+71
View File
@@ -172,6 +172,77 @@ async function main() {
check('静态 monitors.json 不含私有层内容', !pubText.includes(SECRET), ''); check('静态 monitors.json 不含私有层内容', !pubText.includes(SECRET), '');
srvC.kill(); srvC.kill();
// ---------- D3:跨域只读(CORS 白名单) ----------
// 场景:前端部署在 GitHub Pages / Cloudflare,探针在另一台机器,
// 需要让指定页面能跨域读状态与配置。核心风险是「任意网站都能读走监控数据」。
console.log('\n[D3] 跨域只读白名单');
const corsCfg = path.join(TMP, 'cors.json');
fs.writeFileSync(corsCfg, JSON.stringify({
settings: {
title: 't',
corsOrigins: ['https://you.github.io', 'https://monitor.example.com'],
uptimeRobot: { enabled: true, apiKey: SECRET },
},
monitors: [],
}, null, 2));
const srvD = startProber([`--config=${corsCfg}`, `--local-config=${corsCfg}`, `--out=${path.join(TMP, 'd.json')}`], { PORT: '8895' });
await waitForHttp('http://127.0.0.1:8895/api/status');
const acaoOf = async (pathname, origin, method = 'GET') => {
const res = await fetch(`http://127.0.0.1:8895${pathname}`, { method, headers: { Origin: origin } });
return res.headers.get('access-control-allow-origin');
};
check('白名单内的 GitHub Pages 来源被放行', await acaoOf('/api/status', 'https://you.github.io') === 'https://you.github.io');
check('白名单内的自定义域名被放行', await acaoOf('/api/status', 'https://monitor.example.com') === 'https://monitor.example.com');
check('白名单外的站点被拒(无跨域头)', await acaoOf('/api/status', 'https://evil.example') === null);
check('前缀伪造的域名被拒(如 https://you.github.io.evil.com)', await acaoOf('/api/status', 'https://you.github.io.evil.com') === null);
check('协议不符的同域被拒(https 的 localhost 不匹配 http 默认项)', await acaoOf('/api/status', 'https://localhost') === null);
// 本机回环:默认放行且忽略端口(本地前端与探针常跑在不同端口)
check('本机 localhost 放行(任意端口)', await acaoOf('/api/status', 'http://localhost:5173') === 'http://localhost:5173');
check('本机 127.0.0.1 放行(任意端口)', await acaoOf('/api/status', 'http://127.0.0.1:3000') === 'http://127.0.0.1:3000');
check('局域网 IP 未列入白名单时被拒', await acaoOf('/api/status', 'http://192.168.1.5:5173') === null);
// 预检
const pre = await fetch('http://127.0.0.1:8895/api/status', { method: 'OPTIONS', headers: { Origin: 'https://you.github.io', 'Access-Control-Request-Method': 'GET' } });
check('合法来源的预检返回 204 且带跨域头', pre.status === 204 && pre.headers.get('access-control-allow-origin') === 'https://you.github.io', `HTTP ${pre.status}`);
const preBad = await fetch('http://127.0.0.1:8895/api/status', { method: 'OPTIONS', headers: { Origin: 'https://evil.example', 'Access-Control-Request-Method': 'GET' } });
check('非法来源的预检被拒 403', preBad.status === 403, `HTTP ${preBad.status}`);
// 各只读接口都放行
const readOnly = ['/api/status', '/api/monitors', '/api/events', '/api/v2/getMonitors'];
const allowed = [];
for (const p of readOnly) allowed.push((await acaoOf(p, 'https://you.github.io')) === 'https://you.github.io');
check('四个只读接口都支持跨域', allowed.every(Boolean), readOnly.filter((_, i) => !allowed[i]).join(',') || '全部放行');
// 关键:管理端绝不能跨域
const adminAcao = [];
for (const p of ['/api/admin/status', '/api/admin/overview', '/api/admin/login']) {
const r = await fetch(`http://127.0.0.1:8895${p}`, { method: 'GET', headers: { Origin: 'https://you.github.io' } });
adminAcao.push(r.headers.get('access-control-allow-origin'));
}
check('管理端接口一律不带跨域头(必须同源访问)', adminAcao.every((v) => v === null), JSON.stringify(adminAcao));
const adminPre = await fetch('http://127.0.0.1:8895/api/admin/overview', { method: 'OPTIONS', headers: { Origin: 'https://you.github.io', 'Access-Control-Request-Method': 'POST' } });
check('管理端的预检被拒 403(外部页面无法发写操作)', adminPre.status === 403, `HTTP ${adminPre.status}`);
// 跨域读到的配置同样不得含密钥
const corsMonitors = await (await fetch('http://127.0.0.1:8895/api/monitors', { headers: { Origin: 'https://you.github.io' } })).text();
check('跨域读取配置时不泄露 API Key', !corsMonitors.includes(SECRET), corsMonitors.includes(SECRET) ? '泄露了!' : '未泄露');
srvD.kill();
// corsOrigins 里不允许 '*'
console.log('\n[D4] corsOrigins 的写法校验');
const starCfg = path.join(TMP, 'star.json');
fs.writeFileSync(starCfg, JSON.stringify({ settings: { title: 't', corsOrigins: ['*'] }, monitors: [] }, null, 2));
const { corsOrigins: corsFn } = await import(`file://${PROBER.replace(/\\/g, '/')}`).catch(() => ({}));
// corsOrigins 未导出时以 HTTP 层验证:配置 '*' 后不应变成任意来源可读
const srvE = startProber([`--config=${starCfg}`, `--local-config=${starCfg}`, `--out=${path.join(TMP, 'e.json')}`], { PORT: '8894' });
await waitForHttp('http://127.0.0.1:8894/api/status');
const starRes = await fetch('http://127.0.0.1:8894/api/status', { headers: { Origin: 'https://anything.example' } });
check("corsOrigins 配成 '*' 不会放行任意来源(必须写完整 origin)", starRes.headers.get('access-control-allow-origin') === null, starRes.headers.get('access-control-allow-origin') ?? '无跨域头');
srvE.kill();
// ---------- E:来源判定 ---------- // ---------- E:来源判定 ----------
console.log('\n[E] 来源判定'); console.log('\n[E] 来源判定');
const { isPrivateAddress } = await import(`file://${PROBER.replace(/\\/g, '/')}`); const { isPrivateAddress } = await import(`file://${PROBER.replace(/\\/g, '/')}`);