Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 端点清单拉不到时给离线出口并补网络诊断 (#874)
Dash8c3ec6cda565
diff --git a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts b/apps/desktop/src/main/__tests__/clientEndpointsService.test.tsindex 62aaa8496b..5e8c2f00ce 100644--- a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts+++ b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts@@ -5,13 +5,17 @@* 这里只测 desktop 宿主层:清单来源解析(resolveEndpointSource 表驱动)、* 阻断式重试循环(失败 → prompt → 重试/退出,无静默降级、无烘焙合并)、* 弹框前的网络层自动重试(mac 首装瞬时失败自愈;配置事故不消耗预算)、- * 失败 reason 带错误码、+ * 失败 reason 带错误码、失败分类(network / config)、+ * 弹框前的分阶段诊断调用时机、+ * **用户显式确认的离线出口**(仅网络层失败给,配置事故绝不给)、* file 模式的 allowHttp 放行、init 前 getter 抛错(启动时序守卫)、sendSync IPC 形状。*/+import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import { EventEmitter } from 'node:events';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { TEST_CLIENT_ENDPOINTS } from '../../test/vitest/clientEndpointsFixture';@@ -27,18 +31,28 @@ vi.mock('electron', () => ({dialog: { showMessageBoxSync: vi.fn() },ipcMain: { on: ipcOn },net: { request: netRequest },+ // netLog 是静态 import(architecture-invariants.md §2);captureEndpointNetLog 这条+ // 路径由 captureNetLogAround 的注入式用例覆盖,这里只需让模块能加载。+ netLog: { startLogging: vi.fn(async () => {}), stopLogging: vi.fn(async () => {}) },+ session: { defaultSession: { resolveProxy: vi.fn(async () => 'DIRECT') } },}));vi.mock('../logger', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+ getLogDir: () => '/tmp/cindy-test-logs',}));import {activateClientEndpointRealm,+ captureNetLogAround,+ prepareEndpointNetLogFile,+ verifyEndpointNetLogCapture,+ classifyManifestFailure,getClientEndpoint,getClientEndpointForRealm,getResolvedClientEndpoints,loadClientEndpointsForRealm,+ isUsingCachedClientEndpoints,registerClientEndpointsIpc,resetClientEndpointRealm,resetClientEndpointsForTest,@@ -46,6 +60,7 @@ import {resolveEndpointSource,CLIENT_ENDPOINTS_SYNC_CHANNEL,type BlockingResolveDeps,+ type ManifestPromptContext,} from '../clientEndpointsService';afterEach(() => {@@ -141,6 +156,10 @@ const NO_AUTO_RETRY = { autoRetryDelaysMs: [] as readonly number[] };const okFetch = (text: string) => async () => ({ ok: true as const, text });const failFetch = (detail: string) => async () => ({ ok: false as const, detail });+/** promptRetry 现在收整个上下文对象;断言只钉住 reason 与失败分类。 */+const promptedWith = (reason: string, kind: 'network' | 'config' = 'network') =>+ expect.objectContaining({ reason, kind });+function mockNetManifest(text: string): void {const request = new EventEmitter() as EventEmitter & {abort: ReturnType<typeof vi.fn>;@@ -185,7 +204,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'...NO_AUTO_RETRY,});expect(mismatch).toBeNull();- expect(promptRetry).toHaveBeenCalledWith('region-mismatch:cn:global');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('region-mismatch:cn:global', 'config'));await expect(resolveClientEndpointsBlocking({@@ -213,7 +232,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'...NO_AUTO_RETRY,});expect(promptRetry).toHaveBeenCalledTimes(1);- expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ERR_CONNECTION_REFUSED');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed:ERR_CONNECTION_REFUSED'));expect(fetchManifest).toHaveBeenCalledTimes(2);expect(result?.authApiBaseUrl).toBe('https://auth.remote.example.com');expect(exitApp).not.toHaveBeenCalled();@@ -250,7 +269,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'...NO_AUTO_RETRY,});expect(result).toBeNull();- expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ERR_NAME_NOT_RESOLVED');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed:ERR_NAME_NOT_RESOLVED'));expect(exitApp).toHaveBeenCalledTimes(1);});@@ -262,7 +281,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'exitApp: vi.fn(),...NO_AUTO_RETRY,});- expect(promptRetry).toHaveBeenCalledWith('fetch-failed');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed'));});it('localhost http 清单:默认拒绝(CDN 路径零放松),allowHttp(file 模式)放行', async () => {@@ -292,7 +311,7 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'...NO_AUTO_RETRY,});expect(result).toBeNull();- expect(promptRetry).toHaveBeenCalledWith('fetch-failed:ENOENT');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed:ENOENT'));});});@@ -339,7 +358,7 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试expect(promptRetry).toHaveBeenCalledTimes(1);- expect(promptRetry).toHaveBeenCalledWith('fetch-failed:timeout-15000ms');+ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed:timeout-15000ms'));expect(result).toBeNull();expect(exitApp).toHaveBeenCalledTimes(1);});@@ -395,7 +414,8 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {expect(fetchManifest).toHaveBeenCalledTimes(1);expect(sleep).not.toHaveBeenCalled();expect(promptRetry).toHaveBeenCalledTimes(1);- expect(promptRetry.mock.calls[0][0]).not.toMatch(/^fetch-failed/);+ expect(promptRetry.mock.calls[0][0].reason).not.toMatch(/^fetch-failed/);+ expect(promptRetry.mock.calls[0][0].kind).toBe('config');expect(result).toBeNull();});@@ -443,6 +463,25 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {expect(result).toBeNull();});+ it.each([407, 408, 425, 429])('非配置错 HTTP %d 仍消耗重试预算(与分类共用同一判定)', async (status) => {+ const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({+ ok: false,+ detail: `http-${status}`,+ });+ const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);++ await resolveClientEndpointsBlocking({+ fetchManifest,+ promptRetry: vi.fn().mockReturnValue('exit'),+ exitApp: vi.fn(),+ autoRetryDelaysMs: [10, 20],+ sleep,+ });++ expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试+ expect(sleep).toHaveBeenCalledTimes(2);+ });+it('HTTP 502(瞬时服务端错误)仍消耗重试预算', async () => {const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({ok: false,@@ -466,7 +505,735 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {});});+describe('失败分类与弹框前诊断', () => {+ it.each([+ ['fetch-failed', 'network'],+ ['fetch-failed:ERR_FAILED', 'network'],+ ['fetch-failed:timeout-15000ms', 'network'],+ // 5xx 可能是瞬时故障:重试循环会重试,这里也给离线出口。+ ['fetch-failed:http-500', 'network'],+ ['fetch-failed:http-502', 'network'],+ // 瞬时 4xx:限流 / 请求超时过一会儿就好,不能当配置事故——那会让一个正被限流的+ // 用户既不能重试、又用不上手里那份可用缓存。+ ['fetch-failed:http-408', 'network'],+ ['fetch-failed:http-425', 'network'],+ ['fetch-failed:http-429', 'network'],+ // 407 按 RFC 9110 §15.5.8 只可能来自代理,描述的是本机网络环境(代理凭据缺失/+ // 过期)而不是清单部署错;公司代理没登录恰恰是离线出口最该生效的场景。+ ['fetch-failed:http-407', 'network'],+ // 永久性 HTTP = 路径 / 权限 / 部署配置错。重试循环已因此不重试,分类必须一致,+ // 否则同一失败会"配置错所以不重试"又"网络问题所以能用缓存绕过"。+ ['fetch-failed:http-301', 'config'],+ ['fetch-failed:http-403', 'config'],+ ['fetch-failed:http-404', 'config'],+ ['fetch-failed:http-451', 'config'],+ ['fetch-failed:missing-manifest-base-url', 'config'],+ ['invalid-json', 'config'],+ ['unsupported-schema-version:9', 'config'],+ ['invalid-protocol:cdnBaseUrl', 'config'],+ ['region-mismatch:cn:global', 'config'],+ ] as const)('%s → %s', (reason, kind) => {+ expect(classifyManifestFailure(reason)).toBe(kind);+ });++ it('网络失败时诊断摘要与日志路径进 prompt 上下文', async () => {+ const diagnose = vi.fn().mockResolvedValue({+ summary: 'proxy=DIRECT dns=ok(1.2.3.4) tcp=ok(9ms)',+ logPath: '/tmp/cindy-test-logs/endpoint-netlog.json',+ });+ const promptRetry = vi.fn().mockReturnValue('exit');++ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry,+ exitApp: vi.fn(),+ diagnose,+ ...NO_AUTO_RETRY,+ });++ // 一轮只诊断一次(自动重试期间不诊断,别把弹框前的等待翻倍)。+ expect(diagnose).toHaveBeenCalledTimes(1);+ expect(promptRetry.mock.calls[0][0]).toMatchObject({+ kind: 'network',+ diagnosis: 'proxy=DIRECT dns=ok(1.2.3.4) tcp=ok(9ms)',+ logPath: '/tmp/cindy-test-logs/endpoint-netlog.json',+ });+ });++ it('配置事故不跑诊断(探网络没有信息量)', async () => {+ const diagnose = vi.fn();+ const promptRetry = vi.fn().mockReturnValue('exit');++ await resolveClientEndpointsBlocking({+ fetchManifest: okFetch('not json'),+ promptRetry,+ exitApp: vi.fn(),+ diagnose,+ });++ expect(diagnose).not.toHaveBeenCalled();+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ diagnosis: null, logPath: null });+ });++ it('烘焙基址缺失不跑诊断(空 URL 探不出东西)', async () => {+ const diagnose = vi.fn();+ const promptRetry = vi.fn().mockReturnValue('exit');++ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('missing-manifest-base-url'),+ promptRetry,+ exitApp: vi.fn(),+ diagnose,+ });++ expect(diagnose).not.toHaveBeenCalled();+ });++ it('file 模式覆写分类:本地读不到不该让人去检查网络', async () => {+ const promptRetry = vi.fn().mockReturnValue('exit');+ const diagnose = vi.fn();+ const loadOfflineManifest = vi.fn();++ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ENOENT'),+ promptRetry,+ exitApp: vi.fn(),+ allowHttp: true,+ classifyFailure: () => 'config',+ diagnose,+ loadOfflineManifest,+ ...NO_AUTO_RETRY,+ });++ expect(promptRetry).toHaveBeenCalledWith(promptedWith('fetch-failed:ENOENT', 'config'));+ expect(diagnose).not.toHaveBeenCalled();+ expect(loadOfflineManifest).not.toHaveBeenCalled();+ });++ it('诊断永不返回时按兜底 deadline 放弃,阻断框照样弹出', async () => {+ const promptRetry = vi.fn().mockReturnValue('exit');+ const exitApp = vi.fn();+ const startedAt = Date.now();++ const result = await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry,+ exitApp,+ // diagnose 是注入点:实现方忘了设超时不能让启动永久停在这里。+ diagnose: () => new Promise(() => {}),+ diagnosisBudgetMs: 30,+ ...NO_AUTO_RETRY,+ });++ expect(Date.now() - startedAt).toBeLessThan(2_000);+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ diagnosis: null, logPath: null });+ expect(result).toBeNull();+ expect(exitApp).toHaveBeenCalledTimes(1);+ });++ it('诊断自身抛错不影响阻断流程', async () => {+ const promptRetry = vi.fn().mockReturnValue('exit');+ const exitApp = vi.fn();++ const result = await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry,+ exitApp,+ diagnose: async () => {+ throw new Error('probe blew up');+ },+ ...NO_AUTO_RETRY,+ });++ expect(result).toBeNull();+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ diagnosis: null });+ expect(exitApp).toHaveBeenCalledTimes(1);+ });+});++describe('用户确认的离线出口', () => {+ const offlineCandidate = () => ({+ parsed: {+ ok: true as const,+ endpoints: { ...TEST_CLIENT_ENDPOINTS, authApiBaseUrl: 'https://auth.cached.example.com' },+ reviewVersion: null,+ region: null,+ },+ savedAt: '2026/7/29 06:22',+ });++ it('网络失败 + 有缓存 + 用户点离线 → 用缓存端点启动', async () => {+ const loadOfflineManifest = vi.fn(offlineCandidate);+ const fetchManifest = vi+ .fn<BlockingResolveDeps['fetchManifest']>()+ .mockResolvedValue({ ok: false, detail: 'ERR_FAILED' });+ const promptRetry = vi.fn().mockReturnValue('offline');+ const exitApp = vi.fn();++ const result = await resolveClientEndpointsBlocking({+ fetchManifest,+ promptRetry,+ exitApp,+ loadOfflineManifest,+ ...NO_AUTO_RETRY,+ });++ expect(result?.authApiBaseUrl).toBe('https://auth.cached.example.com');+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ offlineSavedAt: '2026/7/29 06:22' });+ expect(exitApp).not.toHaveBeenCalled();+ // 只尝试了一次网络:离线是出口而不是"再试一次"。+ expect(fetchManifest).toHaveBeenCalledTimes(1);+ });++ it('走离线出口时 onResolved 收到 source=cache;网络成功则是 network 并带原文', async () => {+ const cacheResolved = vi.fn();+ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry: () => 'offline',+ exitApp: vi.fn(),+ loadOfflineManifest: offlineCandidate,+ onResolved: cacheResolved,+ ...NO_AUTO_RETRY,+ });+ expect(cacheResolved).toHaveBeenCalledWith(expect.anything(), 'cache');++ const netResolved = vi.fn();+ await resolveClientEndpointsBlocking({+ fetchManifest: okFetch(FULL_MANIFEST),+ promptRetry: vi.fn(),+ exitApp: vi.fn(),+ loadOfflineManifest: offlineCandidate,+ onResolved: netResolved,+ });+ // 第三个参数必须是**校验通过的原文本身**:宿主要拿它原样落缓存,不能重新序列化+ // (重新序列化会抹掉本构建还不认识的新字段,升级后离线启动就丢配置)。+ expect(netResolved).toHaveBeenCalledWith(expect.anything(), 'network', FULL_MANIFEST);+ });++ it('清单带本构建未知字段时,原文照样原样交给宿主落缓存', async () => {+ const withUnknownField = JSON.stringify({+ ...(JSON.parse(FULL_MANIFEST) as object),+ // 前向兼容的发布模型:先上新字段的清单,再发认识它的客户端。+ futureApiBaseUrl: 'https://future.remote.example.com',+ });+ const onResolved = vi.fn();++ await resolveClientEndpointsBlocking({+ fetchManifest: okFetch(withUnknownField),+ promptRetry: vi.fn(),+ exitApp: vi.fn(),+ onResolved,+ });++ expect(onResolved.mock.calls[0][2]).toBe(withUnknownField);+ expect(onResolved.mock.calls[0][2]).toContain('futureApiBaseUrl');+ });++ it.each([301, 403, 404])(+ '永久性 HTTP %d 不给离线出口(与"不重试"的判定保持一致)',+ async (status) => {+ const loadOfflineManifest = vi.fn(offlineCandidate);+ const diagnose = vi.fn();+ const promptRetry = vi.fn().mockReturnValue('exit');++ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch(`http-${status}`),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest,+ diagnose,+ });++ expect(loadOfflineManifest).not.toHaveBeenCalled();+ expect(diagnose).not.toHaveBeenCalled();+ expect(promptRetry.mock.calls[0][0]).toMatchObject({+ kind: 'config',+ offlineSavedAt: null,+ });+ },+ );++ it.each([407, 408, 429])('非配置错 HTTP %d 仍给离线出口(代理没登录/被限流不该连缓存都用不上)', async (status) => {+ const promptRetry = vi.fn().mockReturnValue('offline');++ const result = await resolveClientEndpointsBlocking({+ fetchManifest: failFetch(`http-${status}`),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest: offlineCandidate,+ ...NO_AUTO_RETRY,+ });++ expect(result?.authApiBaseUrl).toBe('https://auth.cached.example.com');+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ kind: 'network' });+ });++ it('HTTP 502(瞬时)仍给离线出口', async () => {+ const loadOfflineManifest = vi.fn(offlineCandidate);+ const promptRetry = vi.fn().mockReturnValue('offline');++ const result = await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('http-502'),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest,+ ...NO_AUTO_RETRY,+ });++ expect(result?.authApiBaseUrl).toBe('https://auth.cached.example.com');+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ kind: 'network' });+ });++ it('配置事故绝不给离线出口:既不读缓存也不点亮按钮', async () => {+ const loadOfflineManifest = vi.fn(offlineCandidate);+ const promptRetry = vi.fn().mockReturnValue('exit');++ await resolveClientEndpointsBlocking({+ fetchManifest: okFetch('not json'),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest,+ });++ expect(loadOfflineManifest).not.toHaveBeenCalled();+ expect(promptRetry.mock.calls[0][0]).toMatchObject({+ kind: 'config',+ offlineSavedAt: null,+ });+ });++ it('没有可用缓存时 offlineSavedAt 为 null(弹框不出离线按钮)', async () => {+ const promptRetry = vi.fn().mockReturnValue('exit');+ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest: () => null,+ ...NO_AUTO_RETRY,+ });+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ offlineSavedAt: null });+ });++ it('读缓存抛错只降级为"没有缓存"', async () => {+ const promptRetry = vi.fn().mockReturnValue('exit');+ const result = await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest: () => {+ throw new Error('disk on fire');+ },+ ...NO_AUTO_RETRY,+ });+ expect(result).toBeNull();+ expect(promptRetry.mock.calls[0][0]).toMatchObject({ offlineSavedAt: null });+ });++ it('选了离线但缓存这一瞬失效 → 回到下一轮尝试,不静默继续', async () => {+ const fetchManifest = vi+ .fn<BlockingResolveDeps['fetchManifest']>()+ .mockResolvedValueOnce({ ok: false, detail: 'ERR_FAILED' })+ .mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });+ // 第一轮报告有缓存,用户点离线时缓存已经不可用(被清理 / 校验不过)。+ const loadOfflineManifest = vi+ .fn<NonNullable<BlockingResolveDeps['loadOfflineManifest']>>()+ .mockReturnValueOnce(null);+ const promptRetry = vi+ .fn<(context: ManifestPromptContext) => 'retry' | 'offline' | 'exit'>()+ .mockReturnValue('offline');++ const result = await resolveClientEndpointsBlocking({+ fetchManifest,+ promptRetry,+ exitApp: vi.fn(),+ loadOfflineManifest,+ ...NO_AUTO_RETRY,+ });++ expect(result?.authApiBaseUrl).toBe('https://auth.remote.example.com');+ expect(fetchManifest).toHaveBeenCalledTimes(2);+ });++ it('自动重试期间不问缓存(只在真要弹框时读一次盘)', async () => {+ const loadOfflineManifest = vi.fn(offlineCandidate);+ await resolveClientEndpointsBlocking({+ fetchManifest: failFetch('ERR_FAILED'),+ promptRetry: () => 'exit',+ exitApp: vi.fn(),+ loadOfflineManifest,+ autoRetryDelaysMs: [1, 2],+ sleep: async () => {},+ });+ expect(loadOfflineManifest).toHaveBeenCalledTimes(1);+ });+});++describe('netlog 抓取(captureNetLogAround)', () => {+ const deferred = () => {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ };++ it('正常路径:返回文件路径,start/stop 配对', async () => {+ const startLogging = vi.fn(async () => {});+ const stopLogging = vi.fn(async () => {});+ const run = vi.fn(async () => {});++ const file = await captureNetLogAround({ startLogging, stopLogging }, '/tmp/n.json', run, 50);++ expect(file).toBe('/tmp/n.json');+ expect(startLogging).toHaveBeenCalledWith('/tmp/n.json', { captureMode: 'default' });+ expect(run).toHaveBeenCalledTimes(1);+ expect(stopLogging).toHaveBeenCalledTimes(1);+ });++ it('录制期间的请求抛错也照样 stop,并仍返回路径', async () => {+ const stopLogging = vi.fn(async () => {});+ const file = await captureNetLogAround(+ { startLogging: async () => {}, stopLogging },+ '/tmp/n.json',+ async () => {+ throw new Error('fetch blew up');+ },+ 50,+ ).catch(() => 'threw');++ // runWhileRecording 的异常向上抛,但 finally 里的 stop 必须已经发出。+ expect(file).toBe('threw');+ expect(stopLogging).toHaveBeenCalledTimes(1);+ });++ it('stop 超时不会锁死收尾:迟到成功的 start 仍会再尝试停止', async () => {+ // 上一版一进 stopOnce 就把 stopped 置 true,于是 stop 超时后就再也不试了——+ // 而 withDeadline 取消不了 Electron 侧操作,没停下的进程级抓包会继续录流量。+ const gate = (() => {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+ })();+ let stopCalls = 0;+ const stopLogging = vi.fn(async () => {+ stopCalls += 1;+ if (stopCalls <= 2) return new Promise(() => {}); // 前两次(有界重试)都不 settle+ return undefined;+ });++ const file = await captureNetLogAround(+ { startLogging: () => gate.promise, stopLogging },+ "/tmp/n.json",+ async () => {},+ 10,+ );+ expect(file).toBeNull(); // start 超时,本次放弃 netlog++ gate.resolve(); // start 迟到成功 → 必须补一次 stop+ await new Promise((r) => setTimeout(r, 60));+ expect(stopCalls).toBeGreaterThanOrEqual(1);+ });++ it('stop 在预算内失败时有界重试(不无限试)', async () => {+ let calls = 0;+ const stopLogging = vi.fn(async () => {+ calls += 1;+ throw new Error('stop boom');+ });+ const file = await captureNetLogAround(+ { startLogging: async () => {}, stopLogging },+ "/tmp/n.json",+ async () => {},+ 20,+ );+ expect(file).toBe("/tmp/n.json");+ expect(calls).toBe(2); // NETLOG_STOP_ATTEMPTS+ });++ it('前台重试耗尽后由后台定时重试兜底,直到确认停止', async () => {+ // review 抓到:前台重试有界,耗尽后如果没有新的触发点,一次没停下的**进程级**抓包+ // 就会继续录启动后的全部流量、文件无界增长。后台重试不占启动路径,但保证有人收尾。+ vi.useFakeTimers();+ try {+ let calls = 0;+ const stopLogging = vi.fn(async () => {+ calls += 1;+ if (calls < 4) throw new Error('stop boom');+ return undefined;+ });++ const pending = captureNetLogAround(+ { startLogging: async () => {}, stopLogging },+ '/tmp/n.json',+ async () => {},+ 20,+ );+ await vi.advanceTimersByTimeAsync(0);+ expect(await pending).toBe('/tmp/n.json');+ expect(calls).toBe(2); // 前台预算就此用尽,启动流程不再多等++ await vi.advanceTimersByTimeAsync(5_000);+ expect(calls).toBe(3); // 后台第 1 次+ await vi.advanceTimersByTimeAsync(5_000);+ expect(calls).toBe(4); // 后台第 2 次成功+ await vi.advanceTimersByTimeAsync(120_000);+ expect(calls).toBe(4); // 停下之后不再排下一次+ } finally {+ vi.useRealTimers();+ }+ });++ it('后台重试不设次数上限:节奏放缓但一直盯到确认停止', async () => {+ // review 抓到:给后台重试设 12 次上限,等于"NetworkService 卡过一分钟再恢复"时+ // 抓包在无人收尾的状态下录满整个进程生命周期 —— 正是这条兜底要防的事。+ vi.useFakeTimers();+ try {+ let logging = true;+ const stopLogging = vi.fn(async () => {+ if (logging) throw new Error('stop boom');+ return undefined;+ });+ const netLogApi = {+ startLogging: async () => {},+ stopLogging,+ get currentlyLogging() {+ return logging;+ },+ };+ const pending = captureNetLogAround(netLogApi, '/tmp/n.json', async () => {}, 20);+ await vi.advanceTimersByTimeAsync(0);+ await pending;+ expect(stopLogging).toHaveBeenCalledTimes(2); // 前台预算++ // 快节奏 6 次 + 慢节奏 6 次都失败之后,仍然有下一个触发点。+ await vi.advanceTimersByTimeAsync(6 * 5_000 + 6 * 30_000);+ const afterFastPhase = stopLogging.mock.calls.length;+ expect(afterFastPhase).toBe(2 + 12);+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);+ expect(stopLogging.mock.calls.length).toBeGreaterThan(afterFastPhase);++ // NetworkService 恢复后:确认停止,循环收手。+ logging = false;+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);+ const settled = stopLogging.mock.calls.length;+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000);+ expect(stopLogging.mock.calls.length).toBe(settled);+ } finally {+ vi.useRealTimers();+ }+ });++ it('currentlyLogging=false 时不空转重试', async () => {+ const stopLogging = vi.fn(async () => {});+ const file = await captureNetLogAround(+ { startLogging: async () => {}, stopLogging, currentlyLogging: false },+ '/tmp/n.json',+ async () => {},+ 20,+ );+ expect(file).toBe('/tmp/n.json');+ expect(stopLogging).not.toHaveBeenCalled();+ });++ it('stop 永不返回时不卡住,仍返回文件路径', async () => {+ const startedAt = Date.now();+ const file = await captureNetLogAround(+ { startLogging: async () => {}, stopLogging: () => new Promise(() => {}) },+ '/tmp/n.json',+ async () => {},+ 20,+ );+ expect(file).toBe('/tmp/n.json');+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ });++ it('start 迟到成功时补发 stop(否则进程级抓包无人收尾、文件无界增长)', async () => {+ const gate = deferred();+ const stopLogging = vi.fn(async () => {});+ const run = vi.fn(async () => {});++ const file = await captureNetLogAround(+ { startLogging: () => gate.promise, stopLogging },+ '/tmp/n.json',+ run,+ 10,+ );++ // 超时先到:本次诊断放弃 netlog。+ expect(file).toBeNull();+ expect(run).not.toHaveBeenCalled();+ expect(stopLogging).not.toHaveBeenCalled();++ // start 之后才成功 —— withDeadline 只解除等待,不取消 Electron 侧操作,+ // 所以这里必须补一次 stop,否则抓包会一直录后续所有应用流量。+ gate.resolve();+ await new Promise((r) => setImmediate(r));+ expect(stopLogging).toHaveBeenCalledTimes(1);+ });++ it('start 迟到失败时不补发 stop(没有 capture 需要关闭)', async () => {+ let reject!: (err: Error) => void;+ const startPromise = new Promise<void>((_r, rj) => {+ reject = rj;+ });+ const stopLogging = vi.fn(async () => {});++ const file = await captureNetLogAround(+ { startLogging: () => startPromise, stopLogging },+ '/tmp/n.json',+ async () => {},+ 10,+ );+ expect(file).toBeNull();++ reject(new Error('start failed late'));+ await new Promise((r) => setImmediate(r));+ expect(stopLogging).not.toHaveBeenCalled();+ });+});++describe('netlog 落盘路径(不得落到 cwd、不得用可预测名)', () => {+ let logDir: string;+ beforeEach(() => {+ logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-netlog-'));+ });+ afterEach(() => {+ fs.rmSync(logDir, { recursive: true, force: true });+ });++ it.each([+ ['null(logger 未初始化)', null],+ ['空串(initLogger 建目录失败时的实际取值)', ''],+ ['纯空白', ' '],+ ])('%s → null,调用方跳过抓取', (_label, dir) => {+ // path.join('', name) 会得到相对路径,落到 process.cwd()——dev 下正是仓库工作区,+ // 会在被 Git 跟踪的目录里留生成物。+ expect(prepareEndpointNetLogFile(dir)).toBeNull();+ });++ it('落在一个新建的私有子目录里(交接期路径不可被替换)', () => {+ const file = prepareEndpointNetLogFile(logDir)!.file;+ expect(file).not.toBeNull();+ expect(path.isAbsolute(file)).toBe(true);++ const captureDir = path.dirname(file);+ // 不是直接落在日志目录里,而是落在我们刚原子创建的随机名子目录里。+ expect(captureDir).not.toBe(logDir);+ expect(path.dirname(captureDir)).toBe(logDir);+ expect(path.basename(captureDir).startsWith('endpoint-netlog-')).toBe(true);+ expect(fs.lstatSync(captureDir).isDirectory()).toBe(true);+ // 文件本身刻意不预创建:交给 Chromium 在这个私有目录里建,+ // 所以不存在「独占创建后 close、Chromium 再按名字打开」那段可替换窗口。+ expect(fs.existsSync(file)).toBe(false);+ });++ it('私有目录仅属主可访问(POSIX)', () => {+ if (process.platform === 'win32') return; // Windows 权限模型不同,目录名随机仍有效+ const file = prepareEndpointNetLogFile(logDir)!.file;+ expect(fs.statSync(path.dirname(file)).mode & 0o777).toBe(0o700);+ });++ it('目录名不可预测,两次调用不同目录', () => {+ const a = prepareEndpointNetLogFile(logDir)!.file;+ const b = prepareEndpointNetLogFile(logDir)!.file;+ expect(path.dirname(a)).not.toBe(path.dirname(b));+ });++ it('每次准备前清掉本前缀旧产物(旧目录 + 两个历史版本的文件名)', () => {+ // 第一版固定名与第二版唯一名的残留都要被清掉,否则唯一名会无界堆积。+ fs.writeFileSync(path.join(logDir, 'endpoint-netlog.json'), 'v1', 'utf8');+ fs.writeFileSync(path.join(logDir, `endpoint-netlog.${process.pid}.abc123.json`), 'v2', 'utf8');+ const first = prepareEndpointNetLogFile(logDir)!.file;+ const second = prepareEndpointNetLogFile(logDir)!.file;++ const left = fs.readdirSync(logDir).filter((n) => n.startsWith('endpoint-netlog'));+ expect(left).toEqual([path.basename(path.dirname(second))]);+ expect(fs.existsSync(path.dirname(first))).toBe(false);+ });++ it('目录不存在时返回 null,不抛错', () => {+ expect(prepareEndpointNetLogFile(path.join(logDir, 'missing'))).toBeNull();+ });++ it('日志目录 group/other 可写时跳过抓取(别的用户能抢目录项)', () => {+ // 0700 子目录只保护内容,保护不了它在父目录里的目录项:父目录对别人可写,+ // 别的用户就能把它 rename 掉、换上 symlink,把 Chromium 引到别处。+ if (process.platform === 'win32') return; // Windows 用 ACL,mode 位判断无意义+ fs.chmodSync(logDir, 0o777);+ expect(prepareEndpointNetLogFile(logDir)).toBeNull();+ fs.chmodSync(logDir, 0o700);+ expect(prepareEndpointNetLogFile(logDir)).not.toBeNull();+ });++ it('日志"目录"其实是文件时跳过抓取', () => {+ const asFile = path.join(logDir, 'not-a-dir');+ fs.writeFileSync(asFile, 'x', 'utf8');+ expect(prepareEndpointNetLogFile(asFile)).toBeNull();+ });+});++describe('netlog 产物事后核对(verifyEndpointNetLogCapture)', () => {+ let logDir: string;+ beforeEach(() => {+ logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-netlog-verify-'));+ });+ afterEach(() => {+ fs.rmSync(logDir, { recursive: true, force: true });+ });++ it('目录项没被换过、目标是常规文件 → 通过', () => {+ const capture = prepareEndpointNetLogFile(logDir)!;+ fs.writeFileSync(capture.file, '{}', 'utf8'); // 模拟 Chromium 写出的产物+ expect(verifyEndpointNetLogCapture(capture)).toBe(true);+ });++ it('目录项被换成 symlink → 不通过(产物丢弃)', () => {+ // 这是攻击的真实形状:把我们创建的目录项换成指向别处的 symlink,好让 Chromium+ // 写到别的地方去。lstat 不跟随 symlink,所以 isDirectory() 为 false。+ if (process.platform === 'win32') return;+ const capture = prepareEndpointNetLogFile(logDir)!;+ const captureDir = path.dirname(capture.file);+ const elsewhere = fs.mkdtempSync(path.join(logDir, 'elsewhere-'));+ fs.rmSync(captureDir, { recursive: true, force: true });+ fs.symlinkSync(elsewhere, captureDir);+ fs.writeFileSync(capture.file, '{}', 'utf8');+ expect(verifyEndpointNetLogCapture(capture)).toBe(false);+ });++ it('目录项换成了别的 inode → 不通过', () => {+ // 用改过的 dirIno 直接表达"目录项已经不是我们创建的那个 inode"。+ // 不通过 rm + mkdir 复现:那样在 ext4 上常常**复用同一个 inode 号**,断言会随文件+ // 系统摇摆(CI 上就是这么红的)。inode 号复用也正是这道核对的已知局限:+ // 它能抓住 symlink / 类型变化,抓不住"号被回收后重建"。+ const capture = prepareEndpointNetLogFile(logDir)!;+ fs.writeFileSync(capture.file, '{}', 'utf8');+ expect(verifyEndpointNetLogCapture({ ...capture, dirIno: capture.dirIno + 1 })).toBe(false);+ expect(verifyEndpointNetLogCapture({ ...capture, dirDev: capture.dirDev + 1 })).toBe(false);+ });++ it('目标被换成 symlink → 不通过', () => {+ if (process.platform === 'win32') return;+ const capture = prepareEndpointNetLogFile(logDir)!;+ const real = path.join(logDir, 'elsewhere.json');+ fs.writeFileSync(real, '{}', 'utf8');+ fs.symlinkSync(real, capture.file);+ expect(verifyEndpointNetLogCapture(capture)).toBe(false);+ });++ it('产物根本不存在 → 不通过', () => {+ const capture = prepareEndpointNetLogFile(logDir)!;+ expect(verifyEndpointNetLogCapture(capture)).toBe(false);+ });+});+describe('getter / IPC', () => {+ it('默认不是离线缓存启动', () => {+ expect(isUsingCachedClientEndpoints()).toBe(false);+ });++it('init 之前 getClientEndpoint / getResolvedClientEndpoints 直接抛错(启动时序守卫)', () => {expect(() => getClientEndpoint('authApiBaseUrl')).toThrow(/not initialized/);expect(() => getResolvedClientEndpoints()).toThrow(/not initialized/);diff --git a/apps/desktop/src/main/__tests__/endpointFetchDiagnostics.test.ts b/apps/desktop/src/main/__tests__/endpointFetchDiagnostics.test.tsnew file mode 100644index 0000000000..233124f088--- /dev/null+++ b/apps/desktop/src/main/__tests__/endpointFetchDiagnostics.test.ts@@ -0,0 +1,166 @@+/**+ * 分阶段网络诊断的探针编排与摘要格式。+ *+ * 三个探针全部注入(不起 Electron、不碰真实网络),重点验证:+ * - 任一探针失败不影响其它两段(否则最有价值的组合——「DNS/TCP 都通,Chromium 仍+ * 报 ERR_FAILED」——就永远拿不到);+ * - 摘要是一行、可直接进日志与弹框。+ */+import { describe, expect, it, vi } from 'vitest';++// createDefaultProbes 静态 import electron(architecture-invariants.md §2 禁止 main+// 运行时动态 import);本文件只测注入探针的编排,mock 到能加载模块即可。+vi.mock('electron', () => ({+ session: { defaultSession: { resolveProxy: vi.fn(async () => 'DIRECT') } },+}));++import {+ formatEndpointFetchDiagnosis,+ probeEndpointFetch,+ type EndpointFetchProbes,+} from '../endpointFetchDiagnostics';++const URL_UNDER_TEST = 'https://hotfix.example.com/cindy/endpoint.json?t=1';++function probes(overrides: Partial<EndpointFetchProbes> = {}): EndpointFetchProbes {+ return {+ resolveProxy: vi.fn(async () => 'DIRECT'),+ lookupHost: vi.fn(async () => ['203.0.113.7']),+ connectTcp: vi.fn(async () => {}),+ ...overrides,+ };+}++describe('probeEndpointFetch', () => {+ it('三段全通:摘要含代理决策、地址与耗时', async () => {+ const report = await probeEndpointFetch(URL_UNDER_TEST, probes());+ expect(report.proxy).toEqual({ ok: true, value: 'DIRECT' });+ expect(report.dns).toEqual({ ok: true, addresses: ['203.0.113.7'] });+ expect(report.tcp.ok).toBe(true);+ const summary = formatEndpointFetchDiagnosis(report);+ expect(summary).toContain('proxy=DIRECT');+ expect(summary).toContain('dns=ok(203.0.113.7)');+ expect(summary).toMatch(/tcp=ok\(\d+ms\)/);+ expect(summary.split('\n')).toHaveLength(1);+ });++ it('按 URL 解析出 host 与端口传给探针', async () => {+ const p = probes();+ await probeEndpointFetch('https://cdn.example.com:8443/endpoint.json', p);+ expect(p.lookupHost).toHaveBeenCalledWith('cdn.example.com');+ expect(p.connectTcp).toHaveBeenCalledWith('cdn.example.com', 8443, expect.any(Number));+ });++ it('http 无端口时探 80', async () => {+ const p = probes();+ await probeEndpointFetch('http://cdn.example.com/endpoint.json', p);+ expect(p.connectTcp).toHaveBeenCalledWith('cdn.example.com', 80, expect.any(Number));+ });++ it('DNS 失败不影响代理与 TCP 两段', async () => {+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes({+ lookupHost: async () => {+ const err = new Error('getaddrinfo ENOTFOUND') as NodeJS.ErrnoException;+ err.code = 'ENOTFOUND';+ throw err;+ },+ }),+ );+ expect(report.dns).toEqual({ ok: false, error: 'ENOTFOUND' });+ expect(report.proxy.ok).toBe(true);+ expect(report.tcp.ok).toBe(true);+ expect(formatEndpointFetchDiagnosis(report)).toContain('dns=fail(ENOTFOUND)');+ });++ it('代理解析失败单独记账,不整份放弃', async () => {+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes({+ resolveProxy: async () => {+ throw new Error('session unavailable');+ },+ }),+ );+ expect(report.proxy.ok).toBe(false);+ expect(report.dns.ok).toBe(true);+ expect(formatEndpointFetchDiagnosis(report)).toContain('proxy=fail(session unavailable)');+ });++ it('TCP 超时进摘要', async () => {+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes({+ connectTcp: async () => {+ throw new Error('ETIMEDOUT');+ },+ }),+ );+ expect(formatEndpointFetchDiagnosis(report)).toContain('tcp=fail(ETIMEDOUT)');+ });++ it('URL 非法时三段都记 invalid-url,不抛错', async () => {+ const p = probes();+ const report = await probeEndpointFetch('not a url', p);+ expect(report.proxy).toEqual({ ok: false, error: 'invalid-url' });+ expect(report.dns).toEqual({ ok: false, error: 'invalid-url' });+ expect(report.tcp).toEqual({ ok: false, error: 'invalid-url' });+ expect(p.lookupHost).not.toHaveBeenCalled();+ });++ it('代理返回空串归一为 unknown(不产出空摘要字段)', async () => {+ const report = await probeEndpointFetch(URL_UNDER_TEST, probes({ resolveProxy: async () => ' ' }));+ expect(formatEndpointFetchDiagnosis(report)).toContain('proxy=unknown');+ });++ it('DNS 返回多地址时摘要只留前两条', async () => {+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes({ lookupHost: async () => ['1.1.1.1', '2.2.2.2', '3.3.3.3'] }),+ );+ expect(formatEndpointFetchDiagnosis(report)).toContain('dns=ok(1.1.1.1,2.2.2.2)');+ });++ it('errno code 是数字时也不炸(诊断自己不能成为失败源)', async () => {+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes({+ lookupHost: async () => {+ const err = new Error('boom') as Error & { code: number };+ err.code = 12345;+ throw err;+ },+ }),+ );+ expect(report.dns).toEqual({ ok: false, error: '12345' });+ });++ describe('每段都必须受 deadline 约束', () => {+ /** 永不 settle 的 promise:模拟 PAC/代理解析或 OS DNS 查询挂住。 */+ const never = () => new Promise<never>(() => {});++ it.each([+ ['proxy', { resolveProxy: never }],+ ['dns', { lookupHost: never }],+ ['tcp', { connectTcp: never }],+ ] as const)('%s 永不返回时按 deadline 记失败,整轮仍然返回', async (stage, override) => {+ const startedAt = Date.now();+ const report = await probeEndpointFetch(+ URL_UNDER_TEST,+ probes(override as Partial<EndpointFetchProbes>),+ 30,+ );+ // 关键不是耗时精确,而是"会返回":这段跑在 app.ready 的阻断路径上,+ // 挂住就等于阻断框(连同离线出口)永远不出现,表现为启动卡死。+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ const outcome = report[stage];+ expect(outcome.ok).toBe(false);+ expect(outcome.ok === false && outcome.error).toBe(`${stage}-timeout-30ms`);+ // 其它两段照常出结果。+ for (const other of ['proxy', 'dns', 'tcp'] as const) {+ if (other !== stage) expect(report[other].ok).toBe(true);+ }+ });+ });+});diff --git a/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts b/apps/desktop/src/main/__tests__/endpointManifestCache.test.tsnew file mode 100644index 0000000000..c5e35c52a5--- /dev/null+++ b/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts@@ -0,0 +1,329 @@+/**+ * 端点清单离线缓存的读写与容错。+ *+ * 重点是「坏数据一律当没有缓存」:这份文件只用来点亮阻断框上的离线按钮,任何解析+ * 异常都必须降级为 null,绝不能反过来变成新的启动失败源。临时目录走 mkdtemp+ * (engineering-conventions §3.1),不碰真实 userData。+ */+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ CROSS_REGION_ENDPOINT_KEYS,+ ENDPOINT_MANIFEST_CACHE_FILE_NAME,+ REGION_ENDPOINT_DOMAIN,+ findBootstrapHostOutsideTrustedDomains,+ findUntrustedCachedEndpoint,+ formatCacheSavedAt,+ readEndpointManifestCache,+ writeEndpointManifestCache,+} from '../endpointManifestCache';++let dir: string;++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-endpoint-cache-'));+});++afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true });+});++const ENTRY = {+ savedAt: '2026-07-29T06:22:00.000Z',+ sourceUrl: 'https://cdn.example.com/endpoint.json',+ manifestText: JSON.stringify({ schemaVersion: 1, authApiBaseUrl: 'https://auth.example.com' }),+};++function cacheFile(): string {+ return path.join(dir, ENDPOINT_MANIFEST_CACHE_FILE_NAME);+}++describe('endpointManifestCache', () => {+ it('写入后可原样读回', () => {+ expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);+ expect(readEndpointManifestCache(dir)).toEqual(ENTRY);+ });++ it('目录不存在时自动创建', () => {+ const nested = path.join(dir, 'a', 'b');+ expect(writeEndpointManifestCache(nested, ENTRY)).toBe(true);+ expect(readEndpointManifestCache(nested)).toEqual(ENTRY);+ });++ it('写入不留下临时文件', () => {+ writeEndpointManifestCache(dir, ENTRY);+ expect(fs.existsSync(`${cacheFile()}.tmp`)).toBe(false);+ });++ it('文件缺失返回 null', () => {+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it.each([+ ['非 JSON', 'not json'],+ ['JSON 数组', '[]'],+ ['JSON 标量', '42'],+ ['缺 manifestText', JSON.stringify({ savedAt: ENTRY.savedAt, sourceUrl: ENTRY.sourceUrl })],+ ['字段类型不对', JSON.stringify({ ...ENTRY, sourceUrl: 123 })],+ ['savedAt 不可解析', JSON.stringify({ ...ENTRY, savedAt: 'whenever' })],+ ['字段空白', JSON.stringify({ ...ENTRY, manifestText: ' ' })],+ ])('%s → null(坏数据当没有缓存)', (_label, raw) => {+ fs.writeFileSync(cacheFile(), raw, 'utf8');+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it('文件字节数超上限时读前就拒绝(不把大文件读进内存)', () => {+ fs.writeFileSync(cacheFile(), 'x'.repeat(128 * 1024 + 1), 'utf8');+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it('多字节 UTF-8 内容按字节而非字符数判断', () => {+ // 每个汉字 3 字节:字符数远小于上限,字节数刚好越界。用 string.length 判断会放行。+ const cjk = '配'.repeat(128 * 1024 / 3 + 10);+ expect(Buffer.byteLength(cjk, 'utf8')).toBeGreaterThan(128 * 1024);+ expect(cjk.length).toBeLessThan(128 * 1024);+ fs.writeFileSync(cacheFile(), cjk, 'utf8');+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it('最终落盘 JSON 超上限时拒绝写入', () => {+ const huge = { ...ENTRY, manifestText: 'x'.repeat(128 * 1024 + 1) };+ expect(writeEndpointManifestCache(dir, huge)).toBe(false);+ expect(fs.existsSync(cacheFile())).toBe(false);+ });++ it('写检查量的是序列化后的字节:全转义字符不会"写得进、读不回"', () => {+ // manifestText 本身 64KiB(旧实现的上限之内),但每个 `"` 被 JSON 转义成 `\\"`,+ // 落盘 payload 翻倍越过 128KiB。旧实现会写成功、读路径再按文件字节数拒掉。+ const quoted = { ...ENTRY, manifestText: '"'.repeat(64 * 1024) };+ expect(Buffer.byteLength(quoted.manifestText, 'utf8')).toBeLessThanOrEqual(128 * 1024);+ expect(Buffer.byteLength(JSON.stringify(quoted, null, 2), 'utf8')).toBeGreaterThan(128 * 1024);++ expect(writeEndpointManifestCache(dir, quoted)).toBe(false);+ expect(fs.existsSync(cacheFile())).toBe(false);+ });++ it('写得进的一定读得回(读写共用同一上限)', () => {+ // 贴着上限:序列化后不超过 128KiB 就必须写成功且原样读回。+ let text = 'y'.repeat(100 * 1024);+ while (Buffer.byteLength(JSON.stringify({ ...ENTRY, manifestText: text }, null, 2), 'utf8') > 128 * 1024) {+ text = text.slice(0, -1024);+ }+ const big = { ...ENTRY, manifestText: text };+ expect(writeEndpointManifestCache(dir, big)).toBe(true);+ expect(readEndpointManifestCache(dir)).toEqual(big);+ });++ it('formatCacheSavedAt 解析不了就原样回显', () => {+ expect(formatCacheSavedAt('not-a-date', 'zh-CN')).toBe('not-a-date');+ expect(formatCacheSavedAt(ENTRY.savedAt, 'zh-CN')).not.toBe('');+ });+});++describe('缓存端点的受信任域约束(安全边界)', () => {+ // 生产实际取值:两份自举基址都由构建脚本注入,userData 写入改不了。+ const GLOBAL_BASE = 'https://hotfix.cindy.app/cindy';+ const CN_BASE = 'https://hotfix.cindy.com.cn/cindy';+ const TRUSTED = Object.values(REGION_ENDPOINT_DOMAIN);+ /** CN 构建的策略:非跨区端点锁 cindy.com.cn,slack/telegram hook 才允许 cindy.app。 */+ const CN_POLICY = { regionDomain: REGION_ENDPOINT_DOMAIN.cn, crossRegionDomain: REGION_ENDPOINT_DOMAIN.global };+ const GLOBAL_POLICY = { regionDomain: REGION_ENDPOINT_DOMAIN.global, crossRegionDomain: REGION_ENDPOINT_DOMAIN.global };++ it('区域域名是显式写死的(不从基址推导)', () => {+ // 上一版从自举基址「去掉最左一段」推导,在多段公共后缀上会**放宽**信任:+ // https://example.co.uk → co.uk,于是任何 attacker.co.uk 都成了可信。+ expect([...TRUSTED].sort()).toEqual(['cindy.app', 'cindy.com.cn']);+ expect(REGION_ENDPOINT_DOMAIN.cn).toBe('cindy.com.cn');+ expect(REGION_ENDPOINT_DOMAIN.global).toBe('cindy.app');+ });++ it('跨区例外只有 slack / telegram hook 两个 key', () => {+ // 每加一个 key 就等于允许该端点跨区,而跨区 token 误发正是要防的事。+ expect([...CROSS_REGION_ENDPOINT_KEYS].sort()).toEqual(['slackHookWsUrl', 'telegramHookWsUrl']);+ });++ it('CN 构建拒绝换成 Global 真实服务的伪造缓存(跨区 token 误发)', () => {+ // 线上两份清单都没有 region 字段、region 本身也是清单里未认证的数据,所以+ // 「两域并集」会让这份缓存通过:sourceUrl 匹配 CN、主机是 Global 的**真实**服务。+ expect(+ findUntrustedCachedEndpoint(+ {+ authApiBaseUrl: 'https://auth.cindy.app',+ websiteUrl: 'https://cindy.com.cn',+ },+ CN_POLICY,+ ),+ ).toBe('authApiBaseUrl');+ });++ it.each([+ 'deviceLinkApiBaseUrl',+ 'oauthBrokerApiBaseUrl',+ 'modelAccessApiBaseUrl',+ 'voiceApiBaseUrl',+ 'authDesktopCallbackUrl',+ ])('CN 构建下 %s 也不允许落在 Global 域', (key) => {+ expect(findUntrustedCachedEndpoint({ [key]: 'https://x.cindy.app' }, CN_POLICY)).toBe(key);+ });++ it('Global 构建下本区端点必须是 cindy.app,不接受 CN 域', () => {+ expect(+ findUntrustedCachedEndpoint({ authApiBaseUrl: 'https://auth.cindy.com.cn' }, GLOBAL_POLICY),+ ).toBe('authApiBaseUrl');+ });++ it('自检:两份自举基址都落在受信任域内', () => {+ expect(findBootstrapHostOutsideTrustedDomains([GLOBAL_BASE, CN_BASE], TRUSTED)).toBeNull();+ });++ it.each([+ ['apex 在多段公共后缀下', 'https://example.co.uk', 'example.co.uk'],+ ['完全无关的域', 'https://cdn.attacker.net', 'cdn.attacker.net'],+ ['非 URL', 'not a url', 'not a url'],+ ])('自检报出越界的自举主机:%s', (_label, baseUrl, expected) => {+ expect(findBootstrapHostOutsideTrustedDomains([baseUrl], TRUSTED)).toBe(expected);+ });++ it('自检忽略空基址(某些构建只有本区基址)', () => {+ expect(findBootstrapHostOutsideTrustedDomains([GLOBAL_BASE, '', ' '], TRUSTED)).toBeNull();+ });++ it('仓内 CN 清单的真实端点全部合规(hook 走跨区例外,其余锁本区)', () => {+ expect(+ findUntrustedCachedEndpoint(+ {+ authApiBaseUrl: 'https://auth.cindy.com.cn',+ slackHookWsUrl: 'wss://slack-hook.cindy.app',+ telegramHookWsUrl: 'wss://telegram-hook.cindy.app',+ websiteUrl: 'https://cindy.com.cn',+ cdnBaseUrl: 'https://hotfix.cindy.com.cn/cindy',+ authDesktopCallbackUrl: 'https://auth.cindy.com.cn/api/auth/desktop/callback',+ },+ CN_POLICY,+ ),+ ).toBeNull();+ });++ it('仓内 Global 清单的真实端点全部合规', () => {+ expect(+ findUntrustedCachedEndpoint(+ {+ authApiBaseUrl: 'https://auth.cindy.app',+ slackHookWsUrl: 'wss://slack-hook.cindy.app',+ websiteUrl: 'https://cindy.app',+ cdnBaseUrl: 'https://hotfix.cindy.app/cindy',+ },+ GLOBAL_POLICY,+ ),+ ).toBeNull();+ });++ it.each([+ ['攻击者自选主机', 'https://evil.example.com'],+ ['受信任域作为子串但不是后缀', 'https://cindy.app.evil.com'],+ ['受信任域拼在主机名里', 'https://notcindy.app'],+ ['末尾多一段', 'https://auth.cindy.app.attacker.net'],+ ])('%s 被拒(返回越界的 key)', (_label, hostile) => {+ expect(+ findUntrustedCachedEndpoint(+ { authApiBaseUrl: hostile, websiteUrl: 'https://cindy.app' },+ GLOBAL_POLICY,+ ),+ ).toBe('authApiBaseUrl');+ });++ it('空值端点跳过检查(缺失端点本就归一成空串)', () => {+ expect(+ findUntrustedCachedEndpoint({ authApiBaseUrl: '', heartbeatUrl: '' }, GLOBAL_POLICY),+ ).toBeNull();+ });++ it('策略缺域名时一律拒绝(fail closed,不是放行)', () => {+ expect(+ findUntrustedCachedEndpoint(+ { authApiBaseUrl: 'https://auth.cindy.app' },+ { regionDomain: '', crossRegionDomain: '' },+ ),+ ).toBe('origin-policy-unavailable');+ });+});++describe('缓存读取只接受常规文件(阻断路径不能被挂住)', () => {+ it('symlink 指向合法缓存也拒绝(statSync 会跟随,lstatSync 不会)', () => {+ const real = path.join(dir, 'real-cache.json');+ fs.writeFileSync(real, JSON.stringify(ENTRY), 'utf8');+ fs.symlinkSync(real, cacheFile());+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it('目录占位时拒绝', () => {+ fs.mkdirSync(cacheFile());+ expect(readEndpointManifestCache(dir)).toBeNull();+ });++ it('FIFO 时拒绝且不阻塞', () => {+ // readFileSync 打开 FIFO 会**阻塞**——这段跑在启动阻断路径上,阻塞等于启动卡死。+ const mkfifo = spawnSync('mkfifo', [cacheFile()]);+ if (mkfifo.status !== 0) return; // 平台没有 mkfifo(Windows)时跳过+ const startedAt = Date.now();+ expect(readEndpointManifestCache(dir)).toBeNull();+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ });++ it('lstat 通过之后路径才变成 FIFO(TOCTOU 窗口)时,open 也不阻塞', () => {+ // review 抓到:lstat 那道只挡住"打开前就是 FIFO";窗口内被换上 FIFO 时,+ // 不带 O_NONBLOCK 的 open(O_RDONLY) 在 POSIX 下会等到有 writer 为止 —— 而这段+ // 跑在启动阻断路径上,等于连弹框都出不来。这里把 lstat 结果伪造成常规文件来+ // 精确复现那个窗口:实现必须靠 O_NONBLOCK + fstat 复核活着回来。+ const mkfifo = spawnSync('mkfifo', [cacheFile()]);+ if (mkfifo.status !== 0) return; // 平台没有 mkfifo(Windows)时跳过+ const spy = vi+ .spyOn(fs, 'lstatSync')+ .mockReturnValue({ isFile: () => true, size: 16, ino: 0, dev: 0 } as unknown as fs.Stats);+ try {+ const startedAt = Date.now();+ expect(readEndpointManifestCache(dir)).toBeNull();+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ } finally {+ spy.mockRestore();+ }+ });+});++describe('缓存写入的临时文件必须唯一且独占创建', () => {+ it('临时文件名带 pid 与随机后缀,不是可预测的 <target>.tmp', () => {+ expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);+ // 固定名字会被别的进程先占位(FIFO → writeFileSync 无限阻塞;symlink → 跟随并截断)。+ expect(fs.existsSync(`${cacheFile()}.tmp`)).toBe(false);+ // 成功路径不留任何临时文件。+ expect(fs.readdirSync(dir).filter((f) => f.endsWith('.tmp'))).toEqual([]);+ });++ it('固定 .tmp 路径被 FIFO 占位也不影响写入(不再走那个路径)', () => {+ const mkfifo = spawnSync('mkfifo', [`${cacheFile()}.tmp`]);+ if (mkfifo.status !== 0) return; // 平台没有 mkfifo(Windows)时跳过+ const startedAt = Date.now();+ expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);+ // 旧实现会在这里无限阻塞;这段跑在清单解析成功之后、启动继续之前。+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ expect(readEndpointManifestCache(dir)).toEqual(ENTRY);+ });++ it('target 被换成 symlink 时 rename 替换掉它本身,不写穿到链接目标', () => {+ const outside = path.join(dir, 'outside.txt');+ fs.writeFileSync(outside, 'untouched', 'utf8');+ fs.symlinkSync(outside, cacheFile());++ expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);+ // 链接目标内容不变 = 没有被当成任意文件写入原语。+ expect(fs.readFileSync(outside, 'utf8')).toBe('untouched');+ // cacheFile 现在是常规文件(symlink 已被 rename 替换),读回正常。+ expect(fs.lstatSync(cacheFile()).isSymbolicLink()).toBe(false);+ expect(readEndpointManifestCache(dir)).toEqual(ENTRY);+ });+});diff --git a/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts b/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.tsnew file mode 100644index 0000000000..b3b576f0ed--- /dev/null+++ b/apps/desktop/src/main/__tests__/endpointManifestDialogCopy.test.ts@@ -0,0 +1,127 @@+/**+ * 端点清单阻断框的四语文案与内容组装。+ *+ * 覆盖两件事:+ * 1. 文案完整性——四种语言的 key 集合一致、无空值,且**单语言输出**(这个框原先+ * 把中英两段拼在同一个 detail 里,用户看到一屏混排,是本次要修的现象);+ * 2. 组装规则——离线按钮只在「网络层失败 + 有可用缓存」时出现,choices 与 buttons+ * 一一对应(宿主按 index 取语义,错位就会把"退出"当成"重试")。+ */+import { describe, expect, it } from 'vitest';++import {+ ENDPOINT_MANIFEST_DIALOG_COPY,+ buildEndpointManifestDialogContent,+ type EndpointManifestDialogLocale,+} from '../endpointManifestDialogCopy';++const LOCALES: EndpointManifestDialogLocale[] = ['zh-CN', 'en', 'ja', 'ko'];++/** CJK 与拉丁字母混排检测用:排除产品名与占位符后还剩英文单词即视为混排。 */+function stripAllowedLatin(text: string): string {+ return text+ .replace(/\{\{\w+\}\}/g, ' ')+ .replace(/Cindy/g, ' ');+}++describe('端点清单弹框文案', () => {+ it('四种语言 key 集合一致且无空值', () => {+ const reference = Object.keys(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN']).sort();+ for (const locale of LOCALES) {+ const copy = ENDPOINT_MANIFEST_DIALOG_COPY[locale];+ expect(Object.keys(copy).sort(), `${locale} key 集合`).toEqual(reference);+ for (const [key, value] of Object.entries(copy)) {+ expect(value.trim(), `${locale}.${key} 不得为空`).not.toBe('');+ }+ }+ });++ it('带占位的行都保留了自己的占位符', () => {+ for (const locale of LOCALES) {+ const copy = ENDPOINT_MANIFEST_DIALOG_COPY[locale];+ expect(copy.sourceLine).toContain('{{source}}');+ expect(copy.reasonLine).toContain('{{reason}}');+ expect(copy.diagnosisLine).toContain('{{diagnosis}}');+ expect(copy.logLine).toContain('{{path}}');+ expect(copy.offlineHint).toContain('{{savedAt}}');+ }+ });++ it('CJK 语言的文案不夹带英文句子(不再中英混排)', () => {+ for (const locale of ['zh-CN', 'ja', 'ko'] as const) {+ for (const [key, value] of Object.entries(ENDPOINT_MANIFEST_DIALOG_COPY[locale])) {+ const leftover = stripAllowedLatin(value);+ expect(/[A-Za-z]{3,}/.test(leftover), `${locale}.${key} 夹带英文:${value}`).toBe(false);+ }+ }+ });++ it('网络失败 + 有缓存:三个按钮,choices 与 buttons 对齐', () => {+ const content = buildEndpointManifestDialogContent({+ locale: 'zh-CN',+ kind: 'network',+ reason: 'fetch-failed:ERR_FAILED',+ source: 'https://cdn.example.com/endpoint.json',+ diagnosis: 'proxy=DIRECT dns=ok(1.2.3.4) tcp=ok(12ms)',+ logPath: '/tmp/logs',+ offlineSavedAt: '2026/7/29 06:22',+ });+ const copy = ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'];+ expect(content.buttons).toEqual([+ copy.retryButton,+ copy.offlineButton,+ copy.quitButton,+ ]);+ expect(content.choices).toEqual(['retry', 'offline', 'exit']);+ expect(content.buttons).toHaveLength(content.choices.length);+ expect(content.defaultId).toBe(0);+ expect(content.cancelId).toBe(2);+ expect(content.message).toBe(copy.title);+ expect(content.detail).toContain('fetch-failed:ERR_FAILED');+ expect(content.detail).toContain('https://cdn.example.com/endpoint.json');+ expect(content.detail).toContain('proxy=DIRECT');+ expect(content.detail).toContain('/tmp/logs');+ expect(content.detail).toContain('2026/7/29 06:22');+ });++ it('网络失败但没有缓存:不出现离线按钮', () => {+ const content = buildEndpointManifestDialogContent({+ locale: 'en',+ kind: 'network',+ reason: 'fetch-failed:ERR_FAILED',+ source: 'https://cdn.example.com/endpoint.json',+ offlineSavedAt: null,+ });+ expect(content.choices).toEqual(['retry', 'exit']);+ expect(content.detail).not.toContain(+ ENDPOINT_MANIFEST_DIALOG_COPY.en.offlineHint.split('{{')[0],+ );+ });++ it('配置事故即使有缓存也不给离线出口', () => {+ const content = buildEndpointManifestDialogContent({+ locale: 'zh-CN',+ kind: 'config',+ reason: 'invalid-json',+ source: 'https://cdn.example.com/endpoint.json',+ offlineSavedAt: '2026/7/29 06:22',+ });+ expect(content.choices).toEqual(['retry', 'exit']);+ expect(content.detail).toContain(ENDPOINT_MANIFEST_DIALOG_COPY['zh-CN'].configBody);+ expect(content.detail).not.toContain('2026/7/29 06:22');+ });++ it('诊断与日志缺失时不留空行占位', () => {+ const content = buildEndpointManifestDialogContent({+ locale: 'zh-CN',+ kind: 'network',+ reason: 'fetch-failed',+ source: 'https://cdn.example.com/endpoint.json',+ diagnosis: null,+ logPath: null,+ offlineSavedAt: null,+ });+ expect(content.detail).not.toContain('{{');+ expect(content.detail.split('\n').filter((line) => line === '')).toHaveLength(1);+ });+});diff --git a/apps/desktop/src/main/__tests__/endpointManifestDialogCopyGlossary.test.ts b/apps/desktop/src/main/__tests__/endpointManifestDialogCopyGlossary.test.tsnew file mode 100644index 0000000000..d65182aac5--- /dev/null+++ b/apps/desktop/src/main/__tests__/endpointManifestDialogCopyGlossary.test.ts@@ -0,0 +1,147 @@+/**+ * 端点清单阻断框四语文案的术语门禁(影子 catalog 第四处)。+ *+ * 为什么需要:`scripts/check-i18n-glossary.mjs` 只读 renderer 的 locale JSON,而这个框+ * 弹在 createWindow 之前——renderer 与 i18next 都还不存在,文案只能手写在 main 侧的+ * `endpointManifestDialogCopy.ts` 里,根门禁扫不到。它还是**启动失败时用户看到的唯一+ * 一屏**,措辞与标点出错的代价不比应用内文案小。+ *+ * 判定逻辑复用 scripts/shared/glossary-rules.mjs,与根门禁、mobile 影子 catalog、+ * 原生菜单与 OAuth 结果页 catalog 同一套,避免各处规则悄悄漂移。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++import {+ ELLIPSIS_LOCALES,+ HALFWIDTH_PUNCT_LOCALES,+ findCaseMismatch,+ findHalfWidthPunct,+ hasAsciiEllipsis,+ makeExemptChecker,+ normalizeForPunctuation,+ occursIn,+ stripNonProse,+ caseStandardFor,+ sourceMentions,+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignore -- 共享规则是 .mjs,没有类型声明;这里只用它做断言+} from '../../../../../scripts/shared/glossary-rules.mjs';++import { ENDPOINT_MANIFEST_DIALOG_COPY } from '../endpointManifestDialogCopy';++const REPO_ROOT = resolve(__dirname, '../../../../..');++interface GlossaryTerm {+ id: string;+ status: 'decided' | 'proposed';+ en: string;+ translations?: Record<string, string>;+ forbidden?: Record<string, (string | { text: string; whenEn: string })[]>;+ exempt?: string[];+ checkCase?: boolean;+}++const glossary = JSON.parse(+ readFileSync(resolve(REPO_ROOT, 'i18n/glossary.json'), 'utf8'),+) as {+ locales: string[];+ sourceLocale: string;+ punctuationExempt?: string[];+ terms: GlossaryTerm[];+};++/**+ * 摊平成 (locale, key, value)。前缀必须是 `desktop:`——glossary.json 的 exempt 按+ * `^(desktop|mobile/xxx):` 校验并匹配,自造前缀会让豁免对本 catalog 静默失效+ * (同 applicationMenuLabels.test.ts 的注释)。用 `endpointDialog.` 子命名空间区分来源。+ */+const entries = Object.entries(ENDPOINT_MANIFEST_DIALOG_COPY).flatMap(([locale, copy]) =>+ Object.entries(copy).map(([key, value]) => ({+ locale,+ key: `desktop:endpointDialog.${key}`,+ value: value as string,+ })),+);++/** 标点豁免:与根门禁同源,只作用于半角标点检查(不含省略号)。 */+const isHalfWidthExempt = makeExemptChecker(glossary.punctuationExempt);++/** key → 英文源文案,供条件禁用按英文源判断。 */+const sourceByKey = new Map(+ entries.filter((e) => e.locale === glossary.sourceLocale).map((e) => [e.key, e.value]),+);++describe('端点清单弹框文案符合术语表', () => {+ it('摊平后覆盖四种语言', () => {+ const locales = new Set(entries.map((e) => e.locale));+ expect([...locales].sort()).toEqual([...glossary.locales].sort());+ expect(entries.length).toBeGreaterThan(0);+ });++ it('不使用术语表的禁用译法', () => {+ const violations: string[] = [];+ const notes: string[] = [];+ for (const term of glossary.terms) {+ const isExempt = makeExemptChecker(term.exempt);+ for (const { locale, key, value } of entries) {+ if (isExempt(key)) continue;+ for (const entry of term.forbidden?.[locale] ?? []) {+ const bad = typeof entry === 'string' ? entry : entry.text;+ const whenEn = typeof entry === 'string' ? null : entry.whenEn;+ if (!occursIn(stripNonProse(value), bad)) continue;+ if (whenEn) {+ const source = sourceByKey.get(key);+ if (!source || !sourceMentions(stripNonProse(source), whenEn)) continue;+ }+ const line = `${locale} ${key}: 「${bad}」(${term.en})— ${value}`;+ if (term.status === 'decided') violations.push(line);+ else notes.push(line);+ }+ }+ }+ if (notes.length > 0) {+ console.warn(`[endpoint-dialog-glossary] 待裁决术语命中:\n${notes.join('\n')}`);+ }+ expect(violations, `端点弹框命中禁用译法:\n${violations.join('\n')}`).toEqual([]);+ });++ it('保留英文的术语大小写形态统一', () => {+ const violations: string[] = [];+ const notes: string[] = [];+ for (const term of glossary.terms) {+ const isExempt = makeExemptChecker(term.exempt);+ for (const { locale, key, value } of entries) {+ if (isExempt(key)) continue;+ const standard = caseStandardFor(term, locale);+ if (!standard) continue;+ const hit = findCaseMismatch(stripNonProse(value), standard);+ if (!hit) continue;+ const line = `${locale} ${key}: 「${hit}」应为「${standard}」`;+ if (term.status === 'decided') violations.push(line);+ else notes.push(line);+ }+ }+ if (notes.length > 0) {+ console.warn(`[endpoint-dialog-glossary] 待裁决术语大小写:\n${notes.join('\n')}`);+ }+ expect(violations, `端点弹框大小写不统一:\n${violations.join('\n')}`).toEqual([]);+ });++ it('标点风格符合各语言规则', () => {+ const violations: string[] = [];+ for (const { locale, key, value } of entries) {+ const prose = normalizeForPunctuation(value);+ if (HALFWIDTH_PUNCT_LOCALES.has(locale) && !isHalfWidthExempt(key)) {+ const mark = findHalfWidthPunct(prose);+ if (mark) violations.push(`${locale} ${key}: 中文后半角「${mark}」— ${value}`);+ }+ if (ELLIPSIS_LOCALES.has(locale) && hasAsciiEllipsis(prose)) {+ violations.push(`${locale} ${key}: 应使用「…」而非三个半角点 — ${value}`);+ }+ }+ expect(violations, `端点弹框标点不符:\n${violations.join('\n')}`).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/clientEndpointsService.ts b/apps/desktop/src/main/clientEndpointsService.tsindex bdffbc5bba..5161fe003d 100644--- a/apps/desktop/src/main/clientEndpointsService.ts+++ b/apps/desktop/src/main/clientEndpointsService.ts@@ -7,11 +7,26 @@* app.ready 内、createWindow / 一切更新检查之前解析清单;endpoint 字段允许按* region 缺失或留空,不会阻断启动;拉不到、JSON / schema 无法解析或非空值非法* 时才弹系统错误框(重试 / 退出),用户不重试成功就不放行启动。- * **没有缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——生效的端点- * (含更新链 CDN base)全部来自清单,非空值配置非法会在启动时立刻暴露。- * 唯一的柔性是弹框**之前**的网络层自动重试(AUTO_RETRY_DELAYS_MS,只对- * 拉取失败生效、不对解析/校验失败生效),用于自愈首启瞬时抖动;重试用尽- * 仍失败照样阻断,所以严格语义不变。+ * **没有自动缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——生效的端点+ * (含更新链 CDN base)默认全部来自本次拉到的清单,非空值配置非法会在启动时立刻暴露。+ *+ * 柔性只有两处,都不破坏"不静默降级":+ * 1. 弹框**之前**的网络层自动重试(AUTO_RETRY_DELAYS_MS,只对拉取失败生效、+ * 不对解析/校验失败生效),用于自愈首启瞬时抖动;重试用尽仍失败照样阻断。+ * 2. **用户在弹框上显式点击**的离线出口(2026-07 追加):传输层失败且本地存有+ * 上次成功清单时,弹框多一个「用上次配置启动」按钮。原设计连"用户明知自己+ * 离线、只想打开应用看看本地内容"都没有出口,只能反复弹框或退出。严格边界见+ * endpointManifestCache.ts:只有**传输层**失败给出口(JSON / schema / 非法值 /+ * region 不匹配,以及永久性 HTTP 3xx/4xx 这类配置事故照旧硬阻断——给出口等于+ * 帮用户绕过真实配置错,分类规则见 classifyManifestFailure),缓存存的是校验通过+ * 的原文、读回后重新走同一套严格解析,清单地址变化即作废,全程必须用户点击。+ *+ * 传输层失败在弹框前还会跑一轮分阶段诊断(endpointFetchDiagnostics:代理决策 /+ * DNS / TCP,每段各有硬 deadline——这段跑在阻断路径上,探针挂住等于启动卡死)+ * 并抓一份 netlog,摘要同时进日志和弹框。原因是 Electron `net.request`+ * 把 DNS、代理、TLS、被本机网络过滤扩展拦下全折叠成通用的 `ERR_FAILED`,+ * 只报一个错误码等于没有现场(2026-07 实测:同一 URL curl 与裸 Electron 都是 200,+ * 安装版毫秒级 ERR_FAILED,单看错误码无从下手)。** 清单来源按运行形态三选一(resolveEndpointSource,纯函数可单测):* - packaged / dev + --endpoints-cdn:从当前构建区域的烘焙自举基址@@ -33,7 +48,7 @@import fs from 'node:fs';import path from 'node:path';-import { app, dialog, ipcMain, net } from 'electron';+import { app, dialog, ipcMain, net, netLog } from 'electron';import {resolveClientEndpointsStrict,@@ -44,11 +59,32 @@ import {type RealmManifestBaseUrls,} from '@cindy/maker-shared/client-endpoints';-import { createLogger } from './logger';+import {+ createDefaultProbes,+ formatEndpointFetchDiagnosis,+ probeEndpointFetch,+ withDeadline,+} from './endpointFetchDiagnostics';+import {+ findBootstrapHostOutsideTrustedDomains,+ findUntrustedCachedEndpoint,+ formatCacheSavedAt,+ readEndpointManifestCache,+ writeEndpointManifestCache,+ REGION_ENDPOINT_DOMAIN,+} from './endpointManifestCache';+import {+ buildEndpointManifestDialogContent,+ type EndpointManifestDialogChoice,+ type EndpointManifestDialogLocale,+ type EndpointManifestFailureKind,+} from './endpointManifestDialogCopy';+import { createLogger, getLogDir } from './logger';import {ENDPOINT_MANIFEST_BASE_URL,ENDPOINT_MANIFEST_PEER_BASE_URL,} from '../shared/endpoints';+import { resolvePreferredSystemLocale } from '../shared/locale';const log = createLogger('clientEndpoints');@@ -67,6 +103,19 @@ const DEFAULT_REALM_MANIFEST_BASE_URLS: RealmManifestBaseUrls =cn: ENDPOINT_MANIFEST_BASE_URL,global: ENDPOINT_MANIFEST_PEER_BASE_URL,};+/**+ * **缓存**端点的来源策略(编译期锚点):非跨区端点必须落在本构建区域的域内。+ *+ * 按区域收紧、而不是「两个域都信」:线上两份清单都没有 region 字段、region 本身也是+ * 清单里未认证的数据,所以并集会让 CN 构建接受一份把 authApiBaseUrl 换成 Global 真实+ * 服务的伪造缓存,离线启动后把 CN 的 token 发去 Global(review 抓到)。+ * 详见 endpointManifestCache.ts 的 REGION_ENDPOINT_DOMAIN / CROSS_REGION_ENDPOINT_KEYS。+ */+const CACHED_ENDPOINT_ORIGIN_POLICY = {+ regionDomain: REGION_ENDPOINT_DOMAIN[BUILD_AUTH_REGION],+ crossRegionDomain: REGION_ENDPOINT_DOMAIN.global,+} as const;+/** 单次请求的网络超时——只用于触发错误框,不是静默降级。 */const ATTEMPT_TIMEOUT_MS = 15_000;@@ -89,6 +138,13 @@ const ATTEMPT_TIMEOUT_MS = 15_000;*/const AUTO_RETRY_DELAYS_MS: readonly number[] = [800, 2400];+/**+ * 整个诊断阶段的兜底预算。生产实现(diagnoseCdnManifestFetch)内部每一段都已经各自+ * 有界、并发跑,墙钟约 11s;这里再套一层是因为 diagnose 是**注入点**——阻断路径上+ * 不允许出现"某个实现忘了设超时,于是启动永远停在这里"的可能。+ */+const DIAGNOSIS_TOTAL_BUDGET_MS = 15_000;+export const CLIENT_ENDPOINTS_SYNC_CHANNEL = 'client-endpoints:get-sync';// ── 清单来源解析(纯函数,规则 14:内存 harness 可测) ─────────────────────@@ -129,7 +185,13 @@ export function resolveEndpointSource(input: ResolveEndpointSourceInput): Endpoi* error 对象整个丢掉、统一折叠成 `fetch-failed`,现场只能看到一句* "fetch-failed",日志里也无从区分 DNS / 代理 / TLS / 超时,排查全靠猜。*/-export type ManifestFetchResult = { ok: true; text: string } | { ok: false; detail: string };+export type ManifestFetchResult =+ | { ok: true; text: string }+ /**+ * detail = 错误码级别的短标识(进 reason / 弹框);raw = 未抽码的原始错误消息,+ * 只进日志。两者分开是因为 `ERR_FAILED` 这类通用码丢掉原文后就再无信息可查。+ */+ | { ok: false; detail: string; raw?: string };/** 归一为单行并截断:避免多行栈把弹框 detail 与日志行撑爆。 */function normalizeDetail(detail: string): string {@@ -146,6 +208,14 @@ function describeFetchError(err: unknown): string {return normalizeDetail(code ?? message);}+/** 未抽码的原始错误消息(含 errno / syscall 等),只写日志不进弹框。 */+function rawFetchError(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ const errno = err as NodeJS.ErrnoException | null;+ const extras = [errno?.code, errno?.syscall].filter(Boolean).join(' ');+ return normalizeDetail(extras ? `${message} (${extras})` : message);+}+/** 失败 detail → 阻断循环用的 reason(保持 maker-shared 的 `fetch-failed` 前缀语义)。 */function fetchFailedReason(detail: string): string {const normalized = normalizeDetail(detail);@@ -166,7 +236,15 @@ function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchRif (settled) return;settled = true;if (timeoutToClear !== undefined) clearTimeout(timeoutToClear);- if (!value.ok) log.debug('fetch failed (%s) for %s', value.detail, url);+ if (!value.ok) {+ // raw 只在这里落日志:detail 抽过码后可能只剩 ERR_FAILED,原文是唯一现场。+ log.warn(+ 'fetch failed (%s%s) for %s',+ value.detail,+ value.raw && value.raw !== value.detail ? ` | ${value.raw}` : '',+ url,+ );+ }resolve(value);};const timeout = setTimeout(() => {@@ -185,15 +263,21 @@ function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchR});response.on('end', () => finish({ ok: true, text: body }, timeout));response.on('error', (err) =>- finish({ ok: false, detail: describeFetchError(err) }, timeout),+ finish(+ { ok: false, detail: describeFetchError(err), raw: rawFetchError(err) },+ timeout,+ ),);});request.on('error', (err) =>- finish({ ok: false, detail: describeFetchError(err) }, timeout),+ finish(+ { ok: false, detail: describeFetchError(err), raw: rawFetchError(err) },+ timeout,+ ),);request.end();} catch (err) {- resolve({ ok: false, detail: describeFetchError(err) });+ resolve({ ok: false, detail: describeFetchError(err), raw: rawFetchError(err) });}});}@@ -228,11 +312,68 @@ function defaultSleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+/**+ * **不该被当成"清单配置错"的 4xx**。两类,理由不同但结论相同:+ * - 瞬时:408 Request Timeout / 425 Too Early(传输层抖动)、429 Too Many Requests+ * (被限流,过一会儿就好)——把它们判成配置错会让一个正被限流的用户既不能重试、+ * 又用不上手里那份可用缓存,直接开不了应用;+ * - 环境侧:407 Proxy Authentication Required。按 RFC 9110 §15.5.8 它**只可能来自+ * 代理**,永远不会由源站发出,所以它描述的是这台机器的网络环境(代理凭据缺失或+ * 过期),不是清单的部署错。这恰恰是离线出口最该生效的场景——公司代理没登录时+ * 正好该允许用上次的配置把应用打开。它同时也会拿到重试预算,这是有意的:代价只有+ * 约 3.2s,而这期间系统/代理有可能把凭据补上。+ * 其余 3xx/4xx 才是路径 / 权限 / 部署配置错。+ */+const NON_CONFIG_4XX_STATUSES = new Set([407, 408, 425, 429]);++/** HTTP 状态码是否属于"重试没有意义"的永久性错误(分类与重试预算共用同一判定)。 */+function isPermanentHttpStatus(status: number): boolean {+ return status < 500 && !NON_CONFIG_4XX_STATUSES.has(status);+}++/**+ * 失败 reason → 失败分类(决定文案与是否给离线出口)。+ *+ * 分界不是"有没有拿到正文",而是**这次失败是不是我们的配置错**,并且与自动重试循环+ * 共用同一判定(isPermanentHttpStatus),避免同一个失败被判成"配置错所以不重试"又+ * "网络问题所以可以用缓存绕过":+ * - 永久性 HTTP(3xx/4xx 去掉 NON_CONFIG_4XX_STATUSES)= 路径 / 权限 / 部署配置错 → config;+ * - 5xx、407/408/425/429 与传输层失败(超时 / DNS / 代理 / ERR_*)→ network,可重试、可离线;+ * - 烘焙基址为空是打包事故,同样 config。+ */+export function classifyManifestFailure(reason: string): EndpointManifestFailureKind {+ if (!reason.startsWith('fetch-failed')) return 'config';+ const detail = reason.slice('fetch-failed'.length).replace(/^:/, '');+ if (detail === 'missing-manifest-base-url') return 'config';+ const httpStatus = /^http-(\d+)$/.exec(detail)?.[1];+ if (httpStatus && isPermanentHttpStatus(Number(httpStatus))) return 'config';+ return 'network';+}++/** 弹框需要的全部上下文;由阻断循环组装,宿主只负责渲染与取回选择。 */+export interface ManifestPromptContext {+ reason: string;+ kind: EndpointManifestFailureKind;+ /** 分阶段网络诊断摘要;非网络失败或诊断未跑时为 null。 */+ diagnosis: string | null;+ /** 诊断产物(netlog / 日志)所在目录;拿不到时为 null。 */+ logPath: string | null;+ /** 有值 = 存在已通过严格解析的离线缓存,弹框应给出「用上次配置启动」。 */+ offlineSavedAt: string | null;+}++/** 严格解析过的离线缓存候选。 */+export interface OfflineManifestCandidate {+ parsed: Extract<ParseClientEndpointManifestResult, { ok: true }>;+ /** 已格式化好的写入时间,直接进弹框文案。 */+ savedAt: string;+}+/** 阻断循环的依赖注入面(规则 14:测试用内存 harness 驱动,不起 Electron)。 */export interface BlockingResolveDeps {fetchManifest(timeoutMs: number): Promise<ManifestFetchResult>;/** 拉取/校验失败时问用户;生产实现是系统模态错误框。 */- promptRetry(reason: string): 'retry' | 'exit';+ promptRetry(context: ManifestPromptContext): EndpointManifestDialogChoice;exitApp(): void;timeoutMs?: number;/** 仅 dev 本地文件路径为 true(localhost http);CDN 路径一律不传。 */@@ -248,8 +389,37 @@ export interface BlockingResolveDeps {autoRetryDelaysMs?: readonly number[];/** 仅测试注入(默认 setTimeout);让重试节奏在内存 harness 里零等待可测。 */sleep?(ms: number): Promise<void>;- /** 启动宿主保存清单元数据;纯端点调用方无需提供。 */- onResolved?(manifest: Extract<ParseClientEndpointManifestResult, { ok: true }>): void;+ /**+ * 失败分类覆写,默认 classifyManifestFailure。dev 的本地文件模式传 `() => 'config'`:+ * 读不到 config/endpoint.json 的 reason 也是 `fetch-failed:ENOENT`,按默认规则会+ * 被判成网络失败,弹框于是让开发者"检查网络连接"——真正的问题在本地路径或内容。+ */+ classifyFailure?(reason: string): EndpointManifestFailureKind;+ /**+ * 弹框前的分阶段网络诊断(代理 / DNS / TCP + netlog)。只在网络层失败时调用,+ * 抛错不影响阻断流程——诊断是排查辅助,绝不能变成新的启动失败源。+ */+ diagnose?(reason: string): Promise<{ summary: string | null; logPath: string | null }>;+ /** 诊断阶段的兜底预算,默认 DIAGNOSIS_TOTAL_BUDGET_MS;仅测试需要调小。 */+ diagnosisBudgetMs?: number;+ /**+ * 读取并**严格解析**离线缓存;返回 null = 无可用缓存(缺失 / 损坏 / 清单地址+ * 变化 / region 不符)。只在网络层失败时调用,且结果仅用于点亮弹框上的离线按钮。+ */+ loadOfflineManifest?(): OfflineManifestCandidate | null;+ /**+ * 启动宿主保存清单元数据;纯端点调用方无需提供。+ * source 区分本次是网络拉到的还是用户选了离线缓存——宿主据此决定是否回写缓存。+ * rawText 只在 source==='network' 时给出:**校验通过的原始正文**。缓存必须存它而+ * 不是按当前 CLIENT_ENDPOINT_KEYS 重新序列化的结果,否则清单里那些本构建还不认识+ * 的新字段会被抹掉(前向兼容的发布模型正是"先发清单再发客户端"),等客户端升级后+ * 从这份缓存离线启动,新端点会静默变成空串。+ */+ onResolved?(+ manifest: Extract<ParseClientEndpointManifestResult, { ok: true }>,+ source: 'network' | 'cache',+ rawText?: string,+ ): void;}/**@@ -257,7 +427,11 @@ export interface BlockingResolveDeps {** 每一轮 = 一次首发尝试 + 若干次自动重试(仅网络层失败消耗预算,见* AUTO_RETRY_DELAYS_MS);一轮全败才 promptRetry,用户选 'retry' 则重新开一轮- * (同样带完整自动重试预算)。没有任何静默降级路径。+ * (同样带完整自动重试预算)。+ *+ * 出口只有三个,都由用户在弹框上点出来:retry(再来一轮)、exit(退出)、+ * offline(用上次成功清单启动,仅网络层失败且缓存可用时才会被点亮)。+ * **没有任何自动降级路径**——不点就一直阻断。*/export async function resolveClientEndpointsBlocking(deps: BlockingResolveDeps,@@ -274,7 +448,7 @@ export async function resolveClientEndpointsBlocking(try {fetched = await deps.fetchManifest(timeoutMs);} catch (err) {- fetched = { ok: false, detail: describeFetchError(err) };+ fetched = { ok: false, detail: describeFetchError(err), raw: rawFetchError(err) };}if (fetched.ok) {@@ -288,7 +462,7 @@ export async function resolveClientEndpointsBlocking(reason = `region-mismatch:${deps.expectedRegionWhenPresent}:${parsed.region}`;break;}- deps.onResolved?.(parsed);+ deps.onResolved?.(parsed, 'network', fetched.text);return parsed.endpoints;}// 拿到了正文但解析/校验不过 = 配置事故:重试同一份内容没有意义,直接弹框。@@ -299,9 +473,11 @@ export async function resolveClientEndpointsBlocking(reason = fetchFailedReason(fetched.detail);// 构建/打包配置事故(基址为空)重试不会改变结果,立即跳出。if (fetched.detail === 'missing-manifest-base-url') break;- // HTTP 3xx/4xx 是永久性错误(路径/权限/配置),重试同一 URL 不会自愈;仅 5xx 可能是瞬时故障。+ // 永久性 HTTP(路径/权限/配置)重试同一 URL 不会自愈;5xx 与+ // NON_CONFIG_4XX_STATUSES(407/408/425/429)可能自愈,继续消耗预算。+ // 判定与失败分类共用 isPermanentHttpStatus,两处不会分叉。const httpStatus = /^http-(\d+)$/.exec(fetched.detail)?.[1];- if (httpStatus && Number(httpStatus) < 500) break;+ if (httpStatus && isPermanentHttpStatus(Number(httpStatus))) break;const delay = retryDelays[attempt];if (delay === undefined) break; // 预算用尽 → 阻断弹框log.warn(@@ -314,32 +490,93 @@ export async function resolveClientEndpointsBlocking(await sleep(delay);}- log.warn(`client endpoints manifest unavailable (${reason}), prompting user`);- if (deps.promptRetry(reason) === 'exit') {+ const kind = (deps.classifyFailure ?? classifyManifestFailure)(reason);+ // 只有 network 才诊断:config 里包含"烘焙基址为空",拿空 URL 去跑 DNS/TCP+ // 只会得到一堆 invalid-url;HTTP 4xx / 内容非法也不是网络栈的问题。+ let diagnosis: string | null = null;+ let logPath: string | null = null;+ if (kind === 'network' && deps.diagnose) {+ try {+ // 兜底 deadline:diagnose 的内部各段都已有界,但它是注入点——阻断路径上不能+ // 存在"实现方忘了设超时就永久卡住启动"的可能。超时按诊断缺失继续弹框。+ const report = await withDeadline(+ deps.diagnose(reason),+ deps.diagnosisBudgetMs ?? DIAGNOSIS_TOTAL_BUDGET_MS,+ 'diagnosis',+ );+ diagnosis = report.summary;+ logPath = report.logPath;+ } catch (err) {+ log.debug('manifest fetch diagnosis failed: %s', String(err));+ }+ }++ let offline: OfflineManifestCandidate | null = null;+ if (kind === 'network' && deps.loadOfflineManifest) {+ try {+ offline = deps.loadOfflineManifest();+ } catch (err) {+ log.debug('offline endpoint manifest unavailable: %s', String(err));+ }+ }++ log.warn(+ 'client endpoints manifest unavailable (%s, kind=%s, diagnosis=%s, offline=%s), prompting user',+ reason,+ kind,+ diagnosis ?? 'n/a',+ offline ? 'available' : 'none',+ );+ const choice = deps.promptRetry({+ reason,+ kind,+ diagnosis,+ logPath,+ offlineSavedAt: offline?.savedAt ?? null,+ });+ if (choice === 'exit') {deps.exitApp();return null;}+ if (choice === 'offline' && offline) {+ log.warn(+ 'starting with cached endpoint manifest (savedAt=%s) after user confirmation',+ offline.savedAt,+ );+ deps.onResolved?.(offline.parsed, 'cache');+ return offline.parsed.endpoints;+ }+ // 'retry',或选了离线但缓存在这一瞬间失效 → 重开一轮完整尝试。}}-function promptRetryDialog(reason: string, sourceLabel: string): 'retry' | 'exit' {+/** 弹框宿主实现:按系统语言取四语文案(不再中英混排),返回用户选择的语义。 */+function promptRetryDialog(+ context: ManifestPromptContext,+ sourceLabel: string,+ locale: EndpointManifestDialogLocale,+): EndpointManifestDialogChoice {+ const content = buildEndpointManifestDialogContent({+ locale,+ kind: context.kind,+ reason: context.reason,+ source: sourceLabel,+ diagnosis: context.diagnosis,+ logPath: context.logPath,+ offlineSavedAt: context.offlineSavedAt,+ });// createWindow 之前无父窗口,showMessageBoxSync 直接系统模态。- const choice = dialog.showMessageBoxSync({+ const clicked = dialog.showMessageBoxSync({type: 'error',title: 'Cindy',- message: '无法获取服务器配置',- detail:- `启动所需的服务器端点清单获取失败(${reason})。\n` +- `来源 source: ${sourceLabel}\n` +- '请检查网络连接后重试;无法联网时应用不能继续启动。\n\n' +- `Failed to load the server endpoint manifest (${reason}). ` +- 'Please check your network connection and retry.',- buttons: ['重试 Retry', '退出 Quit'],- defaultId: 0,- cancelId: 1,+ message: content.message,+ detail: content.detail,+ buttons: content.buttons,+ defaultId: content.defaultId,+ cancelId: content.cancelId,noLink: true,});- return choice === 0 ? 'retry' : 'exit';+ return content.choices[clicked] ?? 'exit';}// ── 模块状态与启动入口 ──────────────────────────────────────────────────────@@ -350,6 +587,8 @@ let crossRealmOrgLoginEnabled = BUILD_VARIANT !== 'dev';let realmManifestBaseUrls: RealmManifestBaseUrls = DEFAULT_REALM_MANIFEST_BASE_URLS;let activeSessionRealm: ClientEndpointRegion | null = null;const realmEndpointCache = new Map<ClientEndpointRegion, ClientEndpointMap>();+/** 本次启动是否走了用户确认的离线缓存(而非本次网络拉取)。 */+let startedFromCachedManifest = false;const BUILD_SCOPED_ENDPOINT_KEYS = new Set<ClientEndpointKey>(['websiteUrl',@@ -357,6 +596,463 @@ const BUILD_SCOPED_ENDPOINT_KEYS = new Set<ClientEndpointKey>(['mobileUpdateBaseUrl',]);+/** 弹框语言:跟随系统语言偏好列表,与原生菜单栏同一套解析。 */+function resolveDialogLocale(): EndpointManifestDialogLocale {+ const langs = app.getPreferredSystemLanguages();+ return resolvePreferredSystemLocale(langs.length > 0 ? langs : [app.getLocale()]);+}++/**+ * netlog 文件名前缀。**不能用固定名**(review 抓到:endpointManifestCache 的写路径修好了,+ * 这条独立的 netlog 路径还敞着):别的进程能写日志目录时,可以在启动诊断跑之前把+ * `endpoint-netlog.json` 预置成 symlink(Chromium 覆写链接目标)或 FIFO(Chromium 的+ * open 卡住,而 NETLOG_STEP_TIMEOUT_MS 只解除我们的等待、并不取消它的文件系统副作用)。+ * 所以每次用带 pid + 随机后缀的唯一名,并先独占创建成常规文件再交给 netLog。+ */+const ENDPOINT_NETLOG_PREFIX = 'endpoint-netlog';+/** 私有抓包目录内的文件名;目录名已经是随机的,这里不需要再随机。 */+const ENDPOINT_NETLOG_FILE_NAME = 'capture.json';+/** 诊断用的额外一次请求预算,比正常尝试短——用户已经在等弹框。 */+const DIAGNOSIS_ATTEMPT_TIMEOUT_MS = 5_000;+/**+ * netLog start / stop 各自的预算。Chromium 的 NetworkService 或磁盘出问题时这两个+ * promise 也可能永不 settle,而它们同样在阻断路径上——不套 deadline 就等于把+ * "探针已经有超时"这件事白做了(review 抓到的正是这条剩余缺口)。+ */+const NETLOG_STEP_TIMEOUT_MS = 3_000;+/**+ * stopLogging 的尝试次数(有界)。一次没停下的进程级抓包会继续录所有流量,所以值得再试+ * 一次;但不能无限重试——那会把阻断框继续往后拖。+ */+const NETLOG_STOP_ATTEMPTS = 2;+/**+ * 前台重试都没停下之后,**后台**继续尝试收尾的节奏。+ *+ * 为什么必须有(review 抓到的第四条):前台重试是有界的,而 `withDeadline` 只解除我们的+ * 等待——两次都超时后,一次进程级抓包就处在"还在录、且没有任何后续收尾触发点"的状态,+ * 会把启动后的全部流量录进去、文件无界增长。所以耗尽前台预算后不是放弃,而是把收尾+ * 挪到后台定时重试:启动流程一秒都不多等,抓包却仍然有人负责关掉。+ *+ * **退出条件是"确认停止",不是"试够次数"**(review 抓到的第五条):上一版给后台重试也+ * 设了 12 次上限,于是 NetworkService 卡了一分多钟再恢复的情况下,抓包在无人收尾的状态+ * 下录满整个进程生命周期——正是这条兜底本来要防的事。现在改成节奏递增、次数不设上限:+ * 5s × 6 → 30s × 6 → 之后每 5 分钟一次,直到 stopLogging 成功或 currentlyLogging 变 false。+ * 定时器 unref,不拖住进程退出;长间隔阶段的成本可以忽略,而"抓包还在录"必须有人收。+ */+const NETLOG_BACKGROUND_STOP_SCHEDULE_MS: readonly number[] = [+ 5_000,+ 5_000,+ 5_000,+ 5_000,+ 5_000,+ 5_000,+ 30_000,+ 30_000,+ 30_000,+ 30_000,+ 30_000,+ 30_000,+];+const NETLOG_BACKGROUND_STOP_LONG_DELAY_MS = 300_000;++/**+ * 准备一个可以安全交给 `netLog.startLogging()` 的 netlog 文件路径。+ *+ * **日志目录拿不到(含空串)时返回 null,调用方必须跳过抓取**:initLogger 建目录失败时+ * getLogDir() 保持空串,`path.join('', name)` 会得到相对路径,于是 netlog 落到+ * process.cwd()——dev 下正是仓库工作区,既违反 credentials-and-local-storage.md 的落盘+ * 位置规则,还会在被 Git 跟踪的目录里留生成物。+ *+ * 路径安全靠**私有子目录 + 目录本身的准入检查 + 事后核对**,不是靠预创建文件+ * (review 连着抓了三轮,每轮都把窗口往外推了一层):+ * - 第一版用固定名 `endpoint-netlog.json`,别的进程能预置 symlink / FIFO;+ * - 第二版改成唯一名 + `'wx'` 独占创建,但 `wx` 只保护到 `closeSync` 返回 ——+ * Chromium 之后是**按路径名重新打开**的,这中间的 close-then-reopen 窗口里文件仍可+ * 被换成 symlink / FIFO,而 deadline 取消不了 Chromium 那边的文件系统副作用;+ * - 第三版用 `mkdtempSync` 开随机名 0700 目录,文件不预创建。但 0700 只保护目录的+ * **内容**,保护不了它在父目录里的那条**目录项**:对父目录有写权限的进程可以把这个+ * 子目录 rename 掉、在同名位置放一个 symlink,于是 Chromium 又被引到别处。+ *+ * 这一层的诚实结论:**只要 API 只能接受路径名(Electron 的 netLog 没有 fd 形态,Node+ * 也没有跨平台的 openat/O_PATH),同 uid 进程就没法用路径方案彻底排除**。所以这里按+ * "把能关的关掉 + 剩下的说清楚"处理:+ * 1. **准入检查**:日志目录必须是常规目录、属主是当前 uid、且 group/other 都不可写。+ * 这条把**别的用户**(以及被 chmod 放开的目录)整类攻击关在门外——那才是真正需要+ * 防的边界;不满足就直接跳过抓取,而不是硬着头皮抓。+ * 2. **不可预测的名字**:攻击者不能预置,只能现场抢 rename,难度与噪声都高一个量级。+ * 3. **事后核对**(verifyEndpointNetLogCapture):抓完后核对目录项还是我们创建的那个+ * inode、目标仍是常规文件;不符就丢弃这份产物并 warn,不把可能被换过的路径展示+ * 给用户或当证据用。+ * 同 uid 进程不在威胁模型内:它本来就能改 userData 里的配置、替换应用自己的文件、+ * attach 调试器——为它把整条诊断能力砍掉,换不来安全,只会把线上那次 ERR_FAILED 重新+ * 变成没有任何现场证据的失败。+ *+ * 每次准备前先清掉本前缀的旧产物(旧目录 + 两个历史版本留下的固定名/唯一名文件):+ * 唯一名意味着不再自动覆盖同一份,不清理就会在日志目录里无界堆积。+ * 任何异常都返回 null(诊断是辅助,绝不能变成启动失败源)。+ */+/** 抓包产物的身份:file 给 netLog,dev/ino 用于抓完之后核对目录项没被换过。 */+export interface PreparedNetLogCapture {+ file: string;+ dirDev: number;+ dirIno: number;+}++/**+ * 日志目录是否可以安全用来放抓包产物:必须是目录、属主是当前 uid、group/other 不可写。+ * 拿不到 uid(Windows 上 process.getuid 不存在)时跳过属主与权限位判断——那边的+ * ACL 语义与 POSIX 位不对应,用 mode 判会得出无意义的结论。+ */+function isLogDirSafeForCapture(dir: string): boolean {+ let stat: fs.Stats;+ try {+ stat = fs.lstatSync(dir);+ } catch {+ return false;+ }+ if (!stat.isDirectory()) return false;+ const getuid = process.getuid?.bind(process);+ if (!getuid) return true;+ if (stat.uid !== getuid()) return false;+ return (stat.mode & 0o022) === 0;+}++export function prepareEndpointNetLogFile(logDir: string | null): PreparedNetLogCapture | null {+ const dir = logDir?.trim();+ if (!dir) return null;+ if (!isLogDirSafeForCapture(dir)) {+ log.debug('netlog capture skipped: log directory is not private (%s)', dir);+ return null;+ }+ try {+ for (const name of fs.readdirSync(dir)) {+ if (!name.startsWith(ENDPOINT_NETLOG_PREFIX)) continue;+ try {+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });+ } catch {+ // 删不掉旧的不影响本次抓取,最多多留一份。+ }+ }+ } catch {+ // 目录列不出来(权限/竞态)不阻断:下面的 mkdtemp 仍然是安全的。+ }+ try {+ const captureDir = fs.mkdtempSync(path.join(dir, `${ENDPOINT_NETLOG_PREFIX}-`));+ const stat = fs.lstatSync(captureDir);+ return {+ file: path.join(captureDir, ENDPOINT_NETLOG_FILE_NAME),+ dirDev: stat.dev,+ dirIno: stat.ino,+ };+ } catch {+ return null;+ }+}++/**+ * 抓完之后核对产物:目录项必须还是我们创建的那个 inode,目标必须是常规文件。+ * 不符就返回 false,调用方丢弃这份产物——被换过的路径既不能当证据,也不该展示给用户。+ *+ * 已知局限(写清楚,不要当成密闭):这是**事后检测**,不是阻止——Chromium 那次写已经+ * 发生了;而且 inode 号会被文件系统回收复用(ext4 上 rm + mkdir 常常拿到同一个号),+ * 所以"号相同"并不等于"没被换过"。它稳定抓得住的是 symlink 与类型变化这类形状。+ * ino 拿不到(Windows 上可能是 0)时跳过 inode 比对,仍然检查目录与文件类型。+ */+export function verifyEndpointNetLogCapture(capture: PreparedNetLogCapture): boolean {+ try {+ const dirStat = fs.lstatSync(path.dirname(capture.file));+ if (!dirStat.isDirectory()) return false;+ if (capture.dirIno && dirStat.ino && (dirStat.ino !== capture.dirIno || dirStat.dev !== capture.dirDev)) {+ return false;+ }+ return fs.lstatSync(capture.file).isFile();+ } catch {+ return false;+ }+}++/** netLog 里本模块用到的两个方法(测试注入内存实现,不起 Electron)。 */+export interface NetLogLike {+ startLogging(file: string, options: { captureMode: 'default' }): Promise<void>;+ stopLogging(): Promise<unknown>;+ /**+ * Electron 的 `netLog.currentlyLogging`。用来在重试前确认"是不是其实已经停了",+ * 避免对着一个早已停止的抓包空转重试。拿不到(测试注入的实现没提供)就按"可能还在录"+ * 处理,继续重试——这个方向是安全的。+ */+ readonly currentlyLogging?: boolean;+}++/**+ * 围绕一次请求抓 netlog。成功返回文件路径。+ *+ * 异常语义(别看错,review 提过注释与实现不符):**start / stop 的异常在这里被降级**+ * ——start 失败返回 null,stop 失败只记日志并仍返回文件路径(那份 netlog 已经落盘,+ * 残缺也对排查有价值);而 `runWhileRecording()` 抛出的异常**照原样向上抛**,只保证+ * finally 里已经配对 stop 过。生产调用方 captureEndpointNetLog 外面裹了 try/catch,+ * 所以整条诊断链路对外仍然只表现为"有没有 netlog"。+ *+ * 三个 await 全部有界:start / stop 各 stepTimeoutMs,中间那次请求由调用方自带预算。+ *+ * **迟到成功的 start 必须补一次 stop**(review 抓到的第三条):withDeadline 只解除+ * 我们这边的等待,并不能取消 Electron 侧的操作。如果 startLogging 在超时之后才成功,+ * 一次**进程级**抓包就在无人收尾的情况下跑起来了——它会持续记录后续所有应用流量,+ * 让 endpoint-netlog.json 无界增长(顺带把与本次诊断无关的请求也录进去)。+ * 所以放弃等待时把收尾挂回原 promise 上,谁先到都保证有一次配对的 stop。+ */+export async function captureNetLogAround(+ netLogApi: NetLogLike,+ file: string,+ runWhileRecording: () => Promise<unknown>,+ stepTimeoutMs: number,+): Promise<string | null> {+ // stopped 只在**确认停止**后置位。上一版一进函数就置 true,于是 stopLogging 超时或+ // 抛错之后,后续路径(迟到成功的 start 补的那次收尾)全部直接 return —— 而+ // withDeadline 取消不了 Electron 侧的操作,一次没停下的**进程级**抓包会继续记录+ // 启动后的所有网络流量、文件无界增长(review 抓到的"收尾被锁死")。+ let stopped = false;+ let stopping = false;+ let backgroundStopScheduled = false;++ /** 一次有界的收尾尝试;确认停止(或抓包已经不在录)返回 true。 */+ const tryStop = async (label: string): Promise<boolean> => {+ if (netLogApi.currentlyLogging === false) {+ stopped = true;+ return true;+ }+ try {+ await withDeadline(netLogApi.stopLogging(), stepTimeoutMs, 'netlog-stop');+ stopped = true;+ return true;+ } catch (err) {+ log.debug('netlog stopLogging did not settle (%s): %s', label, String(err));+ return false;+ }+ };++ /**+ * 前台预算耗尽后的后台收尾:不 await,只保证"还有下一个触发点",而且这个触发点+ * **一直存在到确认停止为止**。定时器 unref,免得为了一次诊断抓包把进程退出拖住。+ */+ const scheduleBackgroundStop = (): void => {+ if (stopped || backgroundStopScheduled) return;+ backgroundStopScheduled = true;+ let attempt = 0;+ const delayFor = (nextAttempt: number): number =>+ NETLOG_BACKGROUND_STOP_SCHEDULE_MS[nextAttempt] ?? NETLOG_BACKGROUND_STOP_LONG_DELAY_MS;+ const tick = (): void => {+ if (stopped) return;+ attempt += 1;+ void tryStop(`background attempt ${attempt}`).then((ok) => {+ if (ok) {+ log.debug('netlog capture stopped by background retry (attempt %d)', attempt);+ return;+ }+ if (attempt === NETLOG_BACKGROUND_STOP_SCHEDULE_MS.length) {+ // 快节奏阶段用完还没停下:提醒一次,然后转长间隔继续盯,不放弃。+ log.warn(+ 'netlog capture still running after %d background stop attempts; keeping a slow retry alive',+ attempt,+ );+ }+ arm();+ });+ };+ const arm = (): void => {+ const timer = setTimeout(tick, delayFor(attempt));+ timer.unref?.();+ };+ arm();+ };++ const stopOnce = async (): Promise<void> => {+ if (stopped || stopping) return;+ stopping = true;+ try {+ for (let attempt = 0; attempt < NETLOG_STOP_ATTEMPTS; attempt += 1) {+ if (await tryStop(`attempt ${attempt + 1}/${NETLOG_STOP_ATTEMPTS}`)) return;+ }+ // 前台两次都没停下:抓包可能还在跑,这比"收尾慢"严重,按 warn 记而不是 debug,+ // 并把后续收尾交给后台重试(review 抓到:上一版到这里就彻底没有触发点了)。+ log.warn('netlog capture still running after foreground stop attempts; retrying in background');+ scheduleBackgroundStop();+ } finally {+ stopping = false;+ }+ };++ const startPromise = netLogApi.startLogging(file, { captureMode: 'default' });+ try {+ await withDeadline(startPromise, stepTimeoutMs, 'netlog-start');+ } catch (err) {+ // 放弃等待,但不放弃收尾:start 迟到成功时仍要把这次进程级抓包关掉。+ // startPromise 已 settle 时 then 会立即排上,所以不存在"标志位还没置好"的竞态。+ void startPromise.then(+ () => stopOnce(),+ () => {+ // start 本身失败 → 没有 capture 需要关闭;这里只是消化 rejection。+ },+ );+ log.debug('netlog capture failed: %s', String(err));+ return null;+ }++ try {+ await runWhileRecording();+ } finally {+ await stopOnce();+ }+ return file;+}++/**+ * 抓一份 netlog:在录制期间再打一次同样的清单请求,把 Chromium 内部对这次失败的+ * 判定(代理决策、socket、TLS、被谁取消)留在磁盘上。`ERR_FAILED` 这类通用码+ * 单看错误字符串永远得不到这些信息。+ */+async function captureEndpointNetLog(): Promise<string | null> {+ try {+ const capture = prepareEndpointNetLogFile(getLogDirSafe());+ if (!capture) {+ log.debug('netlog capture skipped: log directory unavailable or not private');+ return null;+ }+ const file = await captureNetLogAround(+ netLog,+ capture.file,+ () => fetchManifestViaCdn(DIAGNOSIS_ATTEMPT_TIMEOUT_MS),+ NETLOG_STEP_TIMEOUT_MS,+ );+ if (file && !verifyEndpointNetLogCapture(capture)) {+ // 目录项在交接期被换过:这份产物来源不明,既不展示也不当证据。+ log.warn('netlog capture discarded: capture directory changed during handoff');+ return null;+ }+ return file;+ } catch (err) {+ log.debug('netlog capture failed: %s', String(err));+ return null;+ }+}++/**+ * CDN 路径的诊断实现:分阶段探针摘要 + netlog 落盘路径。+ *+ * 两件事**并发**跑:探针只读网络栈状态、netlog 抓的是 Chromium 内部事件,互不干扰,+ * 串行只会让用户在阻断框前多等一截(墙钟从 ~15s 降到 ~11s)。+ */+async function diagnoseCdnManifestFetch(+ manifestUrl: string,+): Promise<{ summary: string | null; logPath: string | null }> {+ const [summary, netLogPath] = await Promise.all([+ probeEndpointFetch(manifestUrl, createDefaultProbes())+ .then((report) => {+ const line = formatEndpointFetchDiagnosis(report);+ log.warn('endpoint manifest fetch diagnosis: %s (%s)', line, manifestUrl);+ return line;+ })+ .catch((err: unknown) => {+ log.debug('endpoint fetch probe failed: %s', String(err));+ return null;+ }),+ captureEndpointNetLog(),+ ]);+ return { summary, logPath: netLogPath ?? getLogDirSafe() };+}++/**+ * 日志目录取值失败(logger 未初始化)时不要连带炸掉阻断流程。+ * **空串也算拿不到**:initLogger 建目录失败时 logRootDir 保持 '',原样用会变成相对路径。+ */+function getLogDirSafe(): string | null {+ try {+ return getLogDir().trim() || null;+ } catch {+ return null;+ }+}++/**+ * 读离线缓存并做与主路径完全相同的严格校验。任何一项不符都返回 null——+ * 弹框上就不会出现离线按钮,用户看到的仍是"重试 / 退出"。+ */+function loadOfflineManifestCandidate(+ manifestUrl: string,+ locale: EndpointManifestDialogLocale,+): OfflineManifestCandidate | null {+ let cached: ReturnType<typeof readEndpointManifestCache>;+ try {+ cached = readEndpointManifestCache(app.getPath('userData'));+ } catch {+ return null;+ }+ if (!cached) return null;+ if (cached.sourceUrl !== manifestUrl) {+ log.warn(+ 'cached endpoint manifest ignored: source changed (cached=%s current=%s)',+ cached.sourceUrl,+ manifestUrl,+ );+ return null;+ }+ // 磁盘内容不被信任:CDN 路径同样零放松(不开 allowHttp)。+ const parsed = resolveClientEndpointsStrict(cached.manifestText);+ if (!parsed.ok) {+ log.warn('cached endpoint manifest ignored: %s', parsed.reason);+ return null;+ }+ if (parsed.region !== null && parsed.region !== BUILD_AUTH_REGION) {+ log.warn(+ 'cached endpoint manifest ignored: region %s != build %s',+ parsed.region,+ BUILD_AUTH_REGION,+ );+ return null;+ }+ // 安全边界:这个文件在 userData、可被其他进程写,严格解析只管语法不管来源。+ // 按 CACHED_ENDPOINT_ORIGIN_POLICY 逐 key 校验来源域,拒掉攻击者自选的主机,也拒掉+ // 「换成另一区域的真实服务」——否则一份被改过的缓存 + 一次 CDN 不可达,就能让+ // authManager 把 access token 发到对方主机或对方区域。+ // 两条废弃做法都别改回去(理由见 endpointManifestCache.ts):从自举基址推导域(多段+ // 公共后缀上会放宽信任)、以及只给一个「两区域并集」的域清单(线上清单没有 region,+ // 并集等于允许跨区替换)。+ const untrusted = findUntrustedCachedEndpoint(parsed.endpoints, CACHED_ENDPOINT_ORIGIN_POLICY);+ if (untrusted) {+ log.error(+ 'cached endpoint manifest rejected: endpoint %s outside build-region domain %s (cross-region keys allow %s)',+ untrusted,+ CACHED_ENDPOINT_ORIGIN_POLICY.regionDomain,+ CACHED_ENDPOINT_ORIGIN_POLICY.crossRegionDomain,+ );+ return null;+ }+ return { parsed, savedAt: formatCacheSavedAt(cached.savedAt, locale) };+}++/**+ * 把本次**校验通过的清单原文**写入缓存,供下次网络失败时的离线出口使用。+ *+ * 存原文而不是按当前 CLIENT_ENDPOINT_KEYS 重新序列化:清单的发布模型是前向兼容的+ * ——先上新字段的清单,再发认识它的客户端;老客户端按"未知字段忽略"接受这份清单。+ * 如果缓存写的是重新序列化的结果,那些字段就在写入时被抹掉了,等客户端升级后从这份+ * 缓存离线启动,新端点会静默变成空串(review 抓到的正是这条)。+ * 原文是刚刚被同一个 parser 接受过的,所以"存原文会不会读不回来"不成立;真正需要+ * 防的是读取时用新 parser 判定不通过,那条路径已经 fail closed(不给离线按钮)。+ */+function cacheResolvedManifest(manifestUrl: string, manifestText: string): void {+ let written = false;+ try {+ written = writeEndpointManifestCache(app.getPath('userData'), {+ savedAt: new Date().toISOString(),+ sourceUrl: manifestUrl,+ manifestText,+ });+ } catch (err) {+ log.debug('endpoint manifest cache write threw: %s', String(err));+ }+ if (!written) log.warn('failed to persist endpoint manifest cache');+}+/*** 启动第一步(先于一切更新检查):阻断式解析清单(packaged=CDN;dev=本地文件,* --endpoints-cdn 时同 packaged)。返回 true = 可以继续启动;false = 用户在@@ -372,31 +1068,62 @@ export async function initClientEndpoints(): Promise<boolean> {// dev 下 app.getAppPath() = apps/desktop;packaged 不走 file 分支,该值无消费。repoRoot: path.resolve(app.getAppPath(), '..', '..'),});- const sourceLabel =- source.kind === 'cdn' ? `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}` : source.filePath;+ const manifestUrl = `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}`;+ const sourceLabel = source.kind === 'cdn' ? manifestUrl : source.filePath;+ const dialogLocale = resolveDialogLocale();+ // 自检:写死的区域域名必须覆盖本构建实际使用的两个自举基址。域名迁移时忘了更新+ // REGION_ENDPOINT_DOMAIN 的后果是离线出口 fail closed(新域名的缓存判不可信),+ // 这条 error 日志保证它不会静默失效到没人知道。不阻断启动:主路径不消费该清单。+ const knownRegionDomains = Object.values(REGION_ENDPOINT_DOMAIN);+ const untrustedBootstrap = findBootstrapHostOutsideTrustedDomains(+ [ENDPOINT_MANIFEST_BASE_URL, ENDPOINT_MANIFEST_PEER_BASE_URL],+ knownRegionDomains,+ );+ if (untrustedBootstrap) {+ log.error(+ 'bootstrap host %s is outside REGION_ENDPOINT_DOMAIN [%s]; offline start will be unavailable until the list is updated',+ untrustedBootstrap,+ knownRegionDomains.join(', '),+ );+ }// The resolver reports the parsed manifest through a callback. Keep it in a// box so TypeScript does not incorrectly conclude that the callback-owned// assignment is unreachable at the reads below.const resolvedManifestBox: {value: Extract<ParseClientEndpointManifestResult, { ok: true }> | null;- } = { value: null };+ fromCache: boolean;+ } = { value: null, fromCache: false };const endpoints = await resolveClientEndpointsBlocking({fetchManifest:source.kind === 'cdn'? fetchManifestViaCdn: () => Promise.resolve(readManifestFromFile(source.filePath)),- promptRetry: (reason) => promptRetryDialog(reason, sourceLabel),+ promptRetry: (context) => promptRetryDialog(context, sourceLabel, dialogLocale),exitApp: () => app.exit(1),allowHttp: source.kind === 'file',expectedRegionWhenPresent: BUILD_AUTH_REGION,- // dev 本地文件:读不到就是路径/内容配置错,不自动重试(见 BlockingResolveDeps)。+ // dev 本地文件:读不到就是路径/内容配置错,不自动重试、也按配置事故出文案+ // (见 BlockingResolveDeps 的 autoRetryDelaysMs / classifyFailure)。autoRetryDelaysMs: source.kind === 'cdn' ? undefined : [],- onResolved: (manifest) => {+ classifyFailure: source.kind === 'cdn' ? undefined : () => 'config',+ // 诊断与离线出口只对 CDN 路径有意义:file 模式的失败是本地路径/内容配置错,+ // 探测网络毫无信息量,拿远端缓存顶掉本地正本更是把 dev 的配置错藏起来。+ diagnose: source.kind === 'cdn' ? () => diagnoseCdnManifestFetch(manifestUrl) : undefined,+ loadOfflineManifest:+ source.kind === 'cdn'+ ? () => loadOfflineManifestCandidate(manifestUrl, dialogLocale)+ : undefined,+ onResolved: (manifest, origin, rawText) => {resolvedManifestBox.value = manifest;+ resolvedManifestBox.fromCache = origin === 'cache';+ if (origin === 'network' && source.kind === 'cdn' && rawText) {+ cacheResolvedManifest(manifestUrl, rawText);+ }},});if (endpoints === null) return false; // 用户选择退出,app.exit 已调用const resolvedManifest = resolvedManifestBox.value;+ startedFromCachedManifest = resolvedManifestBox.fromCache;resolvedEndpoints = endpoints;resolvedRegion = resolvedManifest?.region ?? null;// 老清单没有 region 元数据,但它一定来自构建区域的自举地址。只把这份端点@@ -406,7 +1133,11 @@ export async function initClientEndpoints(): Promise<boolean> {realmEndpointCache.set(activeSessionRealm, endpoints);log.info('resolved from %s (%s): auth=%s cdn=%s',- source.kind === 'cdn' ? 'remote manifest' : 'local manifest file',+ startedFromCachedManifest+ ? 'cached manifest (user-confirmed offline start)'+ : source.kind === 'cdn'+ ? 'remote manifest'+ : 'local manifest file',sourceLabel,endpoints.authApiBaseUrl,endpoints.cdnBaseUrl,@@ -414,6 +1145,14 @@ export async function initClientEndpoints(): Promise<boolean> {return true;}+/**+ * 本次启动是否用的是用户确认的离线缓存。需要联网的功能可以据此给出更准确的提示,+ * 而不是把"清单是旧的"表现成一堆各自失败的请求。+ */+export function isUsingCachedClientEndpoints(): boolean {+ return startedFromCachedManifest;+}+/*** 运行期端点读取入口(main 进程)。init 成功前调用 = 启动时序 bug,直接抛错* 炸出来(没有任何烘焙兜底可回落;--smoke-test 旁路只碰 localDb,不消费端点)。@@ -542,6 +1281,7 @@ export function resetClientEndpointsForTest(): void {resolvedEndpoints = resolved ?? null;resolvedRegion = resolved ? (options?.buildRegion ?? null) : null;+ startedFromCachedManifest = false;crossRealmOrgLoginEnabled = options?.crossRealmOrgLoginEnabled ?? BUILD_VARIANT !== 'dev';realmManifestBaseUrls =options?.realmManifestBaseUrls ?? DEFAULT_REALM_MANIFEST_BASE_URLS;diff --git a/apps/desktop/src/main/endpointFetchDiagnostics.ts b/apps/desktop/src/main/endpointFetchDiagnostics.tsnew file mode 100644index 0000000000..b83625457b--- /dev/null+++ b/apps/desktop/src/main/endpointFetchDiagnostics.ts@@ -0,0 +1,166 @@+/**+ * 端点清单拉取失败时的分阶段网络诊断。+ *+ * 为什么需要:清单拉取走 Electron `net.request`,它的错误只有一句+ * `net::ERR_*`,而最常见的 `ERR_FAILED` 是 Chromium 的**通用**失败码——DNS、系统代理、+ * TLS、被本机网络过滤扩展拦下,全都折叠成同一个字符串。现场只能看到+ * `fetch-failed:ERR_FAILED`,排查全靠猜(2026-07 实测:mac 上一台机器确定性复现,+ * 同一 URL curl 与裸 Electron 都是 200,而安装版毫秒级 ERR_FAILED)。+ *+ * 这里在弹阻断框**之前**把网络栈拆成三段独立探测:+ * - proxy:Chromium 自己解析出的代理决策(`session.resolveProxy`),区分「系统代理/+ * PAC 把请求引到了别处」与「直连」;+ * - dns:Node 的系统解析器(与 Chromium 内置解析器是两条路径,不一致本身就是线索);+ * - tcp:到 host:443 的裸连接,验证链路与端口是否真的可达。+ *+ * 三段都 ok 而 Chromium 仍报 ERR_FAILED,基本就指向「本机有东西在 socket 层拦这个+ * 进程」(网络过滤扩展 / 端点安全软件),这是单看错误码永远得不到的结论。+ *+ * 纯逻辑与 IO 分离:probeEndpointFetch 的三个探针由调用方注入(测试用内存 fake),+ * createDefaultProbes() 才碰 Electron 与 node:dns / node:net。+ */+import dns from 'node:dns/promises';+import { connect } from 'node:net';++import { session } from 'electron';++export interface EndpointFetchProbes {+ /** Chromium 对该 URL 的代理决策,形如 'DIRECT' / 'PROXY 127.0.0.1:7890'。 */+ resolveProxy(url: string): Promise<string>;+ lookupHost(hostname: string): Promise<string[]>;+ /** 建立并立即关闭一条 TCP 连接;失败即 reject。 */+ connectTcp(hostname: string, port: number, timeoutMs: number): Promise<void>;+}++export type ProbeOutcome<T> = ({ ok: true } & T) | { ok: false; error: string };++export interface EndpointFetchProbeReport {+ proxy: ProbeOutcome<{ value: string }>;+ dns: ProbeOutcome<{ addresses: string[] }>;+ tcp: ProbeOutcome<{ elapsedMs: number }>;+}++/** 探测总预算;弹框已经在等用户,这里不值得再耗更久。 */+const PROBE_TIMEOUT_MS = 4_000;++function describe(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ const code = (err as NodeJS.ErrnoException | null)?.code;+ // String() 归一:errno 的 code 在运行期也可能是数字(类型声明只写了 string),+ // 直接 .replace() 会让诊断自己抛异常。+ return String(code ?? message).replace(/\s+/g, ' ').trim().slice(0, 60) || 'unknown';+}++/**+ * 给一个 promise 套硬 deadline。**阻断路径上的每一个 await 都必须套**:系统 PAC /+ * 代理解析、OS DNS 查询、Chromium 的 netLog start/stop 都可能永不 settle,而这些代码+ * 跑在 app.ready 的阻断路径上——任何一个 pending 的 await 就能让阻断框(连同离线+ * 出口)永远不出现,表现为"启动卡住没反应",比原来只报 ERR_FAILED 更糟。+ *+ * 导出供 clientEndpointsService 的 netlog 抓取复用:同一条不变量只留一份实现,+ * 免得两处各写一个超时包装后行为悄悄分叉。+ */+export function withDeadline<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`${label}-timeout-${timeoutMs}ms`)),+ timeoutMs,+ );+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (err: unknown) => {+ clearTimeout(timer);+ reject(err instanceof Error ? err : new Error(String(err)));+ },+ );+ });+}++export function createDefaultProbes(): EndpointFetchProbes {+ return {+ // 静态 import electron(architecture-invariants.md §2:main 禁止运行时动态+ // import();单测用 vi.mock('electron') 提供 session,不用为它开动态 import 的口子)。+ resolveProxy(url) {+ return session.defaultSession.resolveProxy(url);+ },+ async lookupHost(hostname) {+ const records = await dns.lookup(hostname, { all: true });+ return records.map((record) => record.address);+ },+ connectTcp(hostname, port, timeoutMs) {+ return new Promise((resolve, reject) => {+ const socket = connect({ host: hostname, port });+ let settled = false;+ const finish = (err?: Error) => {+ if (settled) return;+ settled = true;+ socket.destroy();+ if (err) reject(err);+ else resolve();+ };+ socket.setTimeout(timeoutMs, () => finish(new Error('ETIMEDOUT')));+ socket.once('connect', () => finish());+ socket.once('error', (err) => finish(err));+ });+ },+ };+}++/**+ * 跑一轮分阶段探测。三段互不阻塞对方的失败——任何一段抛错都只记为该段失败,+ * 整个诊断永远不抛,绝不能把「排查辅助」变成新的启动失败源。+ * 三段并发且各自都有 timeoutMs 硬 deadline,所以整轮墙钟上界 ≈ timeoutMs。+ */+export async function probeEndpointFetch(+ url: string,+ probes: EndpointFetchProbes,+ timeoutMs: number = PROBE_TIMEOUT_MS,+): Promise<EndpointFetchProbeReport> {+ let hostname = '';+ let port = 443;+ try {+ const parsed = new URL(url);+ hostname = parsed.hostname;+ port = parsed.port ? Number(parsed.port) : parsed.protocol === 'http:' ? 80 : 443;+ } catch {+ return {+ proxy: { ok: false, error: 'invalid-url' },+ dns: { ok: false, error: 'invalid-url' },+ tcp: { ok: false, error: 'invalid-url' },+ };+ }++ const proxy = withDeadline(probes.resolveProxy(url), timeoutMs, 'proxy')+ .then((value) => ({ ok: true as const, value: value.trim() || 'unknown' }))+ .catch((err: unknown) => ({ ok: false as const, error: describe(err) }));++ const dnsProbe = withDeadline(probes.lookupHost(hostname), timeoutMs, 'dns')+ .then((addresses) => ({ ok: true as const, addresses }))+ .catch((err: unknown) => ({ ok: false as const, error: describe(err) }));++ const startedAt = Date.now();+ // connectTcp 自己也收 timeoutMs(socket.setTimeout),外层 deadline 是兜底:+ // 探针实现可以被注入,不能假设它一定遵守自己的超时。+ const tcp = withDeadline(probes.connectTcp(hostname, port, timeoutMs), timeoutMs, 'tcp')+ .then(() => ({ ok: true as const, elapsedMs: Date.now() - startedAt }))+ .catch((err: unknown) => ({ ok: false as const, error: describe(err) }));++ return {+ proxy: await proxy,+ dns: await dnsProbe,+ tcp: await tcp,+ };+}++/** 归一成一行短摘要,同时进日志和弹框 detail(用户截图即可定位)。 */+export function formatEndpointFetchDiagnosis(report: EndpointFetchProbeReport): string {+ const proxy = report.proxy.ok ? report.proxy.value : `fail(${report.proxy.error})`;+ const dnsPart = report.dns.ok+ ? `ok(${report.dns.addresses.slice(0, 2).join(',') || 'none'})`+ : `fail(${report.dns.error})`;+ const tcpPart = report.tcp.ok ? `ok(${report.tcp.elapsedMs}ms)` : `fail(${report.tcp.error})`;+ return `proxy=${proxy} dns=${dnsPart} tcp=${tcpPart}`;+}diff --git a/apps/desktop/src/main/endpointManifestCache.ts b/apps/desktop/src/main/endpointManifestCache.tsnew file mode 100644index 0000000000..24325e278a--- /dev/null+++ b/apps/desktop/src/main/endpointManifestCache.ts@@ -0,0 +1,322 @@+/**+ * 上次成功获取的端点清单在本地的落盘缓存。+ *+ * 语义边界(重要,勿放宽):这份缓存**只服务于用户在阻断框上显式选择的「用上次配置+ * 启动」**,不是自动回退。启动主路径仍然是「清单即唯一事实源」——拉不到就阻断,+ * 解析/校验不过就阻断,任何路径都不会静默拿缓存顶上。加它是因为原设计连+ * 「用户明知自己离线、只想打开应用看看本地对话」都没有出口,只能反复弹框或退出。+ *+ * 因此:+ * - 只在**不是本仓配置错**的失败上才允许作为出口(判定以 clientEndpointsService 的+ * classifyManifestFailure 为准:传输层失败 / 5xx / 非配置 4xx);JSON / schema /+ * 非法值 / region 不匹配、永久性 HTTP 这类配置事故照旧硬阻断(给出口等于帮用户+ * 绕过一次真实的配置错);+ * - 读回来的原文必须重新走同一套严格解析,磁盘内容不被信任;+ * - 记录写入时的清单地址,升级或换区导致自举基址变化时缓存直接作废;+ * - **端点主机必须落在写死的、按构建区域收紧的域内**(见 REGION_ENDPOINT_DOMAIN;+ * 只有 slack / telegram hook 这两个跨区共享服务例外)。+ *+ * 最后一条是安全边界,不是洁癖(review 抓到):这个文件位于 userData,可被其他进程+ * 写。严格解析只保证**语法**合法,不保证来源可信——攻击者写一份把 authApiBaseUrl+ * 指向自己 https 主机的缓存,再让清单 CDN 不可达,用户点「用上次配置启动」之后+ * authManager 就会把 access token 发到那台主机(凭证泄露)。真正的修法是服务端签名,+ * 但那是跨仓改动;在此之前用**编译期锚点**把爆炸半径收掉:允许的域是源码里写死的、+ * 且按构建区域收紧的(REGION_ENDPOINT_DOMAIN),任何 userData 写入都改不了它。+ *+ * 存储位置按 credentials-and-local-storage.md:Desktop 持久数据放+ * `app.getPath('userData')`。清单本身是 CDN 上公开可读的配置,不含任何凭证。+ * 路径由调用方注入(宿主决定目录),模块 import 时不产生任何文件系统副作用。+ */+import { randomBytes } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++import type { SupportedLocale } from '../shared/locale.js';++export const ENDPOINT_MANIFEST_CACHE_FILE_NAME = 'endpoint-manifest-cache.json';++/**+ * 缓存**文件**体积上限;超过即视为异常文件,不读也不写。+ *+ * 读写共用同一个常量,而且写路径校验的是**最终序列化结果**的字节数(review 抓到):+ * 上一版写路径只量 `manifestText`(≤64 KiB),落盘的却是把它当 JSON 字符串再包一层+ * (转义 + savedAt / sourceUrl + 缩进)。原文里全是需转义字符时,转义后体积会翻倍,+ * 于是存在一个区间——写检查放行、写成功了,读检查却按文件字节数拒掉,表现为+ * "明明写过缓存,下次离线按钮却点不亮"。两端量同一个东西就不会有这种自相矛盾。+ */+const MAX_CACHE_FILE_BYTES = 128 * 1024;++export interface CachedEndpointManifest {+ /** 写入时刻(ISO 8601)。 */+ savedAt: string;+ /** 写入时的清单地址(不含 cache-bust query),用于判定缓存是否仍然适用。 */+ sourceUrl: string;+ /** 清单原文,读回后仍需严格解析。 */+ manifestText: string;+}++function cacheFilePath(userDataDir: string): string {+ return path.join(userDataDir, ENDPOINT_MANIFEST_CACHE_FILE_NAME);+}++/**+ * 读一个**必须是常规文件**且不超过 maxBytes 的文本文件;不满足一律返回 null。+ *+ * 为什么不用 statSync + readFileSync(review 抓到):这个路径在 userData,别的进程能把它+ * 换成别的东西,而 `statSync` 会跟随 symlink、也不校验文件类型。symlink 到 `/dev/zero`+ * 会让 readFileSync 一直读到内存耗尽,FIFO 会让它**直接阻塞**——而这段代码跑在启动+ * 阻断路径上,阻塞等于启动卡死。+ *+ * 因此四道:+ * 1. `lstatSync` + `isFile()`:symlink / FIFO / 设备 / 目录全部在打开之前就拒掉+ * (lstat 不跟随 symlink,对 symlink 而言 isFile() 为 false);+ * 2. **打开本身带 `O_NONBLOCK`**,这样即使 lstat 与 open 之间路径刚被换成 FIFO,+ * `openSync` 也会立刻返回而不是等一个 writer(见下);+ * 3. 打开后用 `fstatSync` 复核类型与大小,并在两端 dev/ino 都可用时比对,**尽力**发现+ * lstat 与 open 之间路径被替换的情况;+ * 4. 只读 fstat 报告的字节数,不给"打开后又变大"留口子。+ *+ * 第 2 条是 review 抓到的剩余缺口:第 1 道只关掉了"打开之前就是 FIFO"这一半,TOCTOU+ * 窗口内被换上 FIFO 时,不带 O_NONBLOCK 的 `open(O_RDONLY)` 在 POSIX 下会**阻塞**到有+ * writer 为止——而这段跑在启动阻断路径上,阻塞意味着连弹框都出不来。带上 O_NONBLOCK+ * 后 open 立即成功,随后第 3 道的 `isFile()` 把这个 fd 拒掉。常规文件不受 O_NONBLOCK+ * 影响,所以正常路径行为不变。Windows 上没有这个标志(常量缺失),退回 `'r'`——那边也+ * 没有 FIFO 的 open 阻塞语义。+ *+ * 第 3 条的措辞是刻意收紧的(review 指出过上一版说法过头):`fstatSync` 只能证明"我手上+ * 这个 fd 是常规文件、多大",并不能证明 `openSync` 没有跟随一个在窗口内刚被换上的+ * symlink;dev/ino 比对能查出"打开的不是 lstat 看到的那个 inode",但 Node 没有跨平台的+ * `O_NOFOLLOW` 等价物,所以这不是密闭保证,只是让实现与声明一致。Windows 上 ino+ * 可能为 0,那种情况跳过比对。+ */+function openReadOnlyNonBlocking(file: string): number {+ const nonBlock = fs.constants.O_NONBLOCK;+ if (typeof nonBlock === 'number' && nonBlock !== 0) {+ return fs.openSync(file, fs.constants.O_RDONLY | nonBlock);+ }+ return fs.openSync(file, 'r');+}++function readRegularFileWithin(file: string, maxBytes: number): string | null {+ let fd: number | null = null;+ try {+ const pre = fs.lstatSync(file);+ if (!pre.isFile() || pre.size > maxBytes) return null;+ fd = openReadOnlyNonBlocking(file);+ const stat = fs.fstatSync(fd);+ if (!stat.isFile() || stat.size > maxBytes) return null;+ // best-effort:两端 ino 都拿得到才比对(Windows 上可能是 0)。+ if (pre.ino && stat.ino && (pre.ino !== stat.ino || pre.dev !== stat.dev)) return null;+ const buffer = Buffer.allocUnsafe(stat.size);+ const read = fs.readSync(fd, buffer, 0, stat.size, 0);+ return buffer.subarray(0, read).toString('utf8');+ } catch {+ return null;+ } finally {+ if (fd !== null) {+ try {+ fs.closeSync(fd);+ } catch {+ // 关闭失败无可挽回,也不该影响启动流程。+ }+ }+ }+}++/**+ * 读缓存。文件缺失、损坏、字段类型不对或体积异常都返回 null(缓存是可选辅助,+ * 任何异常都不该影响启动流程)。+ */+export function readEndpointManifestCache(userDataDir: string): CachedEndpointManifest | null {+ const file = cacheFilePath(userDataDir);+ const raw = readRegularFileWithin(file, MAX_CACHE_FILE_BYTES);+ if (raw === null) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;+ const record = parsed as Record<string, unknown>;+ const { savedAt, sourceUrl, manifestText } = record;+ if (+ typeof savedAt !== 'string' ||+ typeof sourceUrl !== 'string' ||+ typeof manifestText !== 'string' ||+ !savedAt.trim() ||+ !sourceUrl.trim() ||+ !manifestText.trim() ||+ Number.isNaN(Date.parse(savedAt))+ ) {+ return null;+ }+ return { savedAt, sourceUrl, manifestText };+}++/**+ * 写缓存(先写临时文件再 rename,避免断电/崩溃留下半份 JSON)。+ * 返回 false = 写失败;调用方只记日志,不阻断启动。+ *+ * 临时文件必须是**唯一名字 + 独占创建**(review 抓到:上一版用固定的+ * `<target>.tmp`,而读路径的常规文件校验管不到写路径):+ * - 别的进程在那个可预测路径上放一个 FIFO,`writeFileSync` 会**无限阻塞**。这段跑在+ * 清单解析**成功**之后、启动继续之前,阻塞等于启动卡死;+ * - 放一个 symlink,`writeFileSync` 会跟随并截断链接目标——等于把它变成一个任意+ * 文件写入原语。+ * `'wx'`(O_WRONLY|O_CREAT|O_EXCL)对已存在的路径直接报错而不是打开它,POSIX 下+ * O_CREAT|O_EXCL 遇到 symlink 也必定失败;随机后缀则保证不会被"先占位"卡住。+ * 最终的 renameSync 不跟随 symlink,所以 target 被换成 symlink 也只是被替换掉。+ */+export function writeEndpointManifestCache(+ userDataDir: string,+ entry: CachedEndpointManifest,+): boolean {+ // 量最终落盘的那份字节,并用同一份结果写入:读路径按文件字节数卡同一上限,+ // 两端量同一个东西才不会出现"写得进、读不回"。+ const payload = JSON.stringify(entry, null, 2);+ if (Buffer.byteLength(payload, 'utf8') > MAX_CACHE_FILE_BYTES) return false;+ const target = cacheFilePath(userDataDir);+ const tmp = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;+ let fd: number | null = null;+ try {+ fs.mkdirSync(userDataDir, { recursive: true });+ fd = fs.openSync(tmp, 'wx', 0o600);+ fs.writeFileSync(fd, payload, 'utf8');+ fs.closeSync(fd);+ fd = null;+ fs.renameSync(tmp, target);+ return true;+ } catch {+ if (fd !== null) {+ try {+ fs.closeSync(fd);+ } catch {+ // 关闭失败也要继续清理临时文件。+ }+ }+ try {+ fs.rmSync(tmp, { force: true });+ } catch {+ // 清理失败只会留下一个带随机后缀的临时文件,不影响下次写入。+ }+ return false;+ }+}++// ── 缓存端点的受信任域约束 ──────────────────────────────────────────────────++/**+ * **各构建区域的端点域**——离线缓存的信任锚点,写死在源码里。+ *+ * 为什么不从自举基址「去掉最左一段」推导(第一次 review 抓到):那样做在多段公共后缀上+ * 会**放宽**信任。`https://example.co.uk` 去掉一段得到 `co.uk`,于是任何人注册的+ * `attacker.co.uk` 都被判成可信。要正确推导注册域必须查公共后缀表(PSL);为一处启动期+ * 校验引入 PSL 数据不划算,而且推导本身并不比一份显式清单更可靠。+ *+ * 为什么必须**按区域分开**、不能给一个「两个域都信」的并集(第二次 review 抓到,这是+ * 上一版的真实漏洞):两份线上清单都**没有** `region` 字段,而 `region` 本身也是清单里+ * 的、未认证的数据。并集 + 缺失 region 的组合意味着——CN 构建下,攻击者只要伪造一份+ * sourceUrl 匹配 CN 的缓存、把 `authApiBaseUrl` 换成 Global 的**真实**服务+ * (`https://auth.cindy.app`),就能通过全部校验;用户点离线启动后,CN 的 token 会被+ * 发到 Global 区域。跨区 token 误发正是 auth-realm 设计里最要防的事。+ *+ * 这些常量是**安全常量**(性质同证书固定),不是"生产端点地址"——shared/endpoints.ts+ * 不保存业务端点是为了让端点能远程改;信任锚点恰恰**不能**远程改,否则它就不是锚点。+ *+ * 域名迁移时必须同步更新这里。忘了更新的后果是 fail closed——新域名的缓存被判不可信、+ * 离线按钮消失,并由 findBootstrapHostOutsideTrustedDomains 在启动日志里报出来;+ * 绝不会反过来继续信任别的东西。+ */+export const REGION_ENDPOINT_DOMAIN: Readonly<Record<'cn' | 'global', string>> = {+ cn: 'cindy.com.cn',+ global: 'cindy.app',+};++/**+ * 跨区共享的 hook 服务:两份清单(含 CN)都指向 cindy.app,所以只有这两个 key 允许+ * 落在 Global 域。**别往这里加 key** —— 每加一个就等于允许该端点跨区,而这个集合之外+ * 的所有端点(尤其 auth / device-link / oauth-broker / model-access / voice)必须锁在+ * 本构建区域,否则就回到上面说的跨区 token 误发。+ */+export const CROSS_REGION_ENDPOINT_KEYS: ReadonlySet<string> = new Set([+ 'slackHookWsUrl',+ 'telegramHookWsUrl',+]);++/** 缓存端点的来源策略:按 key 决定它允许落在哪个域。 */+export interface CachedEndpointOriginPolicy {+ /** 本构建区域的端点域(REGION_ENDPOINT_DOMAIN[buildRegion])。 */+ regionDomain: string;+ /** 跨区共享 hook 允许落在的域(固定是 Global 域)。 */+ crossRegionDomain: string;+}++/** 某个 key 允许落在的域。 */+function allowedDomainForKey(key: string, policy: CachedEndpointOriginPolicy): string {+ return CROSS_REGION_ENDPOINT_KEYS.has(key) ? policy.crossRegionDomain : policy.regionDomain;+}++function hostOf(rawUrl: string): string | null {+ try {+ return new URL(rawUrl).hostname.toLowerCase() || null;+ } catch {+ return null;+ }+}++/**+ * 自检:构建期烘焙的自举基址是否都落在受信任域内。返回第一个越界的主机(供日志),+ * 全部落在域内返回 null。+ *+ * 它把「写死的域名清单」和「构建实际使用的基址」钉在一起:域名迁移后如果忘了更新+ * 清单,这里会在启动日志里明确报出来,而不是让离线出口静默失效到没人知道为止。+ */+export function findBootstrapHostOutsideTrustedDomains(+ bootstrapBaseUrls: readonly string[],+ trustedDomains: readonly string[] = Object.values(REGION_ENDPOINT_DOMAIN),+): string | null {+ for (const baseUrl of bootstrapBaseUrls) {+ if (!baseUrl?.trim()) continue;+ const host = hostOf(baseUrl);+ if (!host) return baseUrl;+ if (!isHostWithinDomain(host, trustedDomains)) return host;+ }+ return null;+}++function isHostWithinDomain(host: string, domains: readonly string[]): boolean {+ return domains.some((domain) => host === domain || host.endsWith(`.${domain}`));+}++/**+ * 检查一份**缓存**端点集合是否全部落在受信任域内。返回第一个越界的 key(供日志),+ * 全部合规返回 null。空值跳过(缺失端点本就归一成空串)。+ *+ * 只用于缓存路径:网络路径的清单来自烘焙 https 基址、由 TLS 认证来源,不需要这层+ * 约束,加上反而会在合法改配置时误伤。+ */+export function findUntrustedCachedEndpoint(+ endpoints: Readonly<Record<string, string>>,+ policy: CachedEndpointOriginPolicy,+): string | null {+ if (!policy.regionDomain || !policy.crossRegionDomain) return 'origin-policy-unavailable';+ for (const [key, value] of Object.entries(endpoints)) {+ if (!value) continue;+ const host = hostOf(value);+ if (host === null) return key;+ if (!isHostWithinDomain(host, [allowedDomainForKey(key, policy)])) return key;+ }+ return null;+}++/** 缓存时间戳 → 弹框里给用户看的本地时间;解析不了就原样回显。 */+export function formatCacheSavedAt(savedAt: string, locale: SupportedLocale): string {+ const timestamp = Date.parse(savedAt);+ if (Number.isNaN(timestamp)) return savedAt;+ try {+ return new Date(timestamp).toLocaleString(locale);+ } catch {+ return new Date(timestamp).toISOString();+ }+}diff --git a/apps/desktop/src/main/endpointManifestDialogCopy.ts b/apps/desktop/src/main/endpointManifestDialogCopy.tsnew file mode 100644index 0000000000..c0840f7858--- /dev/null+++ b/apps/desktop/src/main/endpointManifestDialogCopy.ts@@ -0,0 +1,202 @@+/**+ * 启动期「端点清单获取失败」系统弹框的四语文案与内容组装。+ *+ * 这个框弹在 createWindow 之前,renderer 与 i18next 都还不存在,所以文案只能手写在+ * main 侧。原实现把中英两段直接拼在同一个 detail 里(「无法获取服务器配置 … Failed to+ * load the server endpoint manifest …」),用户看到的是一屏中英混排;这里改成按系统+ * 语言选一种语言输出。+ *+ * 单独成模块的理由与 applicationMenuLabels / oauthResultPage 相同:+ * `scripts/check-i18n-glossary.mjs` 只读 renderer 的 locale JSON,扫不到手写 catalog,+ * 抽出来才能被 __tests__/endpointManifestDialogCopyGlossary.test.ts 直接 import 扫描;+ * 也避免测试为了拿文案去 import 整个 Electron 主进程模块。+ *+ * 组装逻辑(buildEndpointManifestDialogContent)是纯函数:失败分类、按钮集合与+ * detail 排版都不碰 Electron,由 clientEndpointsService 负责真正弹框。+ */+import type { SupportedLocale } from '../shared/locale.js';++export type EndpointManifestDialogLocale = SupportedLocale;++/**+ * 失败分类。**判定规则的唯一事实源是 clientEndpointsService 的+ * classifyManifestFailure**;下面只是举例说明两类的意图,不要按举例反推边界。+ *+ * network = 拿不到清单但重试 / 离线出口有意义:传输层失败(超时 / DNS / 代理 / ERR_*)、+ * 5xx,以及 407 / 408 / 425 / 429 这类**非配置 4xx**(407 只可能来自代理,描述的是本机+ * 网络环境;其余是瞬时)。可重试、可能给离线出口。+ * config = 拿不到**可用**清单且重试无意义:正文内容不合法、region 不匹配、烘焙基址为空,+ * 以及**永久性** HTTP 3xx/4xx(路径 / 权限 / 部署错)。这一类不给离线出口。+ */+export type EndpointManifestFailureKind = 'network' | 'config';++/** 用户在弹框上做出的选择。 */+export type EndpointManifestDialogChoice = 'retry' | 'offline' | 'exit';++export interface EndpointManifestDialogCopy {+ title: string;+ networkBody: string;+ configBody: string;+ /** 以下四条均带 {{}} 占位,由 buildEndpointManifestDialogContent 填充。 */+ sourceLine: string;+ reasonLine: string;+ diagnosisLine: string;+ logLine: string;+ offlineHint: string;+ retryButton: string;+ offlineButton: string;+ quitButton: string;+}++export const ENDPOINT_MANIFEST_DIALOG_COPY: Record<+ EndpointManifestDialogLocale,+ EndpointManifestDialogCopy+> = {+ 'zh-CN': {+ title: '无法获取服务器配置',+ networkBody:+ 'Cindy 启动前需要先获取服务器配置,这次请求没有成功。请检查网络连接后重新获取。',+ configBody:+ '服务器没有返回可用的配置,重新获取不会改变结果。请稍后再试或联系我们。',+ sourceLine: '配置来源:{{source}}',+ reasonLine: '失败原因:{{reason}}',+ diagnosisLine: '网络诊断:{{diagnosis}}',+ logLine: '诊断日志位置:{{path}}',+ offlineHint:+ '也可以用上次成功获取的配置离线启动(获取于 {{savedAt}}),需要联网的功能会不可用。',+ retryButton: '重新获取配置',+ offlineButton: '用上次配置启动',+ quitButton: '退出 Cindy',+ },+ en: {+ title: 'Cannot load server configuration',+ networkBody:+ 'Cindy needs the server configuration before it can start, and this request did not go through. Check your network connection and fetch it again.',+ configBody:+ 'The server did not return a usable configuration, so fetching it again will not change the result. Try later or contact us.',+ sourceLine: 'Configuration source: {{source}}',+ reasonLine: 'Failure reason: {{reason}}',+ diagnosisLine: 'Network diagnosis: {{diagnosis}}',+ logLine: 'Diagnostic log location: {{path}}',+ offlineHint:+ 'You can also start offline with the configuration Cindy last fetched ({{savedAt}}). Features that need a network connection will be unavailable.',+ retryButton: 'Fetch Configuration',+ offlineButton: 'Use Last Configuration',+ quitButton: 'Quit Cindy',+ },+ ja: {+ title: 'サーバー設定を取得できません',+ networkBody:+ 'Cindy の起動にはサーバー設定の取得が必要ですが、今回のリクエストは失敗しました。ネットワーク接続を確認してから再取得してください。',+ configBody:+ 'サーバーから使用可能な設定を取得できませんでした。再取得しても結果は変わりません。時間をおいて試すか、お問い合わせください。',+ sourceLine: '設定の取得先: {{source}}',+ reasonLine: '失敗の原因: {{reason}}',+ diagnosisLine: 'ネットワーク診断: {{diagnosis}}',+ logLine: '診断ログの場所: {{path}}',+ offlineHint:+ '前回取得できた設定でオフライン起動することもできます(取得日時: {{savedAt}})。ネットワークが必要な機能は利用できません。',+ retryButton: '設定を再取得',+ offlineButton: '前回の設定で起動',+ quitButton: 'Cindy を終了',+ },+ ko: {+ title: '서버 설정을 가져올 수 없습니다',+ networkBody:+ 'Cindy를 시작하려면 먼저 서버 설정을 가져와야 하지만 이번 요청이 실패했습니다. 네트워크 연결을 확인한 후 다시 가져오세요.',+ configBody:+ '서버에서 사용할 수 있는 설정을 가져오지 못했습니다. 다시 가져와도 결과는 바뀌지 않습니다. 잠시 후 다시 시도하거나 문의해 주세요.',+ sourceLine: '설정 출처: {{source}}',+ reasonLine: '실패 원인: {{reason}}',+ diagnosisLine: '네트워크 진단: {{diagnosis}}',+ logLine: '진단 로그 위치: {{path}}',+ offlineHint:+ '마지막으로 가져온 설정으로 오프라인 시작할 수도 있습니다({{savedAt}} 기준). 네트워크가 필요한 기능은 사용할 수 없습니다.',+ retryButton: '설정 다시 가져오기',+ offlineButton: '지난 설정으로 시작',+ quitButton: 'Cindy 종료',+ },+};++export interface EndpointManifestDialogInput {+ locale: EndpointManifestDialogLocale;+ kind: EndpointManifestFailureKind;+ /** 错误码级别的短标识(fetch-failed:ERR_FAILED / invalid-json 等)。 */+ reason: string;+ /**+ * 清单来源:CDN 路径是 URL,dev 的 file 模式是本地文件路径。四语文案因此用中性的+ * 「来源 / source / 取得先 / 출처」,不写「URL / 地址」——否则 file 模式下名不副实。+ */+ source: string;+ /** 网络分阶段诊断摘要;没跑或跑失败时省略。 */+ diagnosis?: string | null;+ /**+ * 诊断产物位置:netlog 抓成功时是那个文件,失败时回落成日志目录——所以文案用+ * 「诊断日志位置」而不是「诊断日志」,不承诺一定是单个文件。+ */+ logPath?: string | null;+ /** 上次成功配置的获取时间(已格式化);有值即提供离线启动按钮。 */+ offlineSavedAt?: string | null;+}++export interface EndpointManifestDialogContent {+ /** showMessageBoxSync 的 message(macOS 上是加粗标题行)。 */+ message: string;+ detail: string;+ buttons: string[];+ defaultId: number;+ cancelId: number;+ /** 按钮下标 → 语义,避免调用方按 index 猜。 */+ choices: EndpointManifestDialogChoice[];+}++function fill(template: string, values: Record<string, string>): string {+ return template.replace(/\{\{(\w+)\}\}/g, (match, key: string) =>+ key in values ? values[key] : match,+ );+}++/**+ * 组装弹框内容。离线按钮只在 kind === 'network' 且确实有可用缓存时出现——配置内容+ * 非法时给离线出口等于让用户绕过一次真实的配置事故。+ */+export function buildEndpointManifestDialogContent(+ input: EndpointManifestDialogInput,+): EndpointManifestDialogContent {+ const copy = ENDPOINT_MANIFEST_DIALOG_COPY[input.locale];+ const offlineAvailable = input.kind === 'network' && Boolean(input.offlineSavedAt);++ const lines = [+ input.kind === 'network' ? copy.networkBody : copy.configBody,+ '',+ fill(copy.reasonLine, { reason: input.reason }),+ fill(copy.sourceLine, { source: input.source }),+ ];+ if (input.diagnosis) {+ lines.push(fill(copy.diagnosisLine, { diagnosis: input.diagnosis }));+ }+ if (input.logPath) {+ lines.push(fill(copy.logLine, { path: input.logPath }));+ }+ if (offlineAvailable) {+ lines.push('', fill(copy.offlineHint, { savedAt: input.offlineSavedAt ?? '' }));+ }++ const buttons = [copy.retryButton];+ const choices: EndpointManifestDialogChoice[] = ['retry'];+ if (offlineAvailable) {+ buttons.push(copy.offlineButton);+ choices.push('offline');+ }+ buttons.push(copy.quitButton);+ choices.push('exit');++ return {+ message: copy.title,+ detail: lines.join('\n'),+ buttons,+ defaultId: 0,+ cancelId: buttons.length - 1,+ choices,+ };+}diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.mdindex ddcd805696..6aa80b8469 100644--- a/docs/dev-rules/engineering-conventions.md+++ b/docs/dev-rules/engineering-conventions.md@@ -153,6 +153,9 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V`apps/mobile/src/__tests__/shadowCatalogGlossary.test.ts`- desktop:`src/main/applicationMenuLabels.ts`(macOS 原生菜单栏)→`apps/desktop/src/main/__tests__/applicationMenuLabels.test.ts`+ - desktop:`src/main/endpointManifestDialogCopy.ts`(启动期端点清单获取失败的系统弹框,+ 弹在 createWindow 之前、renderer 与 i18next 都还不存在)→+ `apps/desktop/src/main/__tests__/endpointManifestDialogCopyGlossary.test.ts`- desktop:`src/main/oauthResultPage.ts`(OAuth 回调结果页,渲染在系统浏览器里)→`apps/desktop/src/main/__tests__/oauthResultPageGlossary.test.ts`。它的文案分散在若干函数里且要传 provider / brand 实参,测试用固定占位实参求值后再扫;占位值不含diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.tsindex 17d672fffe..99e81a47c7 100644--- a/packages/maker-shared/src/clientEndpoints.ts+++ b/packages/maker-shared/src/clientEndpoints.ts@@ -11,9 +11,19 @@* - 拉不到 / JSON 或 schema 无法解析 / 非空 endpoint 值非法 → 启动阻断,* 宿主报错并提供重试;* - endpoint 字段允许按 region 缺失或留空,解析结果统一补成空串,不因此阻断启动;- * - **没有缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——任何本地兜底+ * - **没有自动缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——任何本地兜底* 都会把非空 CDN 配置错误静默掩盖成"部分端点漂移",这里要的是非法值立刻暴露;* desktop 与 mobile 正式包均遵守本条严格语义。+ * 唯一例外是 desktop 阻断框上**由用户显式点击**的离线出口(2026-07 追加,+ * 见 apps/desktop/src/main/endpointManifestCache.ts):只在**不是本仓配置错**的+ * 失败上出现——传输层失败(超时 / DNS / 代理 / ERR_*)、5xx,以及 407 / 408 / 425 /+ * 429 这类非配置 4xx(407 只可能来自代理,是本机网络环境;其余是瞬时)。+ * **判定以 desktop 的 classifyManifestFailure 为准**,别按这段注释里的举例反推+ * "4xx 一定没有离线按钮"。缓存里存的是当初校验通过的清单原文,读回后仍走本模块的+ * 同一套严格解析,清单地址变化即作废,且端点主机必须落在**源码写死的受信任域**内+ * (缓存文件在 userData、可被其他进程写,语法合法 ≠ 来源可信)。JSON / schema /+ * 非法值 / region 不匹配,以及**永久性** HTTP 3xx/4xx(路径 / 权限 / 部署错)这类+ * 配置事故照旧硬阻断——本模块的解析语义一字未放松,宿主也不得据此新增任何自动回退。* - 客户端只烘焙 CN/Global 两份清单的 CDN 基址(自举与组织区域发现必需,* 且防"清单配错 CDN 把自己锁死");**更新/hotfix 链的 CDN base 也来自清单*** (cdnBaseUrl)