one-model-router 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,141 @@
1
+ /**
2
+ * 扫码登录的手机落地页服务(局域网,仅三个只读端点)。
3
+ *
4
+ * 目的:二维码内容不再指向站点 scanUrl,而是本机页面 —— 手机全程只看到
5
+ * 这个中性页面(无任何品牌信息),授权在页内 iframe 完成(本地代理首跳、
6
+ * 剥掉防嵌入头),授权成功后页面直接显示「登录成功」,绝不跳转到站点页面
7
+ * (站点对所有响应发 X-Frame-Options: DENY,iframe 里的回调链会被浏览器
8
+ * 拦截、不渲染;主页面早已切到成功态)。
9
+ *
10
+ * 令牌边界:本服务只暴露 {status}(pending/scanned/done/expired),
11
+ * 令牌永远只由 PC 侧 pollRelayQrLogin 获取;手机页面拿不到任何凭据。
12
+ *
13
+ * 安全:独立小服务绑 0.0.0.0(手机可达),但只有上述三个路由,
14
+ * 不代理 admin API、不读不写任何本地数据。
15
+ */
16
+ import http from 'node:http'
17
+ import os from 'node:os'
18
+
19
+ /** 本机局域网 IPv4(无则返回空串,调用方回退直连 scanUrl)。 */
20
+ export function lanAddress() {
21
+ const found = []
22
+ for (const [name, list] of Object.entries(os.networkInterfaces())) {
23
+ for (const n of list ?? []) {
24
+ if (n.family === 'IPv4' && !n.internal) found.push({ name, address: n.address })
25
+ }
26
+ }
27
+ // 优先常见路由器网段;虚拟网卡(vEthernet/WSL/Docker/Loopback 等)垫底,
28
+ // 避免手机扫出来的地址实际不可达
29
+ const score = ({ name, address }) => {
30
+ let s = 0
31
+ if (/^192\.168\./.test(address)) s += 8
32
+ else if (/^10\./.test(address)) s += 6
33
+ else if (/^172\.(1[6-9]|2\d|3[01])\./.test(address)) s += 3
34
+ if (/vEthernet|WSL|Docker|Loopback|Hyper|VMware|Virtual/i.test(name)) s -= 10
35
+ return s
36
+ }
37
+ found.sort((a, b) => score(b) - score(a))
38
+ return found[0]?.address ?? ''
39
+ }
40
+
41
+ function pageHtml(qrId) {
42
+ // 中性手机页:无品牌名;iframe 走本地代理;轮询本地状态端点
43
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
44
+ <meta name="viewport" content="width=device-width,initial-scale=1">
45
+ <title>登录授权</title>
46
+ <style>
47
+ html,body{margin:0;height:100%;font:15px/1.6 system-ui,sans-serif;background:#0f1115;color:#e6edf3}
48
+ #wrap{display:flex;flex-direction:column;height:100%}
49
+ header{padding:12px 16px;text-align:center;border-bottom:1px solid #21262d;font-weight:600}
50
+ #tip{padding:10px 16px;text-align:center;color:#8b949e}
51
+ #f{flex:1;width:100%;border:0;background:#fff}
52
+ #ok{display:none;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center;padding:24px}
53
+ #ok .big{font-size:44px;color:#3fb950}
54
+ #ok .sub{color:#8b949e}
55
+ </style></head><body>
56
+ <div id="wrap">
57
+ <header>登录授权</header>
58
+ <div id="tip">请在下方完成授权确认;授权成功后本页面会自动提示,无需其它操作。</div>
59
+ <iframe id="f" src="/qr-go/${encodeURIComponent(qrId)}" allow="credentials"></iframe>
60
+ <div id="ok"><div class="big">✓</div><div>登录成功<div class="sub">可以关闭此页面,回到电脑上继续使用</div></div></div>
61
+ </div>
62
+ <script>
63
+ const f = document.getElementById('f'), tip = document.getElementById('tip'), ok = document.getElementById('ok')
64
+ const timer = setInterval(async () => {
65
+ try {
66
+ const r = await (await fetch('/qr-status/${encodeURIComponent(qrId)}')).json()
67
+ if (r.status === 'done') {
68
+ clearInterval(timer)
69
+ f.style.display = 'none'; tip.textContent = ''
70
+ ok.style.display = 'flex'
71
+ } else if (r.status === 'expired') {
72
+ clearInterval(timer)
73
+ f.style.display = 'none'
74
+ tip.textContent = '二维码已过期,请在电脑上重新发起登录'
75
+ }
76
+ } catch { /* 网络抖动,下轮再试 */ }
77
+ }, 1200)
78
+ </script></body></html>`
79
+ }
80
+
81
+ /**
82
+ * 懒启动单例。getScanUrl(qrId) 提供站点原始扫码链接;getStatus(qrId) 读 PC 侧缓存状态。
83
+ * 返回本地基址(如 http://192.168.1.5:18690);启动失败返回空串(调用方回退直连)。
84
+ */
85
+ export async function ensureQrMobile({ getScanUrl, getStatus, port = Number(process.env.OMR_QR_PORT) || 18690 } = {}) {
86
+ if (globalThis.__omrQrMobile?.listening) return globalThis.__omrQrMobile.baseUrl
87
+ const ip = lanAddress()
88
+ if (!ip) return ''
89
+ const server = http.createServer((req, res) => {
90
+ const url = new URL(req.url ?? '/', 'http://localhost')
91
+ const m = url.pathname.match(/^\/(qr|qr-go|qr-status)\/([A-Za-z0-9_-]{8,128})$/)
92
+ if (req.method !== 'GET' || !m) { res.writeHead(404); res.end(); return }
93
+ const [, kind, id] = m
94
+ if (kind === 'qr') {
95
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
96
+ res.end(pageHtml(id))
97
+ return
98
+ }
99
+ if (kind === 'qr-status') {
100
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
101
+ res.end(JSON.stringify({ status: getStatus(id) ?? 'unknown' }))
102
+ return
103
+ }
104
+ // qr-go:代理首跳(站点 303 → 提供商授权页),剥防嵌入头后本地渲染
105
+ void (async () => {
106
+ try {
107
+ const scanUrl = getScanUrl(id)
108
+ if (!scanUrl) { res.writeHead(410, { 'content-type': 'text/plain; charset=utf-8' }); res.end('二维码不存在或已过期'); return }
109
+ const headers = { 'user-agent': String(req.headers['user-agent'] ?? 'Mozilla/5.0') }
110
+ let target = scanUrl
111
+ let r = null
112
+ for (let i = 0; i < 5; i++) {
113
+ r = await fetch(target, { redirect: 'manual', headers, signal: AbortSignal.timeout(15_000) })
114
+ const loc = r.headers.get('location')
115
+ if (r.status >= 300 && r.status < 400 && loc) {
116
+ target = new URL(loc, target).href
117
+ continue
118
+ }
119
+ break
120
+ }
121
+ if (!r) throw new Error('无响应')
122
+ const body = Buffer.from(await r.arrayBuffer())
123
+ res.writeHead(200, {
124
+ 'content-type': r.headers.get('content-type') ?? 'text/html; charset=utf-8',
125
+ 'cache-control': 'no-store',
126
+ })
127
+ res.end(body)
128
+ } catch (error) {
129
+ if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
130
+ res.end(`授权页加载失败:${error?.message ?? error}`)
131
+ }
132
+ })()
133
+ })
134
+ await new Promise((resolve, reject) => {
135
+ server.once('error', reject)
136
+ server.listen(port, '0.0.0.0', resolve)
137
+ })
138
+ const baseUrl = `http://${ip}:${server.address().port}`
139
+ globalThis.__omrQrMobile = { listening: true, baseUrl }
140
+ return baseUrl
141
+ }
@@ -1,30 +1,29 @@
1
1
  /**
2
- * DSH Remote 站点账号「一键登录」(桌面端)。
2
+ * DSH Remote 站点账号「一键登录」。
3
3
  *
4
- * 用户点一下「登录并保存令牌」→ 弹出独立登录窗口 → 在 dsh.r2049.cn 完成登录
5
- * (知乎 / GitHub 扫码或账号密码)→ 从 Authorization 请求头或登录态里捕获站点
4
+ * Electron 主进程(桌面端):弹出独立登录窗口 → 在 dsh.r2049.cn 完成登录
5
+ * (知乎 / GitHub 扫码)→ 从 Authorization 请求头或登录态里捕获站点
6
6
  * Bearer token → 交给编排层 `updateSyncSettings` 密封落盘并注册 Host → 关闭窗口。
7
7
  *
8
+ * 纯 Node(npm start 的 Web 端):不再拉起本机浏览器 —— 站点登录态属于
9
+ * dsh.r2049.cn 源,跨域无法被本服务读取,改写「Web 方式」:
10
+ * - 管理页在新标签页打开站点登录页,用户用自己浏览器的登录态完成登录;
11
+ * - 用户从开发者工具复制站点令牌,粘贴回管理页;
12
+ * - 幂等走同一个 `updateSyncSettings` 入口:密封落盘 + 一次性 Host 注册。
13
+ *
8
14
  * 凭据边界(与 P0/B1 探针一致):
9
- * - 站点 token 只在内存中传递,不写文件、不打印、不进任何 API 返回值;
10
- * - 用独立 partition / 临时 profile,不碰用户日常浏览器;
15
+ * - 站点 token 只在内存 / 单次请求体里传递,不写文件、不打印、不进任何 API 返回值;
16
+ * - Electron 用独立 partition,不碰用户日常浏览器;
11
17
  * - 注册 Host 成功后编排层会立即把 siteToken 清空,长期只留设备级凭据。
12
- *
13
- * 窗口实现:
14
- * - Electron 主进程(桌面端默认):原生 BrowserWindow + 独立 session partition;
15
- * - 纯 Node(npm start / 调试):playwright-core + 系统 Chrome/Edge。
16
- * 两条路径都同时用「请求头」和「localStorage 扫描」双通道捕获,任一命中即完成。
17
18
  */
18
19
 
19
- import { existsSync, readFileSync } from 'node:fs'
20
20
  import { fileURLToPath } from 'node:url'
21
21
 
22
22
  const DEFAULT_ORIGIN = 'https://dsh.r2049.cn'
23
+ /** 登录方式:Electron 弹独立窗口;纯 Node(Web 端)走「新标签页 + 粘贴令牌」。 */
24
+ const LOGIN_MODE = process.versions?.electron ? 'popup' : 'web'
23
25
  /** 登录窗口 preload:首帧前加遮罩,注入脚本改完 DOM 再撤掉,避免页面闪跳。 */
24
26
  const PRELOAD_PATH = fileURLToPath(new URL('./login-preload.cjs', import.meta.url))
25
- const VEIL_SCRIPT = (() => {
26
- try { return readFileSync(PRELOAD_PATH, 'utf8') } catch { return '' }
27
- })()
28
27
  /** 测试/CI 可用环境变量缩短等待与关闭可见窗口;生产默认 30 分钟 + 可见窗口。 */
29
28
  const LOGIN_WAIT_MS = Number(process.env.OMR_RELAY_LOGIN_TIMEOUT_MS) || 30 * 60_000
30
29
  const POLL_MS = Number(process.env.OMR_RELAY_LOGIN_POLL_MS) || 1200
@@ -140,7 +139,7 @@ const BANNER_SCRIPT = `(() => {
140
139
  const d = document.createElement('div')
141
140
  d.id = 'omr-login-banner'
142
141
  d.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:2147483647;background:#0F6E56;color:#fff;padding:11px 18px;font:14px/1.6 system-ui,sans-serif;text-align:center;box-shadow:0 1px 4px rgba(0,0,0,.2)'
143
- d.textContent = '【一模路通】请在此窗口登录账号(知乎扫码最快)。登录成功后令牌会自动保存到桌面端并注册 Host 设备,窗口随即关闭;令牌不落盘、不打印。'
142
+ d.textContent = '【一模路通】请在此窗口登录账号。登录成功后令牌会自动保存到本地服务并注册 Host 设备,窗口随即关闭;令牌不落盘、不打印。'
144
143
  document.documentElement.appendChild(d)
145
144
  }
146
145
  cleanText()
@@ -186,7 +185,7 @@ const LOADING_PAGE = 'data:text/html;charset=utf-8,' + encodeURIComponent(
186
185
  + '<div>加载中…</div></body></html>'
187
186
  )
188
187
 
189
- /** 失败/超时提示(Electron 与 Playwright 两条登录路径共用):
188
+ /** 失败/超时提示(Electron 登录路径用;Web 端改在新标签页登录,不注入站点页面):
190
189
  * 遮罩不存在时先补一个,再追加错误信息与「返回重试」按钮;点击后回登录首页重新开始。 */
191
190
  const noticeScript = (origin, text) => `(() => {
192
191
  if (!document.documentElement) return
@@ -292,6 +291,7 @@ const state = {
292
291
  finishedAt: 0,
293
292
  message: '',
294
293
  session: null,
294
+ origin: DEFAULT_ORIGIN,
295
295
  }
296
296
 
297
297
  export function relayLoginState() {
@@ -302,24 +302,12 @@ export function relayLoginState() {
302
302
  finishedAt: state.finishedAt,
303
303
  message: state.message,
304
304
  elapsedMs: state.startedAt ? Date.now() - state.startedAt : 0,
305
+ /** 'popup'(Electron 弹窗自动捕获)| 'web'(新标签页登录 + 手动粘贴令牌) */
306
+ mode: LOGIN_MODE,
307
+ loginUrl: `${state.origin}/app/`,
305
308
  }
306
309
  }
307
310
 
308
- /** 找到系统浏览器可执行文件;找不到时让 playwright 用 channel 兜底。 */
309
- function resolveBrowserPath() {
310
- const candidates = [
311
- process.env.OMR_CHROME_PATH,
312
- 'C:/Program Files/Google/Chrome/Application/chrome.exe',
313
- 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
314
- 'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
315
- 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
316
- '/usr/bin/google-chrome',
317
- '/usr/bin/chromium',
318
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
319
- ].filter(Boolean)
320
- return candidates.find(p => existsSync(p)) || ''
321
- }
322
-
323
311
  /** Electron:独立 partition 的 BrowserWindow,webRequest 抓 Authorization。 */
324
312
  async function openElectronSession(origin, onToken, log = () => {}) {
325
313
  const electron = await import('electron')
@@ -465,113 +453,24 @@ async function openElectronSession(origin, onToken, log = () => {}) {
465
453
  }
466
454
  }
467
455
 
468
- /** 纯 Node 回退:playwright-core + 系统 Chrome/Edge(行为与 Electron 路径对齐)。 */
469
- async function openPlaywrightSession(origin, onToken, log = () => {}) {
470
- const { chromium } = await import('playwright-core')
471
- const executablePath = resolveBrowserPath()
472
- const browser = await chromium.launch({
473
- ...(executablePath ? { executablePath } : { channel: 'chrome' }),
474
- headless: process.env.OMR_RELAY_LOGIN_HEADLESS === '1',
475
- args: ['--no-first-run', '--no-default-browser-check', '--disable-features=Translate'],
476
- })
477
- const context = await browser.newContext({ viewport: { width: 1120, height: 860 } })
478
- // 与 Electron 一致:每个文档首帧前盖遮罩,注入脚本改完 DOM 再撤掉
479
- if (VEIL_SCRIPT) await context.addInitScript(VEIL_SCRIPT)
480
- const page = await context.newPage()
481
-
482
- const showNotice = text => {
483
- // 提示 evaluate 可能撞上导航导致上下文销毁:轮询重试直到提示真正落上页面
484
- let tries = 0
485
- const attempt = async () => {
486
- if (page.isClosed()) return
487
- try {
488
- await page.evaluate(noticeScript(origin, text))
489
- if (await page.evaluate(`!!document.getElementById('omr-login-timeout')`)) return
490
- } catch { /* 导航中,稍后重试 */ }
491
- if (++tries < 12) setTimeout(attempt, 400)
492
- }
493
- void attempt()
494
- }
495
- const showSpinner = () => void page.evaluate(SPINNER_SCRIPT).catch(() => {})
496
-
497
- // 主框架导航失败:立即显示失败提示(ERR_ABORTED 是导航被替换,不算失败)
498
- // 注意:主框架判定用 parentFrame()(主框架无父框架);事件帧与 page.mainFrame() 不是同一对象实例,=== 会失效
499
- let lastFailed = false
500
- let timeoutId = 0
501
- const armTimeout = () => {
502
- clearTimeout(timeoutId)
503
- timeoutId = setTimeout(() => showNotice('登录页面打开超时(超过 60 秒),请检查网络或稍后重试。'), 60_000)
504
- }
505
- page.on('requestfailed', req => {
506
- try {
507
- if (req.resourceType() === 'document' && req.isNavigationRequest() && !req.frame().parentFrame()) {
508
- const err = req.failure()?.errorText || 'FAILED'
509
- if (/ABORTED/i.test(err)) return
510
- lastFailed = true
511
- clearTimeout(timeoutId)
512
- log(`登录页主框架加载失败:${err}`)
513
- showNotice(`登录页面打开失败(${err.replace(/^net::/, '')}),请检查网络后点「返回重试」。`)
514
- }
515
- } catch { /* 单个请求异常不影响令牌捕获 */ }
516
- })
517
- page.on('request', req => {
518
- try {
519
- // 主框架导航请求发出:旧页面立即盖「加载中」遮罩(点击渠道跳转也有即时反馈),并重置超时
520
- if (req.resourceType() === 'document' && req.isNavigationRequest() && !req.frame().parentFrame()) {
521
- lastFailed = false
522
- showSpinner()
523
- armTimeout()
524
- }
525
- } catch { /* 忽略 */ }
526
- const token = pickBearer(req.headers()['authorization'] || '')
527
- if (token) onToken(token)
528
- })
529
- page.on('domcontentloaded', async () => {
530
- // 页面级事件:仅主文档触发,无需框架过滤
531
- clearTimeout(timeoutId)
532
- await page.evaluate(BANNER_SCRIPT).catch(e => log(`横幅注入失败:${e?.message ?? e}`))
533
- })
534
- page.on('response', res => {
535
- if (res.status() < 200 || res.status() >= 300 || !res.url().startsWith(origin) || !res.url().includes('/api/')) return
536
- void res.json().then(data => {
537
- const token = pickToken(data)
538
- if (token) onToken(token)
539
- }).catch(() => {})
540
- })
541
-
542
- // 先加载本地加载页(离线秒开):浏览器窗口打开时立即有「加载中」内容,不露出空白
543
- try { await page.goto(LOADING_PAGE, { waitUntil: 'load', timeout: 10_000 }) } catch { /* data 页失败也继续 */ }
544
- await page.evaluate(BANNER_SCRIPT).catch(() => {})
545
- try { await page.goto(`${origin}/app/`, { waitUntil: 'domcontentloaded', timeout: 30_000 }) } catch { /* 页面慢不影响捕获 */ }
546
- await page.evaluate(BANNER_SCRIPT).catch(() => {})
547
-
548
- return {
549
- async poll() {
550
- if (page.isClosed()) return null
551
- try {
552
- const text = await page.evaluate(STORAGE_SCAN_SCRIPT)
553
- return pickTokenFromStorage(JSON.parse(text || '[]'))
554
- } catch { return null }
555
- },
556
- isClosed: () => page.isClosed(),
557
- async close() {
558
- clearTimeout(timeoutId)
559
- await browser.close().catch(() => {})
560
- },
561
- }
562
- }
563
-
564
456
  /**
565
457
  * 启动一次登录(幂等:已有进行中的会话直接返回状态)。
566
458
  * @param {object} options
567
459
  * @param {string} options.apiOrigin 控制面根地址
568
460
  * @param {Function} options.onToken async (siteToken) => void —— 由调用方保存,切勿打印
569
461
  * @param {Function} options.log 日志(不得输出 token)
462
+ * @param {Function} [options.openSession] 测试注入:自定义登录会话(不传则按运行环境选择)
570
463
  */
571
- export async function startRelayLogin({ apiOrigin = DEFAULT_ORIGIN, onToken, log = () => {} } = {}) {
464
+ export async function startRelayLogin({ apiOrigin = DEFAULT_ORIGIN, onToken, log = () => {}, openSession } = {}) {
572
465
  if (state.status === 'waiting') return { started: false, ...relayLoginState() }
573
466
  if (typeof onToken !== 'function') throw new Error('startRelayLogin 需要 onToken 回调')
574
467
  const origin = String(apiOrigin || DEFAULT_ORIGIN).replace(/\/+$/, '')
468
+ state.origin = origin
469
+
470
+ // Web 端(纯 Node)不拉本机浏览器:跨域读不到站点登录态,改由管理页在新标签页
471
+ // 打开站点登录页、用户粘贴令牌(见文件头注释)。返回 loginUrl 供前端打开。
472
+ const opener = openSession ?? (LOGIN_MODE === 'popup' ? openElectronSession : null)
473
+ if (!opener) return { started: false, ...relayLoginState() }
575
474
 
576
475
  state.status = 'waiting'
577
476
  state.startedAt = Date.now()
@@ -585,10 +484,9 @@ export async function startRelayLogin({ apiOrigin = DEFAULT_ORIGIN, onToken, log
585
484
  }
586
485
 
587
486
  try {
588
- const opener = process.versions?.electron ? openElectronSession : openPlaywrightSession
589
487
  state.session = await opener(origin, capture, log)
590
488
  state.message = '登录窗口已打开:请在窗口中完成登录(知乎扫码最快),成功后自动保存令牌'
591
- log(`站点登录窗口已打开(${process.versions?.electron ? 'Electron' : 'Playwright'})`)
489
+ log('站点登录窗口已打开(Electron)')
592
490
  } catch (error) {
593
491
  state.status = 'failed'
594
492
  state.finishedAt = Date.now()
@@ -55,6 +55,8 @@ function groupsSummary() {
55
55
  enabled: g.enabled !== false,
56
56
  models: Array.isArray(g.models) ? g.models : [],
57
57
  disabled: Array.isArray(g.disabled) ? g.disabled : [],
58
+ // 内置默认组(omr/default):成员由小时扫描维护,手机端只读展示
59
+ builtin: g.builtin === true,
58
60
  }))
59
61
  }
60
62