Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(auth): hotfix 不可达时通过备源与本地清单恢复登录 (#4719)

Dash52c21732746d
diff --git a/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts b/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts
index 741adb836b..f39bb18080 100644
--- a/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts
+++ b/apps/desktop/src/main/__tests__/endpointManifestCache.test.ts
@@ -58,6 +58,17 @@ const canSymlink = (() => {
})();
describe('endpointManifestCache', () => {
+ it('按区域独立写入且保留旧缓存,互不覆盖', () => {
+ const cn = { ...ENTRY, sourceUrl: 'https://hotfix.cindy.com.cn/cindy/endpoint.json' };
+ const global = { ...ENTRY, sourceUrl: 'https://hotfix.cindy.app/cindy/endpoint.json' };
+ expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);
+ expect(writeEndpointManifestCache(dir, cn, 'cn')).toBe(true);
+ expect(writeEndpointManifestCache(dir, global, 'global')).toBe(true);
+ expect(readEndpointManifestCache(dir, 'cn')).toEqual(cn);
+ expect(readEndpointManifestCache(dir, 'global')).toEqual(global);
+ expect(readEndpointManifestCache(dir)).toEqual(ENTRY);
+ });
+
it('写入后可原样读回', () => {
expect(writeEndpointManifestCache(dir, ENTRY)).toBe(true);
expect(readEndpointManifestCache(dir)).toEqual(ENTRY);
diff --git a/apps/desktop/src/main/__tests__/endpointManifestLoader.test.ts b/apps/desktop/src/main/__tests__/endpointManifestLoader.test.ts
new file mode 100644
index 0000000000..aea72dd8ee
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/endpointManifestLoader.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ getBundledEndpointManifest,
+ type EndpointManifestCacheEntry,
+ type ClientEndpointRegion,
+} from '@cindy/maker-shared/client-endpoints';
+import { resolveDesktopEndpointManifest } from '../endpointManifestLoader';
+
+const cache = vi.hoisted(() => new Map<string, EndpointManifestCacheEntry>());
+vi.mock('../endpointManifestCache', () => ({
+ readEndpointManifestCache: (_dir: string, region?: string) =>
+ cache.get(region ?? 'legacy') ?? null,
+ writeEndpointManifestCache: (
+ _dir: string,
+ entry: EndpointManifestCacheEntry,
+ region?: string,
+ ) => {
+ cache.set(region ?? 'legacy', entry);
+ return true;
+ },
+}));
+const base = (region: ClientEndpointRegion) =>
+ `https://hotfix.cindy.${region === 'cn' ? 'com.cn' : 'app'}/cindy`;
+const text = (region: ClientEndpointRegion) =>
+ getBundledEndpointManifest(region, `${base(region)}/endpoint.json`)!;
+const offline = async () => ({ ok: false as const, detail: 'ERR_CONNECTION_TIMED_OUT' });
+beforeEach(() => cache.clear());
+
+describe('desktop persistent regional discovery', () => {
+ it('migrates legacy cache by reading it only for its matching source and region', async () => {
+ const manifestText = JSON.stringify({
+ ...JSON.parse(text('cn')),
+ authApiBaseUrl: 'https://auth-next.cindy.com.cn',
+ });
+ cache.set('legacy', {
+ savedAt: new Date().toISOString(),
+ sourceUrl: `${base('cn')}/endpoint.json`,
+ manifestText,
+ });
+ expect(
+ await resolveDesktopEndpointManifest('/fake-user-data', 'cn', base('cn'), offline),
+ ).toMatchObject({ ok: true, source: 'cache', text: manifestText });
+ expect(
+ await resolveDesktopEndpointManifest('/fake-user-data', 'global', base('global'), offline),
+ ).toMatchObject({ ok: true, source: 'bundled', text: text('global') });
+ });
+
+ it('writes separate files and recovers either region after process memory is lost', async () => {
+ for (const region of ['cn', 'global'] as const) {
+ expect(
+ await resolveDesktopEndpointManifest('/fake-user-data', region, base(region), async () => ({
+ ok: true,
+ text: text(region),
+ })),
+ ).toMatchObject({ ok: true, source: 'network' });
+ }
+ expect([...cache.keys()].sort()).toEqual(['cn', 'global']);
+ for (const region of ['cn', 'global'] as const) {
+ expect(
+ await resolveDesktopEndpointManifest('/fake-user-data', region, base(region), offline),
+ ).toMatchObject({ ok: true, source: 'cache', text: text(region) });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/clientEndpointsService.ts b/apps/desktop/src/main/clientEndpointsService.ts
index 60a04eeb91..659b577ca2 100644
--- a/apps/desktop/src/main/clientEndpointsService.ts
+++ b/apps/desktop/src/main/clientEndpointsService.ts
@@ -6,20 +6,14 @@
* 语义是**在线清单优先 + 配置事故阻断**(2026-08 启动可靠性修订):
* app.ready 内、createWindow / 一切更新检查之前解析清单;endpoint 字段允许按
* region 缺失或留空,不会阻断启动;JSON / schema 无法解析或非空值非法时才弹系统
- * 错误框(重试 / 退出),用户不重试成功就不放行启动。CDN 传输失败在自动重试用尽后,
- * 若存在经过同一套严格校验的缓存则自动用完整缓存清单继续启动;没有缓存时仍阻断。
+ * 错误框(重试 / 退出),用户不重试成功就不放行启动。CDN 传输失败在短预算后,
+ * 依次使用受信任备用源、本区缓存或随包完整清单。自定义源不会回退到官方服务。
* 没有逐字段烘焙回退——一次启动只使用一份完整清单快照。
*
- * 柔性只有两处,都不绕过配置校验:
- * 1. 弹框**之前**的网络层自动重试(AUTO_RETRY_DELAYS_MS,只对拉取失败生效、
- * 不对解析/校验失败生效),用于自愈首启瞬时抖动;重试用尽仍失败照样阻断。
- * 2. **严格校验后的离线缓存出口**(2026-07 追加、2026-08 自动化):传输层失败且
- * 本地存有上次成功清单时,正式 CDN 启动路径自动用缓存继续;通用 resolver 仍可
- * 保留弹框上的「用上次配置启动」按钮。严格边界见
- * endpointManifestCache.ts:只有**传输层**失败给出口(JSON / schema / 非法值 /
- * region 不匹配,以及永久性 HTTP 3xx/4xx 这类配置事故照旧硬阻断——给出口等于
- * 帮用户绕过真实配置错,分类规则见 classifyManifestFailure),缓存存的是校验通过
- * 的原文、读回后重新走同一套严格解析,清单地址变化即作废。
+ * 启动与跨区恢复共用 endpointManifestLoader:主源/备用源各最多等待 2.5 秒;
+ * 网络失败才可使用缓存或随包快照,配置错误保持阻断。通用阻断 resolver 仍保留
+ * 旧的重试/手动离线依赖接口,生产通过 resolveManifest 注入统一发现策略。
+ * 缓存校验边界见共享 clientEndpointOrigins,存储见 endpointManifestCache。
*
* 传输层失败在弹框前还会跑一轮分阶段诊断(endpointFetchDiagnostics:代理决策 /
* DNS / TCP,每段各有硬 deadline——这段跑在阻断路径上,探针挂住等于启动卡死)
@@ -53,6 +47,9 @@ import { app, clipboard, dialog, ipcMain, net, netLog } from 'electron';
import {
resolveClientEndpointsStrict,
+ classifyEndpointManifestFailure,
+ type ResilientEndpointResult,
+ type EndpointManifestSource,
type ClientEndpointKey,
type ClientEndpointMap,
type ClientEndpointRegion,
@@ -68,10 +65,6 @@ import {
} from './endpointFetchDiagnostics';
import {
findBootstrapHostOutsideTrustedDomains,
- findUntrustedCachedEndpoint,
- formatCacheSavedAt,
- readEndpointManifestCache,
- writeEndpointManifestCache,
REGION_ENDPOINT_DOMAIN,
} from './endpointManifestCache';
import {
@@ -82,10 +75,14 @@ import {
type EndpointManifestDialogLocale,
type EndpointManifestFailureKind,
} from './endpointManifestDialogCopy';
+import { resolveDesktopEndpointManifest } from './endpointManifestLoader';
import { createLogger, getLogDir } from './logger';
import { ENDPOINT_MANIFEST_BASE_URL, ENDPOINT_MANIFEST_PEER_BASE_URL } from '../shared/endpoints';
import { resolvePreferredSystemLocale } from '../shared/locale';
-import { captureCindyVersionOriginEndpoints, getCindyVersionEndpointOverride } from './cindy-make/versionRuntimeIdentity.js';
+import {
+ captureCindyVersionOriginEndpoints,
+ getCindyVersionEndpointOverride,
+} from './cindy-make/versionRuntimeIdentity.js';
const log = createLogger('clientEndpoints');
@@ -103,19 +100,6 @@ 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;
@@ -129,8 +113,8 @@ const ATTEMPT_TIMEOUT_MS = 15_000;
* 弹阻断框,用户重启一次或点一下「重试」就正常 = 典型瞬时失败,却被呈现成
* "无法获取服务器配置"。
*
- * 这里补的只是"瞬时抖动自愈",不是静默降级:预算用尽仍失败照样弹框阻断,
- * 依然没有缓存回退、没有烘焙兜底。**只有网络层失败(fetch 未拿到正文)消耗
+ * 通用 resolver 的重试策略保留兼容;生产路径使用共享的短预算发现策略。
+ * **只有网络层失败(fetch 未拿到正文)消耗
* 预算**;JSON / schema / 非法值这类配置事故重试同一份内容没有意义,立刻弹框。
*
* 时长权衡:真断网时 DNS 立即失败,约 3.2s 就会弹框;最坏情况(三次都卡到
@@ -318,11 +302,10 @@ function defaultSleep(ms: number): Promise<void> {
* 约 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);
+ return classifyEndpointManifestFailure(`fetch-failed:http-${status}`) === 'config';
}
/**
@@ -336,12 +319,7 @@ function isPermanentHttpStatus(status: number): boolean {
* - 烘焙基址为空是打包事故,同样 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';
+ return classifyEndpointManifestFailure(reason);
}
/** 弹框需要的全部上下文;由阻断循环组装,宿主只负责渲染与取回选择。 */
@@ -366,6 +344,8 @@ export interface OfflineManifestCandidate {
/** 阻断循环的依赖注入面(规则 14:测试用内存 harness 驱动,不起 Electron)。 */
export interface BlockingResolveDeps {
fetchManifest(timeoutMs: number): Promise<ManifestFetchResult>;
+ /** Production startup and cross-region recovery share this resolution policy. */
+ resolveManifest?(): Promise<ResilientEndpointResult>;
/** 拉取/校验失败时问用户;生产实现是系统模态提示框。 */
promptRetry(context: ManifestPromptContext): EndpointManifestDialogChoice;
exitApp(): void;
@@ -415,7 +395,7 @@ export interface BlockingResolveDeps {
*/
onResolved?(
manifest: Extract<ParseClientEndpointManifestResult, { ok: true }>,
- source: 'network' | 'cache',
+ source: EndpointManifestSource,
rawText?: string,
): void;
}
@@ -441,6 +421,15 @@ export async function resolveClientEndpointsBlocking(
for (;;) {
let reason = 'fetch-failed';
for (let attempt = 0; ; attempt += 1) {
+ if (deps.resolveManifest) {
+ const result = await deps.resolveManifest();
+ if (result.ok) {
+ deps.onResolved?.(result.parsed, result.source, result.text);
+ return result.parsed.endpoints;
+ }
+ reason = result.reason;
+ break;
+ }
let fetched: ManifestFetchResult;
try {
fetched = await deps.fetchManifest(timeoutMs);
@@ -995,87 +984,6 @@ function getLogDirSafe(): string | 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 = 用户在
@@ -1085,15 +993,17 @@ export async function initClientEndpoints(): Promise<boolean> {
// A verified Make profile carries the original Dev's public service configuration.
// Ordinary packaged apps still use CDN; ambient file/env overrides cannot enable this path.
const versionSnapshot = getCindyVersionEndpointOverride();
- const source: EndpointSource = versionSnapshot ? { kind: 'file', filePath: 'Cindy Make' } : resolveEndpointSource({
- isPackaged: app.isPackaged,
- env: {
- XDT_ENDPOINTS_CDN: process.env.XDT_ENDPOINTS_CDN,
- XDT_ENDPOINT_MANIFEST_FILE: process.env.XDT_ENDPOINT_MANIFEST_FILE,
- },
- // dev 下 app.getAppPath() = apps/desktop;packaged 不走 file 分支,该值无消费。
- repoRoot: path.resolve(app.getAppPath(), '..', '..'),
- });
+ const source: EndpointSource = versionSnapshot
+ ? { kind: 'file', filePath: 'Cindy Make' }
+ : resolveEndpointSource({
+ isPackaged: app.isPackaged,
+ env: {
+ XDT_ENDPOINTS_CDN: process.env.XDT_ENDPOINTS_CDN,
+ XDT_ENDPOINT_MANIFEST_FILE: process.env.XDT_ENDPOINT_MANIFEST_FILE,
+ },
+ // dev 下 app.getAppPath() = apps/desktop;packaged 不走 file 分支,该值无消费。
+ repoRoot: path.resolve(app.getAppPath(), '..', '..'),
+ });
const manifestUrl = `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}`;
const sourceLabel = source.kind === 'cdn' ? manifestUrl : source.filePath;
const dialogLocale = resolveDialogLocale();
@@ -1120,10 +1030,21 @@ export async function initClientEndpoints(): Promise<boolean> {
fromCache: boolean;
} = { value: null, fromCache: false };
const endpoints = await resolveClientEndpointsBlocking({
- fetchManifest:
- versionSnapshot ? () => Promise.resolve({ ok: true as const, text: versionSnapshot.manifestText }) : source.kind === 'cdn'
+ fetchManifest: versionSnapshot
+ ? () => Promise.resolve({ ok: true as const, text: versionSnapshot.manifestText })
+ : source.kind === 'cdn'
? fetchManifestViaCdn
: () => Promise.resolve(readManifestFromFile(source.filePath)),
+ resolveManifest:
+ source.kind === 'cdn'
+ ? () =>
+ resolveDesktopEndpointManifest(
+ app.getPath('userData'),
+ BUILD_AUTH_REGION,
+ ENDPOINT_MANIFEST_BASE_URL,
+ (url, timeoutMs) => fetchTextViaNet(`${url}?t=${Date.now()}`, timeoutMs),
+ )
+ : undefined,
promptRetry: (context) => promptRetryDialog(context, sourceLabel, dialogLocale),
exitApp: () => app.exit(1),
allowHttp: source.kind === 'file',
@@ -1135,17 +1056,10 @@ export async function initClientEndpoints(): Promise<boolean> {
// 诊断与离线出口只对 CDN 路径有意义:file 模式的失败是本地路径/内容配置错,
// 探测网络毫无信息量,拿远端缓存顶掉本地正本更是把 dev 的配置错藏起来。
diagnose: source.kind === 'cdn' ? () => diagnoseCdnManifestFetch(manifestUrl) : undefined,
- loadOfflineManifest:
- source.kind === 'cdn'
- ? () => loadOfflineManifestCandidate(manifestUrl, dialogLocale)
- : undefined,
- offlineFallbackMode: source.kind === 'cdn' ? 'automatic' : 'prompt',
- onResolved: (manifest, origin, rawText) => {
+ onResolved: (manifest, origin) => {
resolvedManifestBox.value = manifest;
- resolvedManifestBox.fromCache = origin === 'cache';
- if (origin === 'network' && source.kind === 'cdn' && rawText) {
- cacheResolvedManifest(manifestUrl, rawText);
- }
+ resolvedManifestBox.fromCache = origin === 'cache' || origin === 'bundled';
+ log.info('endpoint discovery source=%s region=%s', origin, BUILD_AUTH_REGION);
},
});
if (endpoints === null) return false; // 用户选择退出,app.exit 已调用
@@ -1162,11 +1076,20 @@ export async function initClientEndpoints(): Promise<boolean> {
// 另一 realm 会重新拉线上清单,把本地服务悄悄替换掉。仅对明确的 local + file
// 启动把同一份清单固定到两个 realm;remote/CDN 与普通文件覆写仍保持区域隔离。
const pinLocalEndpointsToAllRealms =
- versionSnapshot?.local === true || (!app.isPackaged && process.env.XDT_DESKTOP_DEV_MODE === 'local' && source.kind === 'file');
- captureCindyVersionOriginEndpoints(source.kind === 'file' ? {
- manifestText: JSON.stringify({ schemaVersion: 1, region: resolvedRegion ?? BUILD_AUTH_REGION, ...endpoints }),
- local: pinLocalEndpointsToAllRealms,
- } : undefined);
+ versionSnapshot?.local === true ||
+ (!app.isPackaged && process.env.XDT_DESKTOP_DEV_MODE === 'local' && source.kind === 'file');
+ captureCindyVersionOriginEndpoints(
+ source.kind === 'file'
+ ? {
+ manifestText: JSON.stringify({
+ schemaVersion: 1,
+ region: resolvedRegion ?? BUILD_AUTH_REGION,
+ ...endpoints,
+ }),
+ local: pinLocalEndpointsToAllRealms,
+ }
+ : undefined,
+ );
if (pinLocalEndpointsToAllRealms) {
realmEndpointCache.set('cn', endpoints);
realmEndpointCache.set('global', endpoints);
@@ -1197,7 +1120,7 @@ export function isUsingCachedClientEndpoints(): boolean {
/**
* 运行期端点读取入口(main 进程)。init 成功前调用 = 启动时序 bug,直接抛错
- * 炸出来(没有任何烘焙兜底可回落;--smoke-test 旁路只碰 localDb,不消费端点)。
+ * 炸出来(随包兜底也必须先经过启动解析;--smoke-test 旁路不消费端点)。
*/
export function getClientEndpoint(key: ClientEndpointKey): string {
if (resolvedEndpoints === null) {
@@ -1252,22 +1175,16 @@ export async function loadClientEndpointsForRealm(
if (!baseUrl) {
throw new Error('realm-manifest-url-unavailable');
}
- const fetched = await fetchTextViaNet(
- `${baseUrl}/${MANIFEST_FILE_NAME}?t=${Date.now()}`,
- ATTEMPT_TIMEOUT_MS,
+ const result = await resolveDesktopEndpointManifest(
+ app.getPath('userData'),
+ region,
+ baseUrl,
+ (url, timeoutMs) => fetchTextViaNet(`${url}?t=${Date.now()}`, timeoutMs),
);
- if (!fetched.ok) {
- throw new Error(fetchFailedReason(fetched.detail));
- }
- const parsed = resolveClientEndpointsStrict(fetched.text);
- if (!parsed.ok) {
- throw new Error(parsed.reason);
- }
- if (parsed.region !== null && parsed.region !== region) {
- throw new Error(`region-mismatch:${region}:${parsed.region}`);
- }
- realmEndpointCache.set(region, parsed.endpoints);
- return parsed.endpoints;
+ if (!result.ok) throw new Error(result.reason);
+ log.info('realm endpoint discovery source=%s region=%s', result.source, region);
+ realmEndpointCache.set(region, result.parsed.endpoints);
+ return result.parsed.endpoints;
}
export function getClientEndpointForRealm(
diff --git a/apps/desktop/src/main/endpointManifestCache.ts b/apps/desktop/src/main/endpointManifestCache.ts
index 0bc020d97a..6a01bd51af 100644
--- a/apps/desktop/src/main/endpointManifestCache.ts
+++ b/apps/desktop/src/main/endpointManifestCache.ts
@@ -55,8 +55,11 @@ export interface CachedEndpointManifest {
manifestText: string;
}
-function cacheFilePath(userDataDir: string): string {
- return path.join(userDataDir, ENDPOINT_MANIFEST_CACHE_FILE_NAME);
+function cacheFilePath(userDataDir: string, region?: 'cn' | 'global'): string {
+ return path.join(
+ userDataDir,
+ region ? `endpoint-manifest-cache.${region}.json` : ENDPOINT_MANIFEST_CACHE_FILE_NAME,
+ );
}
/**
@@ -127,8 +130,11 @@ function readRegularFileWithin(file: string, maxBytes: number): string | null {
* 读缓存。文件缺失、损坏、字段类型不对或体积异常都返回 null(缓存是可选辅助,
* 任何异常都不该影响启动流程)。
*/
-export function readEndpointManifestCache(userDataDir: string): CachedEndpointManifest | null {
- const file = cacheFilePath(userDataDir);
+export function readEndpointManifestCache(
+ userDataDir: string,
+ region?: 'cn' | 'global',
+): CachedEndpointManifest | null {
+ const file = cacheFilePath(userDataDir, region);
const raw = readRegularFileWithin(file, MAX_CACHE_FILE_BYTES);
if (raw === null) return null;
let parsed: unknown;
@@ -171,12 +177,13 @@ export function readEndpointManifestCache(userDataDir: string): CachedEndpointMa
export function writeEndpointManifestCache(
userDataDir: string,
entry: CachedEndpointManifest,
+ region?: 'cn' | 'global',
): boolean {
// 量最终落盘的那份字节,并用同一份结果写入:读路径按文件字节数卡同一上限,
// 两端量同一个东西才不会出现"写得进、读不回"。
const payload = JSON.stringify(entry, null, 2);
if (Buffer.byteLength(payload, 'utf8') > MAX_CACHE_FILE_BYTES) return false;
- const target = cacheFilePath(userDataDir);
+ const target = cacheFilePath(userDataDir, region);
const tmp = `${target}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
let fd: number | null = null;
try {
@@ -204,112 +211,14 @@ export function writeEndpointManifestCache(
}
}
-// ── 缓存端点的受信任域约束 ──────────────────────────────────────────────────
-
-/**
- * **各构建区域的端点域**——离线缓存的信任锚点,写死在源码里。
- *
- * 为什么不从自举基址「去掉最左一段」推导(第一次 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,所以只有这几个 hook key
- * 允许落在 Global 域。**别往这里加 key** —— 每加一个就等于允许该端点跨区,而这个集合之外
- * 的所有端点(尤其 auth / device-link / oauth-broker / model-access / voice)必须锁在
- * 本构建区域,否则就回到上面说的跨区 token 误发。
- */
-export const CROSS_REGION_ENDPOINT_KEYS: ReadonlySet<string> = new Set([
- 'slackHookWsUrl',
- 'telegramHookWsUrl',
- 'xHookWsUrl',
-]);
-
-/** 缓存端点的来源策略:按 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;
-}
+// Shared by desktop and mobile; keep these exports for existing desktop callers.
+export {
+ REGION_ENDPOINT_DOMAIN,
+ CROSS_REGION_ENDPOINT_KEYS,
+ findBootstrapHostOutsideTrustedDomains,
+ findUntrustedCachedEndpoint,
+ type CachedEndpointOriginPolicy,
+} from '@cindy/maker-shared/client-endpoints';
/** 缓存时间戳 → 弹框里给用户看的本地时间;解析不了就原样回显。 */
export function formatCacheSavedAt(savedAt: string, locale: SupportedLocale): string {
diff --git a/apps/desktop/src/main/endpointManifestLoader.ts b/apps/desktop/src/main/endpointManifestLoader.ts
new file mode 100644
index 0000000000..800c23da11
--- /dev/null
+++ b/apps/desktop/src/main/endpointManifestLoader.ts
@@ -0,0 +1,28 @@
+import {
+ readTrustedEndpointCache,
+ resolveResilientEndpointManifest,
+ type ClientEndpointRegion,
+ type ResilientEndpointDeps,
+} from '@cindy/maker-shared/client-endpoints';
+import { readEndpointManifestCache, writeEndpointManifestCache } from './endpointManifestCache';
+
+/** Keep the legacy build cache readable; each realm now writes its own atomic file. */
+export function resolveDesktopEndpointManifest(
+ userDataDir: string,
+ region: ClientEndpointRegion,
+ baseUrl: string,
+ fetchText: ResilientEndpointDeps['fetchText'],
+) {
+ const sourceUrl = baseUrl ? `${baseUrl.replace(/\/+$/, '')}/endpoint.json` : '';
+ return resolveResilientEndpointManifest({
+ region,
+ sourceUrl,
+ fetchText,
+ readCache: () => {
+ const scoped = readEndpointManifestCache(userDataDir, region);
+ if (readTrustedEndpointCache(scoped, region, sourceUrl)) return scoped;
+ return readEndpointManifestCache(userDataDir);
+ },
+ writeCache: (entry) => writeEndpointManifestCache(userDataDir, entry, region),
+ });
+}
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index e5dbd505e2..c543a10992 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -3,6 +3,8 @@ const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, '../..');
+// Shared endpoint discovery bundles the public manifests from the repository config directory.
+config.watchFolders = [...config.watchFolders, path.join(workspaceRoot, 'config')];
// Keep upload routing build-time-only, with the desktop validator as the single configuration source.
// Missing config is allowed for local/open-source builds; malformed or cross-region config is not.
const { mobileLogUploadBuildEnv, mobileLogUploadConfigRequired } = require('../../scripts/shared/log-upload-build-env.mjs');
diff --git a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
index dac7c81c42..c6ec80cd9c 100644
--- a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
+++ b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
@@ -2,14 +2,18 @@
* 远程端点清单启动解析(clientEndpointStartup)+ env live binding 回写单测。
*
* 关键覆盖:
- * - 正式包只认 CDN 清单;字段缺失/空白不阻断,拉取失败或清单非法仍阻断;
- * - 不使用包内 endpoint.json 做字段合并或整份回退;
+ * - 自定义源无官方随包兜底;字段缺失/空白不阻断,配置错误仍阻断;
+ * - 官方源的缓存/随包恢复见 endpointManifestLoader.test.ts,不做字段合并;
* - applyResolvedClientEndpoints 重赋值后,跨模块 ESM live binding 立即可见。
*/
import { describe, expect, it, vi } from 'vitest';
import type { ManifestFetchResult } from '@/config/clientEndpointStartup';
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: { getItem: async () => null, setItem: async () => undefined },
+}));
+
type FetchManifest = (timeoutMs: number) => Promise<ManifestFetchResult>;
async function freshModules() {
diff --git a/apps/mobile/src/__tests__/endpointManifestLoader.test.ts b/apps/mobile/src/__tests__/endpointManifestLoader.test.ts
new file mode 100644
index 0000000000..aa7888d6a4
--- /dev/null
+++ b/apps/mobile/src/__tests__/endpointManifestLoader.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getBundledEndpointManifest } from '@cindy/maker-shared/client-endpoints';
+
+const storage = vi.hoisted(() => new Map<string, string>());
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: {
+ getItem: async (key: string) => storage.get(key) ?? null,
+ setItem: async (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ },
+}));
+const cnBase = 'https://hotfix.cindy.com.cn/cindy';
+const globalBase = 'https://hotfix.cindy.app/cindy';
+const cnText = getBundledEndpointManifest('cn', `${cnBase}/endpoint.json`)!;
+const globalText = getBundledEndpointManifest(
+ 'global',
+ `${globalBase}/endpoint.json`,
+)!;
+
+beforeEach(() => {
+ storage.clear();
+ vi.resetModules();
+ vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', 'global');
+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL', globalBase);
+ vi.stubEnv('EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL', cnBase);
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+});
+
+describe('mobile endpoint startup and recovery', () => {
+ it.each(['cn', 'global'] as const)('uses the compiled GitHub backup for %s when hotfix fails', async (region) => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (!url.startsWith('https://raw.githubusercontent.com/')) throw new TypeError('hotfix unavailable');
+ return { ok: true, text: async () => region === 'cn' ? cnText : globalText };
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const { resolveMobileEndpointManifest } = await import('@/config/endpointManifestLoader');
+ const result = await resolveMobileEndpointManifest(region, region === 'cn' ? cnBase : globalBase);
+ expect(result).toMatchObject({ ok: true, source: 'mirror', text: region === 'cn' ? cnText : globalText });
+ const filename = region === 'cn' ? 'endpoint.json' : 'endpoint.global.json';
+ expect(fetchMock.mock.calls[1][0]).toContain(
+ `https://raw.githubusercontent.com/makecindy/cindy/main/config/${filename}?`,
+ );
+ expect(storage.size).toBe(1);
+ });
+
+ it('persists both regions, survives module reload, and restores CN endpoints without changing the Global update identity', async () => {
+ const fetchMock = vi.fn(async (url: string) => ({
+ ok: true,
+ text: async () => (url.startsWith(cnBase) ? cnText : globalText),
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ let startup = await import('@/config/clientEndpointStartup');
+ let env = await import('@/config/env');
+ expect(await startup.runStartupEndpointResolve()).toEqual({
+ ok: true,
+ source: 'cdn',
+ });
+ await env.loadMobileEndpointsForRealm('cn');
+ expect(storage.size).toBe(2);
+ vi.resetModules();
+ fetchMock.mockRejectedValue(new TypeError('Network request failed'));
+ startup = await import('@/config/clientEndpointStartup');
+ env = await import('@/config/env');
+ expect(await startup.runStartupEndpointResolve()).toEqual({
+ ok: true,
+ source: 'cache',
+ });
+ await env.loadMobileEndpointsForRealm('cn');
+ const updateEndpoint = env.OTA_SERVER_BASE_URL;
+ env.activateMobileSessionRealm('cn');
+ expect(env.AUTH_API_BASE_URL).toBe('https://auth.cindy.com.cn');
+ expect(env.getActiveMobileSessionRealm()).toBe('cn');
+ expect(env.BUILD_AUTH_REGION).toBe('global');
+ expect(env.OTA_SERVER_BASE_URL).toBe(updateEndpoint);
+ env.resetMobileSessionRealm();
+ expect(env.AUTH_API_BASE_URL).toBe('https://auth.cindy.app');
+ });
+
+ it('first install can start and load the other region while hotfix is unreachable', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('offline')));
+ const startup = await import('@/config/clientEndpointStartup');
+ const env = await import('@/config/env');
+ expect(await startup.runStartupEndpointResolve()).toEqual({
+ ok: true,
+ source: 'bundled',
+ });
+ expect(await env.loadMobileEndpointsForRealm('cn')).toMatchObject({
+ authApiBaseUrl: 'https://auth.cindy.com.cn',
+ });
+ expect(storage.size).toBe(0);
+ });
+
+ it('aborts a stalled fetch before continuing with the bundled snapshot', async () => {
+ vi.useFakeTimers();
+ const signals: AbortSignal[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((_url, options) => {
+ signals.push(options.signal);
+ return new Promise(() => {});
+ }),
+ );
+ const { resolveMobileEndpointManifest } =
+ await import('@/config/endpointManifestLoader');
+ const result = resolveMobileEndpointManifest('cn', cnBase);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(await result).toMatchObject({ ok: true, source: 'bundled' });
+ expect(signals).toHaveLength(2);
+ expect(signals.every((signal) => signal.aborted)).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/config/clientEndpointStartup.ts b/apps/mobile/src/config/clientEndpointStartup.ts
index e5abede807..ba0ca20262 100644
--- a/apps/mobile/src/config/clientEndpointStartup.ts
+++ b/apps/mobile/src/config/clientEndpointStartup.ts
@@ -1,25 +1,10 @@
-/**
- * clientEndpointStartup —— 客户端端点清单(`<hotfix CDN base>/endpoint.json`)
- * 的 mobile 启动解析(useStartupEndpointGate 的执行体;依赖注入、可纯函数单测)。
- *
- * 语义:**CDN 清单是正式包唯一事实源**。启动时仍先拉取并解析 JSON,但 endpoint
- * 字段允许按 region 缺失或留空,不会因此阻断业务树。清单无法获取、JSON / schema
- * 不可解析或非空 URL 值非法时仍由启动闸门显示重试页。不读包内 `endpoint.json`、
- * 不做字段合并、不做整份回退,
- * 避免线上配置错误被静默掩盖或不同端点跑在不同版本。
- *
- * 共享逻辑(schema / 校验)在 @cindy/maker-shared/client-endpoints;本文件负责
- * mobile 侧 IO(全局 fetch + AbortController)与启动阻断;成功后经
- * env.applyResolvedClientEndpoints 回写 live binding。
- *
- * 唯一的柔性是**返回失败前**的网络层自动重试(AUTO_RETRY_DELAYS_MS):首次
- * 安装后的第一次启动网络栈最冷(DNS / 代理无缓存、系统仍在校验安装包),
- * 单次失败就把用户推到错误屏是把瞬时抖动当成故障。只对拉取失败生效,
- * 不对解析 / 校验失败生效;预算用尽仍失败照样阻断,严格语义不变。
+/** Startup discovery uses the same regional cache/bundle policy as session recovery.
+ * Primary configuration errors remain blocking; no fields are merged across snapshots.
*/
import {
- resolveClientEndpointsStrict,
+ classifyEndpointManifestFailure,
+ type ResilientEndpointResult,
type ClientEndpointMap,
type ClientEndpointRegion,
} from '@cindy/maker-shared/client-endpoints';
@@ -29,85 +14,29 @@ import {
ENDPOINT_MANIFEST_BASE_URL,
applyResolvedClientEndpoints,
} from './env';
+import {
+ fetchMobileEndpointManifest,
+ resolveMobileEndpointManifest,
+} from './endpointManifestLoader';
-const MANIFEST_RELATIVE_PATH = '/endpoint.json';
-/** 单次请求的网络超时——超时即阻断启动,不是无限等待。 */
-const ATTEMPT_TIMEOUT_MS = 10_000;
-/**
- * 返回失败前的自动重试节奏(ms);长度 = 额外尝试次数。与 desktop
- * clientEndpointsService 同语义,节奏按 mobile 的 10s 单次超时略收紧。
- */
const AUTO_RETRY_DELAYS_MS: readonly number[] = [700, 2000];
-
-/**
- * 一次取清单原文的结果。失败带 `detail`(错误码级别短标识):原实现 `catch {}`
- * 把错误整个吞掉、reason 恒为 `fetch-failed`,错误屏与用户反馈里都分不清
- * 超时 / DNS / HTTP 状态码,排查全靠猜。
- */
export type ManifestFetchResult =
- | { ok: true; text: string }
- | { ok: false; detail: string };
-
-/** 归一为单行并截断,避免长栈把错误屏文案撑爆。 */
-function normalizeDetail(detail: string): string {
- return detail.replace(/\s+/g, ' ').trim().slice(0, 120);
-}
-
-/** RN fetch 失败 → 简短标识(AbortError / TypeError: Network request failed 等)。 */
-function describeFetchFailure(err: unknown): string {
- if (err instanceof Error) {
- return normalizeDetail(err.message ? `${err.name}:${err.message}` : err.name);
- }
- return normalizeDetail(String(err));
-}
-
-/** 失败 detail → 闸门 reason(保持 maker-shared 的 `fetch-failed` 前缀语义)。 */
-function fetchFailedReason(detail: string): string {
- const normalized = normalizeDetail(detail);
- return normalized ? `fetch-failed:${normalized}` : 'fetch-failed';
-}
-
-function defaultSleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-async function fetchManifestViaCdn(
- timeoutMs: number,
- manifestBaseUrl: string = ENDPOINT_MANIFEST_BASE_URL,
-): Promise<ManifestFetchResult> {
- // 构建缺自举基址属打包配置事故:CDN 级不可用,交给启动闸门阻断。
- if (!manifestBaseUrl) return { ok: false, detail: 'missing-manifest-base-url' };
- const controller = new AbortController();
- let timedOut = false;
- const timer = setTimeout(() => {
- timedOut = true;
- controller.abort();
- }, timeoutMs);
- try {
- const response = await fetch(
- `${manifestBaseUrl}${MANIFEST_RELATIVE_PATH}?t=${Date.now()}`,
- { signal: controller.signal },
- );
- if (!response.ok) return { ok: false, detail: `http-${response.status}` };
- return { ok: true, text: await response.text() };
- } catch (err) {
- // abort 与网络错在 RN 下都落到这里:自己记的 timedOut 比 err.name 可靠。
- return { ok: false, detail: timedOut ? `timeout-${timeoutMs}ms` : describeFetchFailure(err) };
- } finally {
- clearTimeout(timer);
- }
-}
+ { ok: true; text: string } | { ok: false; detail: string };
+const defaultSleep = (ms: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, ms));
/** 测试注入点;生产走默认实现。 */
export interface StartupEndpointResolveDeps {
fetchManifest?: (timeoutMs: number) => Promise<ManifestFetchResult>;
/** iOS 在端点闸门放行前读取 StoreKit 分发环境;其它平台返回 false。 */
resolveIsTestFlight?: () => Promise<boolean>;
- apply?: (resolved: ClientEndpointMap & {
- reviewVersion: string | null;
- isTestFlight: boolean;
- region: 'cn' | 'global' | null;
- }) => void;
+ apply?: (
+ resolved: ClientEndpointMap & {
+ reviewVersion: string | null;
+ isTestFlight: boolean;
+ region: 'cn' | 'global' | null;
+ },
+ ) => void;
/** CindyDev 切换 Release 时传入第二个受信任清单基址。 */
manifestBaseUrl?: string;
/** 目标清单必须匹配的 auth 物理区域;默认仍为安装包构建区域。 */
@@ -121,40 +50,10 @@ export interface StartupEndpointResolveDeps {
sleep?: (ms: number) => Promise<void>;
}
-/**
- * 首发尝试 + 自动重试,返回最后一次结果。只有拉取失败消耗预算;
- * 拿到正文即刻返回(是否合法由调用方解析判定,失败不重试)。
- */
-async function fetchManifestWithRetry(args: {
- fetchManifest: (timeoutMs: number) => Promise<ManifestFetchResult>;
- timeoutMs: number;
- retryDelays: readonly number[];
- sleep: (ms: number) => Promise<void>;
-}): Promise<ManifestFetchResult> {
- for (let attempt = 0; ; attempt += 1) {
- let fetched: ManifestFetchResult;
- try {
- fetched = await args.fetchManifest(args.timeoutMs);
- } catch (err) {
- fetched = { ok: false, detail: describeFetchFailure(err) };
- }
- if (fetched.ok) return fetched;
- // 构建/打包配置事故(基址为空)重试不会改变结果,立即退出。
- if (fetched.detail === 'missing-manifest-base-url') return fetched;
- // HTTP 3xx/4xx 是永久性错误,重试同一 URL 不会自愈;仅 5xx 可能是瞬时故障。
- const httpStatus = /^http-(\d+)$/.exec(fetched.detail)?.[1];
- if (httpStatus && Number(httpStatus) < 500) return fetched;
- const delay = args.retryDelays[attempt];
- if (delay === undefined) return fetched; // 预算用尽 → 交调用方阻断
- await args.sleep(delay);
- }
-}
-
export type StartupEndpointResolveOutcome =
| {
ok: true;
- /** 正式包的生效端点只能来自 CDN 清单。 */
- source: 'cdn';
+ source: 'cdn' | 'mirror' | 'cache' | 'bundled';
}
| { ok: false; reason: string };
@@ -169,13 +68,8 @@ export async function runStartupEndpointResolve(
deps: StartupEndpointResolveDeps = {},
): Promise<StartupEndpointResolveOutcome> {
try {
- const fetchManifest =
- deps.fetchManifest ??
- ((requestTimeoutMs: number) =>
- fetchManifestViaCdn(
- requestTimeoutMs,
- deps.manifestBaseUrl ?? ENDPOINT_MANIFEST_BASE_URL,
- ));
+ const baseUrl = deps.manifestBaseUrl ?? ENDPOINT_MANIFEST_BASE_URL;
+ const expectedRegion = deps.expectedRegion ?? BUILD_AUTH_REGION;
const apply =
deps.apply ??
((resolved) =>
@@ -183,35 +77,33 @@ export async function runStartupEndpointResolve(
preserveBuildReleaseMetadata:
deps.preserveBuildReleaseMetadata === true,
}));
- const timeoutMs = deps.timeoutMs ?? ATTEMPT_TIMEOUT_MS;
- const retryDelays = deps.autoRetryDelaysMs ?? AUTO_RETRY_DELAYS_MS;
- const sleep = deps.sleep ?? defaultSleep;
-
- const fetched = await fetchManifestWithRetry({
- fetchManifest,
- timeoutMs,
- retryDelays,
- sleep,
- });
- if (!fetched.ok) return { ok: false, reason: fetchFailedReason(fetched.detail) };
-
- // 拿到正文:解析/校验不过 = 线上清单配置错,重试同一份内容没有意义,直接阻断。
- const result = resolveClientEndpointsStrict(fetched.text);
- if (!result.ok) return { ok: false, reason: result.reason };
- // 老清单缺 region 时保持兼容;一旦自报 region,就必须与安装包构建区域一致。
- const expectedRegion = deps.expectedRegion ?? BUILD_AUTH_REGION;
- if (result.region !== null && result.region !== expectedRegion) {
- return {
- ok: false,
- reason: `region-mismatch:${expectedRegion}:${result.region}`,
- };
+ let outcome: ResilientEndpointResult;
+ for (let attempt = 0; ; attempt += 1) {
+ outcome = await resolveMobileEndpointManifest(expectedRegion, baseUrl, {
+ timeoutMs: deps.timeoutMs,
+ fetchText: (url, timeoutMs) =>
+ deps.fetchManifest
+ ? deps.fetchManifest(timeoutMs)
+ : fetchMobileEndpointManifest(url, timeoutMs),
+ });
+ if (outcome.ok) break;
+ const delay = (deps.autoRetryDelaysMs ?? AUTO_RETRY_DELAYS_MS)[attempt];
+ if (
+ classifyEndpointManifestFailure(outcome.reason) !== 'network' ||
+ delay === undefined
+ )
+ return outcome;
+ // Only custom sources with no usable snapshot reach this retry path.
+ await (deps.sleep ?? defaultSleep)(delay);
}
+ const result = outcome.parsed;
// 分发环境识别失败不能把 endpoint 闸门变成启动故障;降级为非 TestFlight,
// 保留既有 review 行为。真实 iOS 路径由 useStartupEndpointGate 注入 StoreKit 实现。
let isTestFlight = false;
try {
- isTestFlight = await (deps.resolveIsTestFlight?.() ?? Promise.resolve(false));
+ isTestFlight = await (deps.resolveIsTestFlight?.() ??
+ Promise.resolve(false));
} catch {
isTestFlight = false;
}
@@ -222,7 +114,10 @@ export async function runStartupEndpointResolve(
isTestFlight,
region: result.region,
});
- return { ok: true, source: 'cdn' };
+ return {
+ ok: true,
+ source: outcome.source === 'network' ? 'cdn' : outcome.source,
+ };
} catch {
return { ok: false, reason: 'internal-error' };
}
diff --git a/apps/mobile/src/config/endpointManifestLoader.ts b/apps/mobile/src/config/endpointManifestLoader.ts
new file mode 100644
index 0000000000..e53b5e3fd1
--- /dev/null
+++ b/apps/mobile/src/config/endpointManifestLoader.ts
@@ -0,0 +1,78 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import {
+ ENDPOINT_CACHE_MAX_CHARS,
+ resolveResilientEndpointManifest,
+ type ClientEndpointRegion,
+ type EndpointManifestFetchResult,
+ type ResilientEndpointDeps,
+} from '@cindy/maker-shared/client-endpoints';
+
+/** No env import: both startup and env's cross-region loader use this adapter. */
+export async function fetchMobileEndpointManifest(
+ url: string,
+ timeoutMs: number,
+): Promise<EndpointManifestFetchResult> {
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ try {
+ const response = await fetch(
+ `${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`,
+ {
+ signal: controller.signal,
+ },
+ );
+ if (!response.ok) return { ok: false, detail: `http-${response.status}` };
+ return { ok: true, text: await response.text() };
+ } catch (error) {
+ const detail =
+ error instanceof Error ? `${error.name}:${error.message}` : String(error);
+ return {
+ ok: false,
+ detail: timedOut
+ ? `timeout-${timeoutMs}ms`
+ : detail.replace(/\s+/g, ' ').slice(0, 120),
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export function resolveMobileEndpointManifest(
+ region: ClientEndpointRegion,
+ baseUrl: string,
+ overrides: Partial<
+ Pick<
+ ResilientEndpointDeps,
+ 'fetchText' | 'timeoutMs' | 'readCache' | 'writeCache'
+ >
+ > = {},
+) {
+ const sourceUrl = baseUrl
+ ? `${baseUrl.replace(/\/+$/, '')}/endpoint.json`
+ : '';
+ const key = `cindy.mobile.endpoint-manifest.v1.${region}.${encodeURIComponent(sourceUrl)}`;
+ return resolveResilientEndpointManifest({
+ region,
+ sourceUrl,
+ fetchText: fetchMobileEndpointManifest,
+ readCache: async () => {
+ const raw = await AsyncStorage.getItem(key);
+ if (!raw || raw.length > ENDPOINT_CACHE_MAX_CHARS) return null;
+ try {
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return null;
+ }
+ },
+ writeCache: async (entry) => {
+ const raw = JSON.stringify(entry);
+ if (raw.length <= ENDPOINT_CACHE_MAX_CHARS)
+ await AsyncStorage.setItem(key, raw);
+ },
+ ...overrides,
+ });
+}
diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.ts
index 2d65c1837f..2071bf25f2 100644
--- a/apps/mobile/src/config/env.ts
+++ b/apps/mobile/src/config/env.ts
@@ -11,6 +11,7 @@ import {
} from '@cindy/maker-shared/client-endpoints';
import type { LoginMessageKey } from '@/auth/loginMessages';
+import { resolveMobileEndpointManifest } from './endpointManifestLoader';
export type CindyAuthRegion = 'cn' | 'global' | 'dev';
@@ -49,7 +50,7 @@ export const MOBILE_REDIRECT_URL = `${APP_SCHEME}://auth`;
// __DEV__ 端点初值来源:metro 构建期按 AUTH_REGION 把仓内
// config/endpoint.json 或 config/endpoint.global.json require 进 dev bundle
-// (__DEV__ 常量折叠 + DCE 后 prod bundle 不含该 JSON)。与 desktop dev 读同一份
+// 正式包的随包兜底由共享 resolver 负责;这里仅初始化 dev。与 desktop dev 读同一份
// region 正本同语义;正本非法直接抛错红屏(阻断语义:配置错要炸出来)。
// 显式 EXPO_PUBLIC_* env 仍然优先——「手机连本地 server」的既有工作流不变。
// prod(非 __DEV__)此处为空:生效端点由启动闸门拉取的 endpoint.json 回填
@@ -493,8 +494,6 @@ export function getMobileEndpointRealmConfig(): {
};
}
-const MOBILE_REALM_MANIFEST_TIMEOUT_MS = 10_000;
-
/** 当前登录态消费业务请求的区域;与安装包/更新通道所在区域相互独立。 */
export function getActiveMobileSessionRealm(): ClientEndpointRegion {
return activeSessionRealm;
@@ -509,26 +508,10 @@ export async function loadMobileEndpointsForRealm(
if (!baseUrl) {
throw new Error('realm-manifest-url-unavailable');
}
- const controller = new AbortController();
- const timer = setTimeout(
- () => controller.abort(),
- MOBILE_REALM_MANIFEST_TIMEOUT_MS,
- );
- try {
- const response = await fetch(`${baseUrl}/endpoint.json?t=${Date.now()}`, {
- signal: controller.signal,
- });
- if (!response.ok) throw new Error(`http-${response.status}`);
- const parsed = parseClientEndpointManifest(await response.text());
- if (!parsed.ok) throw new Error(parsed.reason);
- if (parsed.region !== null && parsed.region !== region) {
- throw new Error(`region-mismatch:${region}:${parsed.region}`);
- }
- realmEndpointCache.set(region, parsed.endpoints);
- return parsed.endpoints;
- } finally {
- clearTimeout(timer);
- }
+ const result = await resolveMobileEndpointManifest(region, baseUrl);
+ if (!result.ok) throw new Error(result.reason);
+ realmEndpointCache.set(region, result.parsed.endpoints);
+ return result.parsed.endpoints;
}
export function getMobileEndpointForRealm(
diff --git a/apps/mobile/src/config/useStartupEndpointGate.ts b/apps/mobile/src/config/useStartupEndpointGate.ts
index 254a327971..00fc0b85c1 100644
--- a/apps/mobile/src/config/useStartupEndpointGate.ts
+++ b/apps/mobile/src/config/useStartupEndpointGate.ts
@@ -1,7 +1,6 @@
// 启动端点清单闸门 hook:冷启动时跑 runStartupEndpointResolve,成功前业务树
-// 不挂载。正式包只认 CDN 清单:字段缺失/空白允许放行;拉取失败、JSON/schema
-// 无法解析或非空值非法时进入 error 态,由 _layout 渲染错误屏,用户点重试再跑一次;
-// 无包内回退。
+// 不挂载。网络故障可用本区缓存/随包完整清单继续;配置错误仍进入 error 态,
+// 由 _layout 渲染错误屏,用户点重试再跑一次。清单缺失/空白字段允许放行。
// __DEV__ 默认放行(零网络,端点初值来自仓内 config/endpoint.json,见 env.ts);
// EXPO_PUBLIC_ENDPOINTS_CDN=1 时 dev 也走完整 CDN 闸门(测线上清单,与
// desktop 的 --endpoints-cdn 同语义)。
diff --git a/config/endpoint-manifest-mirrors.json b/config/endpoint-manifest-mirrors.json
new file mode 100644
index 0000000000..f40961b377
--- /dev/null
+++ b/config/endpoint-manifest-mirrors.json
@@ -0,0 +1,8 @@
+{
+ "cn": [
+ "https://raw.githubusercontent.com/makecindy/cindy/main/config/endpoint.json"
+ ],
+ "global": [
+ "https://raw.githubusercontent.com/makecindy/cindy/main/config/endpoint.global.json"
+ ]
+}
diff --git a/docs/auth-realm-routing.md b/docs/auth-realm-routing.md
index 71e5ff2bb6..468f7c8b13 100644
--- a/docs/auth-realm-routing.md
+++ b/docs/auth-realm-routing.md
@@ -79,6 +79,46 @@ membership 后检查邮箱域名(Desktop `finishFreshLogin`、Mobile `acceptOu
## 会话持久化与恢复
+### 清单服务不可用时的恢复
+
+Desktop 启动、Mobile 启动和两端跨区域恢复使用同一套发现策略:
+
+1. 主清单在线优先,单次预算 2.5 秒。
+2. 主源发生传输错误、5xx、407/408/425/429 时,可尝试一个构建期配置的本区备用入口,
+ 同样最多 2.5 秒。主源的 JSON/schema/非法 URL/错区域或永久 HTTP 配置错误仍阻断;
+ 备源失败或配置不兼容则跳过,继续使用可信本地清单。
+3. 在线来源不可用时,读取本区最近成功的持久清单;读取后重新校验 schema、来源 URL
+ 和按区域限定的受信任端点域。Desktop 兼容读取旧单文件缓存,新写入按区域分文件;
+ Mobile 按区域和清单 URL 分键保存公开配置,不存凭据。在线清单也须满足同一离线信任
+ 判据才写入缓存;含非 Cindy 业务端点的自定义清单仅在线使用,不缓存、不扩展信任域。
+4. 没有有效缓存时,官方源使用随包的对应区域完整清单。自建、开发和显式自定义来源
+ 不会被官方生产地址替代。随包清单直接来自两份仓内正本,没有第二份业务地址真相源。
+
+每次解析只选择一份完整快照,不合并新旧字段,不把回退结果重新保存为在线成功缓存。
+网络或存储故障不清除登录凭据;端点解析成功之后仍走正常的认证与账号代次校验。
+缓存读写的异步等待各有 500ms 上限;Desktop 沿用同步文件 IO,该上限不能中断同步调用。
+迟到的网络结果不改变已激活的端点。后续启动重新尝试在线清单;本次会话不在后台偷偷
+切换认证服务。
+
+备用入口登记在 `config/endpoint-manifest-mirrors.json`,每区最多一个 HTTPS
+完整清单 URL,随 JS 构建进入两端,不能从下载清单或用户缓存读入。空数组表示该区尚未
+登记备用服务。默认复用官方 GitHub 仓库的两份原始清单,使用 GitHub 的文件分发路径,
+不经过 hotfix 节点。主分支合入清单即更新备源,不需要维护第三份清单副本;发布时仍须
+同步 hotfix,避免主备配置漂移。GitHub 在部分网络不可达,或 main 清单升级后与旧客户端
+不兼容时,继续走缓存/随包兜底,不接受不兼容备源内容。
+替换入口前须实际部署并确认与 hotfix 的 CDN/源站故障域独立,同步发布对应区域的
+完整清单;不能拿另一地区的认证服务当备站。
+
+旧清单的代价:故障期间无法立即收到端点迁移或审核/更新元数据调整。退役旧认证域前,
+需协调仍在分发的客户端随包清单;仅修改线上清单不保证失联客户端立刻停止使用旧地址。
+认证吊销仍由认证服务执行,离线清单不授予离线登录权限。更新身份仍跟随构建区域,
+跨区域恢复不改更新器字段语义。
+
+实现:`packages/maker-shared/src/clientEndpointResilience.ts` 与两端的
+`endpointManifestLoader.ts`。回归覆盖共享故障矩阵、两端持久缓存恢复和手机首启无缓存。
+
+### 认证记录
+
Desktop safeStorage 和 Mobile SecureStore 都只保存一个加密的原子记录:
```json
diff --git a/packages/maker-shared/src/__tests__/clientEndpointResilience.test.ts b/packages/maker-shared/src/__tests__/clientEndpointResilience.test.ts
new file mode 100644
index 0000000000..e8d0136c1e
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/clientEndpointResilience.test.ts
@@ -0,0 +1,396 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ classifyEndpointManifestFailure,
+ getBundledEndpointManifest,
+ getEndpointManifestMirrors,
+ resolveResilientEndpointManifest,
+ type ClientEndpointRegion,
+ type EndpointManifestCacheEntry,
+ type EndpointManifestFetchResult,
+} from '../clientEndpoints';
+
+const sourceUrl = (region: ClientEndpointRegion) =>
+ `https://hotfix.cindy.${region === 'cn' ? 'com.cn' : 'app'}/cindy/endpoint.json`;
+const manifest = (region: ClientEndpointRegion, extra = {}) =>
+ JSON.stringify({
+ ...JSON.parse(getBundledEndpointManifest(region, sourceUrl(region))!),
+ ...extra,
+ });
+const fail = async (): Promise<EndpointManifestFetchResult> => ({
+ ok: false,
+ detail: 'timeout-2500ms',
+});
+const entry = (
+ region: ClientEndpointRegion,
+ extra = {},
+): EndpointManifestCacheEntry => ({
+ sourceUrl: sourceUrl(region),
+ savedAt: '2026-09-19T00:00:00Z',
+ manifestText: manifest(region, extra),
+});
+
+afterEach(() => vi.useRealTimers());
+
+describe('regional endpoint resilience', () => {
+ it.each(['cn', 'global'] as const)(
+ 'compiled %s mirrors are bounded HTTPS trust anchors',
+ (region) => {
+ const urls = getEndpointManifestMirrors(region, sourceUrl(region));
+ expect(urls.length).toBeLessThanOrEqual(1);
+ for (const raw of urls) {
+ const url = new URL(raw);
+ expect(url.protocol).toBe('https:');
+ expect(url.username + url.password + url.hash).toBe('');
+ expect(url.hostname).not.toBe(new URL(sourceUrl(region)).hostname);
+ }
+ },
+ );
+
+ it.each(['cn', 'global'] as const)(
+ 'boots %s without network or cache using its complete bundled snapshot',
+ async (region) => {
+ const writeCache = vi.fn();
+ const result = await resolveResilientEndpointManifest({
+ region,
+ sourceUrl: sourceUrl(region),
+ fetchText: fail,
+ writeCache,
+ });
+ expect(result).toMatchObject({
+ ok: true,
+ source: 'bundled',
+ text: manifest(region),
+ });
+ expect(writeCache).not.toHaveBeenCalled();
+ },
+ );
+
+ it('persists the validated raw online document, including unknown fields, and restores it on the next launch', async () => {
+ let persisted: unknown;
+ const text = manifest('cn', {
+ authApiBaseUrl: 'https://auth-next.cindy.com.cn',
+ futureEndpoint: 'keep-me',
+ voiceApiBaseUrl: '',
+ });
+ const deps = {
+ region: 'cn' as const,
+ sourceUrl: sourceUrl('cn'),
+ readCache: () => persisted,
+ writeCache: (value: unknown) => {
+ persisted = value;
+ },
+ };
+ expect(
+ await resolveResilientEndpointManifest({
+ ...deps,
+ fetchText: async () => ({ ok: true, text }),
+ }),
+ ).toMatchObject({ ok: true, source: 'network' });
+ expect(persisted).toMatchObject({ manifestText: text });
+ expect(
+ await resolveResilientEndpointManifest({ ...deps, fetchText: fail }),
+ ).toMatchObject({
+ ok: true,
+ source: 'cache',
+ text,
+ parsed: {
+ endpoints: {
+ voiceApiBaseUrl: '',
+ authApiBaseUrl: 'https://auth-next.cindy.com.cn',
+ },
+ },
+ });
+ });
+
+ it.each([
+ ['invalid-json', '{'],
+ ['unsupported-schema-version:99', manifest('cn', { schemaVersion: 99 })],
+ ['region-mismatch:cn:global', manifest('cn', { region: 'global' })],
+ [
+ 'invalid-protocol:authApiBaseUrl',
+ manifest('cn', { authApiBaseUrl: 'http://auth.cindy.com.cn' }),
+ ],
+ ])('does not hide online configuration errors: %s', async (reason, text) => {
+ const readCache = vi.fn(() => entry('cn'));
+ const fetchText = vi.fn(async () => ({ ok: true as const, text }));
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ readCache,
+ fetchText,
+ mirrorUrls: ['https://backup.example.com/cn/endpoint.json'],
+ }),
+ ).toEqual({ ok: false, reason });
+ expect(readCache).not.toHaveBeenCalled();
+ expect(fetchText).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([403, 404, 301])('keeps HTTP %i blocking', async (status) => {
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText: async () => ({ ok: false, detail: `http-${status}` }),
+ }),
+ ).toEqual({ ok: false, reason: `fetch-failed:http-${status}` });
+ });
+
+ it.each([407, 408, 425, 429, 500, 503])(
+ 'allows fallback for transient HTTP %i',
+ async (status) => {
+ expect(
+ classifyEndpointManifestFailure(`fetch-failed:http-${status}`),
+ ).toBe('network');
+ },
+ );
+
+ it.each([
+ entry('global'),
+ { ...entry('cn'), manifestText: manifest('global') },
+ entry('cn', {
+ authApiBaseUrl: 'https://auth.cindy.com.cn.attacker.example',
+ }),
+ { ...entry('cn'), sourceUrl: 'https://old.cindy.com.cn/endpoint.json' },
+ { ...entry('cn'), savedAt: 'broken' },
+ { ...entry('cn'), manifestText: '{' },
+ ])(
+ 'rejects wrong-region, wrong-source and damaged caches',
+ async (cached) => {
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText: fail,
+ readCache: () => cached,
+ }),
+ ).toMatchObject({ ok: true, source: 'bundled', text: manifest('cn') });
+ },
+ );
+
+ it('uses an independent mirror for the same region and persists against the primary identity', async () => {
+ const text = manifest('cn', {
+ authApiBaseUrl: 'https://auth-next.cindy.com.cn',
+ });
+ const fetchText = vi
+ .fn()
+ .mockImplementationOnce(fail)
+ .mockResolvedValueOnce({ ok: true, text });
+ const writeCache = vi.fn();
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText,
+ writeCache,
+ mirrorUrls: ['https://backup.example.com/cn/endpoint.json'],
+ }),
+ ).toMatchObject({ ok: true, source: 'mirror', text });
+ expect(writeCache).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sourceUrl: sourceUrl('cn'),
+ manifestText: text,
+ }),
+ );
+ });
+
+ it('does not accept region-less Global endpoints from a CN mirror', async () => {
+ const fetchText = vi
+ .fn()
+ .mockImplementationOnce(fail)
+ .mockResolvedValueOnce({ ok: true, text: manifest('global') });
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText,
+ mirrorUrls: ['https://backup.example.com/cn/endpoint.json'],
+ }),
+ ).toMatchObject({ ok: true, source: 'bundled', text: manifest('cn') });
+ });
+
+ it.each(['cn', 'global'] as const)(
+ 'only persists restorable %s snapshots from custom sources',
+ async (region) => {
+ const customSource = 'https://custom.example.com/endpoint.json';
+ const text = manifest(region, {
+ authApiBaseUrl: 'https://auth.custom.example.com',
+ });
+ const writeCache = vi.fn();
+ expect(
+ await resolveResilientEndpointManifest({
+ region,
+ sourceUrl: customSource,
+ writeCache,
+ fetchText: async () => ({ ok: true, text }),
+ }),
+ ).toMatchObject({ ok: true, source: 'network', text });
+ expect(writeCache).not.toHaveBeenCalled();
+ // Even a legacy entry must not make custom domains trusted offline.
+ expect(
+ await resolveResilientEndpointManifest({
+ region,
+ sourceUrl: customSource,
+ fetchText: fail,
+ readCache: () => ({
+ ...entry(region),
+ sourceUrl: customSource,
+ manifestText: text,
+ }),
+ }),
+ ).toMatchObject({ ok: false });
+ const trustedText = manifest(region);
+ await resolveResilientEndpointManifest({
+ region,
+ sourceUrl: customSource,
+ writeCache,
+ fetchText: async () => ({ ok: true, text: trustedText }),
+ });
+ expect(writeCache).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sourceUrl: customSource,
+ manifestText: trustedText,
+ }),
+ );
+ expect(
+ await resolveResilientEndpointManifest({
+ region,
+ sourceUrl: customSource,
+ fetchText: fail,
+ readCache: () => writeCache.mock.calls[0][0],
+ }),
+ ).toMatchObject({ ok: true, source: 'cache', text: trustedText });
+ },
+ );
+
+ it.each([
+ ['JSON', { ok: true, text: '{' }],
+ ['schema', { ok: true, text: manifest('cn', { schemaVersion: 99 }) }],
+ ['region', { ok: true, text: manifest('cn', { region: 'global' }) }],
+ [
+ 'domain',
+ {
+ ok: true,
+ text: manifest('cn', { authApiBaseUrl: 'https://auth.future.example' }),
+ },
+ ],
+ [
+ 'protocol',
+ {
+ ok: true,
+ text: manifest('cn', { authApiBaseUrl: 'http://auth.cindy.com.cn' }),
+ },
+ ],
+ ['404', { ok: false, detail: 'http-404' }],
+ ] as const)(
+ 'skips incompatible mirror %s without caching it',
+ async (_kind, response) => {
+ for (const cached of [
+ undefined,
+ entry('cn', { authApiBaseUrl: 'https://cached.cindy.com.cn' }),
+ ]) {
+ const writeCache = vi.fn();
+ const fetchText = vi
+ .fn()
+ .mockImplementationOnce(fail)
+ .mockResolvedValueOnce(response);
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText,
+ writeCache,
+ readCache: () => cached,
+ }),
+ ).toMatchObject({
+ ok: true,
+ source: cached ? 'cache' : 'bundled',
+ text: cached?.manifestText ?? manifest('cn'),
+ });
+ expect(fetchText).toHaveBeenCalledTimes(2);
+ expect(writeCache).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it.each([
+ 'invalid',
+ 'http://backup.example.com/endpoint.json',
+ 'https://user:[email protected]/endpoint.json',
+ ])('skips invalid mirror URL %s without requesting it', async (url) => {
+ const fetchText = vi.fn(fail);
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText,
+ mirrorUrls: [url],
+ }),
+ ).toMatchObject({ ok: true, source: 'bundled' });
+ expect(fetchText).toHaveBeenCalledTimes(1);
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: url,
+ fetchText,
+ }),
+ ).toEqual({ ok: false, reason: 'invalid-manifest-url' });
+ expect(fetchText).toHaveBeenCalledTimes(1);
+ });
+
+ it('never switches a custom environment to official services', async () => {
+ const url = 'https://custom.example.com/endpoint.json';
+ expect(getEndpointManifestMirrors('cn', url)).toEqual([]);
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: url,
+ fetchText: fail,
+ }),
+ ).toEqual({ ok: false, reason: 'fetch-failed:timeout-2500ms' });
+ });
+
+ it('bounds a hung transport and ignores a late response without persisting it', async () => {
+ vi.useFakeTimers();
+ let finish!: (value: EndpointManifestFetchResult) => void;
+ const writeCache = vi.fn();
+ const pending = resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ mirrorUrls: [],
+ writeCache,
+ fetchText: () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ });
+ await vi.advanceTimersByTimeAsync(2500);
+ expect(await pending).toMatchObject({ ok: true, source: 'bundled' });
+ finish({ ok: true, text: manifest('global') });
+ await vi.runAllTimersAsync();
+ expect(writeCache).not.toHaveBeenCalled();
+ });
+
+ it('storage failure cannot turn successful authentication discovery into a startup failure', async () => {
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText: fail,
+ readCache: () => {
+ throw new Error('disk unavailable');
+ },
+ }),
+ ).toMatchObject({ ok: true, source: 'bundled' });
+ expect(
+ await resolveResilientEndpointManifest({
+ region: 'cn',
+ sourceUrl: sourceUrl('cn'),
+ fetchText: async () => ({ ok: true, text: manifest('cn') }),
+ writeCache: () => {
+ throw new Error('disk full');
+ },
+ }),
+ ).toMatchObject({ ok: true, source: 'network' });
+ });
+});
diff --git a/packages/maker-shared/src/clientEndpointOrigins.ts b/packages/maker-shared/src/clientEndpointOrigins.ts
new file mode 100644
index 0000000000..a5e9063e18
--- /dev/null
+++ b/packages/maker-shared/src/clientEndpointOrigins.ts
@@ -0,0 +1,116 @@
+// ── 缓存端点的受信任域约束 ──────────────────────────────────────────────────
+
+/**
+ * **各构建区域的端点域**——离线缓存的信任锚点,写死在源码里。
+ *
+ * 为什么不从自举基址「去掉最左一段」推导(第一次 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,所以只有这几个 hook key
+ * 允许落在 Global 域。**别往这里加 key** —— 每加一个就等于允许该端点跨区,而这个集合之外
+ * 的所有端点(尤其 auth / device-link / oauth-broker / model-access / voice)必须锁在
+ * 本构建区域,否则就回到上面说的跨区 token 误发。
+ */
+export const CROSS_REGION_ENDPOINT_KEYS: ReadonlySet<string> = new Set([
+ 'slackHookWsUrl',
+ 'telegramHookWsUrl',
+ 'xHookWsUrl',
+]);
+
+/** 缓存端点的来源策略:按 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;
+}
diff --git a/packages/maker-shared/src/clientEndpointResilience.ts b/packages/maker-shared/src/clientEndpointResilience.ts
new file mode 100644
index 0000000000..3148f5d08e
--- /dev/null
+++ b/packages/maker-shared/src/clientEndpointResilience.ts
@@ -0,0 +1,254 @@
+import cnManifest from '../../../config/endpoint.json';
+import globalManifest from '../../../config/endpoint.global.json';
+import mirrors from '../../../config/endpoint-manifest-mirrors.json';
+import {
+ parseClientEndpointManifest,
+ type ClientEndpointRegion,
+ type ParseClientEndpointManifestResult,
+} from './clientEndpointSchema';
+import {
+ findUntrustedCachedEndpoint,
+ REGION_ENDPOINT_DOMAIN,
+} from './clientEndpointOrigins';
+
+export const ENDPOINT_DISCOVERY_TIMEOUT_MS = 2_500;
+const STORAGE_TIMEOUT_MS = 500;
+export const ENDPOINT_CACHE_MAX_CHARS = 128 * 1024;
+
+export type EndpointManifestFetchResult =
+ { ok: true; text: string } | { ok: false; detail: string };
+export type EndpointManifestSource = 'network' | 'mirror' | 'cache' | 'bundled';
+export interface EndpointManifestCacheEntry {
+ savedAt: string;
+ sourceUrl: string;
+ manifestText: string;
+}
+export type ResilientEndpointResult =
+ | {
+ ok: true;
+ parsed: Extract<ParseClientEndpointManifestResult, { ok: true }>;
+ text: string;
+ source: EndpointManifestSource;
+ }
+ | { ok: false; reason: string };
+
+export function classifyEndpointManifestFailure(
+ reason: string,
+): 'network' | 'config' {
+ if (!reason.startsWith('fetch-failed')) return 'config';
+ const detail = reason.slice('fetch-failed'.length).replace(/^:/, '');
+ if (detail === 'missing-manifest-base-url') return 'config';
+ const status = /^http-(\d+)$/.exec(detail)?.[1];
+ return status &&
+ Number(status) < 500 &&
+ ![407, 408, 425, 429].includes(Number(status))
+ ? 'config'
+ : 'network';
+}
+
+function parseForRegion(
+ text: string,
+ region: ClientEndpointRegion,
+): ParseClientEndpointManifestResult {
+ const parsed = parseClientEndpointManifest(text);
+ if (parsed.ok && parsed.region !== null && parsed.region !== region) {
+ return { ok: false, reason: `region-mismatch:${region}:${parsed.region}` };
+ }
+ return parsed;
+}
+
+export function parseTrustedEndpointSnapshot(
+ text: string,
+ region: ClientEndpointRegion,
+) {
+ if (text.length > ENDPOINT_CACHE_MAX_CHARS) return null;
+ const parsed = parseForRegion(text, region);
+ if (
+ !parsed.ok ||
+ findUntrustedCachedEndpoint(parsed.endpoints, {
+ regionDomain: REGION_ENDPOINT_DOMAIN[region],
+ crossRegionDomain: REGION_ENDPOINT_DOMAIN.global,
+ })
+ )
+ return null;
+ return parsed;
+}
+
+const bundledManifests = { cn: cnManifest, global: globalManifest };
+
+/** Custom/self-hosted discovery must never fall back to Cindy production. */
+export function getBundledEndpointManifest(
+ region: ClientEndpointRegion,
+ sourceUrl: string,
+): string | null {
+ const manifest = bundledManifests[region];
+ if (sourceUrl !== `${manifest.cdnBaseUrl}/endpoint.json`) return null;
+ return JSON.stringify(manifest);
+}
+
+/** Mirrors are build-time trust anchors, never supplied by downloaded/cache data. */
+export function getEndpointManifestMirrors(
+ region: ClientEndpointRegion,
+ sourceUrl: string,
+): readonly string[] {
+ return getBundledEndpointManifest(region, sourceUrl) === null
+ ? []
+ : mirrors[region];
+}
+
+export function readTrustedEndpointCache(
+ value: unknown,
+ region: ClientEndpointRegion,
+ sourceUrl: string,
+): {
+ parsed: Extract<ParseClientEndpointManifestResult, { ok: true }>;
+ text: string;
+} | null {
+ if (!value || typeof value !== 'object') return null;
+ const entry = value as Partial<EndpointManifestCacheEntry>;
+ if (
+ entry.sourceUrl !== sourceUrl ||
+ typeof entry.savedAt !== 'string' ||
+ !Number.isFinite(Date.parse(entry.savedAt)) ||
+ typeof entry.manifestText !== 'string'
+ )
+ return null;
+ const parsed = parseTrustedEndpointSnapshot(entry.manifestText, region);
+ return parsed ? { parsed, text: entry.manifestText } : null;
+}
+
+/** Bounds optional storage and buggy transports too; late completion cannot apply endpoints. */
+async function bounded<T>(
+ operation: () => T | Promise<T>,
+ timeoutMs: number,
+ fallback: T,
+): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ Promise.resolve()
+ .then(operation)
+ .catch(() => fallback),
+ new Promise<T>((resolve) => {
+ timer = setTimeout(() => resolve(fallback), timeoutMs);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export interface ResilientEndpointDeps {
+ region: ClientEndpointRegion;
+ sourceUrl: string;
+ /** Transport must cancel its request at timeoutMs; no credentials are sent. */
+ fetchText(
+ url: string,
+ timeoutMs: number,
+ ): Promise<EndpointManifestFetchResult>;
+ readCache?(): unknown | Promise<unknown>;
+ writeCache?(entry: EndpointManifestCacheEntry): unknown | Promise<unknown>;
+ timeoutMs?: number;
+ /** Host/build injected only. Undefined selects the compiled anchors. */
+ mirrorUrls?: readonly string[];
+ bundledText?: string | null;
+}
+
+/** One complete snapshot per resolution. Primary configuration errors remain fatal. */
+export async function resolveResilientEndpointManifest(
+ deps: ResilientEndpointDeps,
+): Promise<ResilientEndpointResult> {
+ if (!deps.sourceUrl)
+ return { ok: false, reason: 'fetch-failed:missing-manifest-base-url' };
+ const timeoutMs = deps.timeoutMs ?? ENDPOINT_DISCOVERY_TIMEOUT_MS;
+ // At most one independent mirror keeps the whole discovery budget bounded.
+ const mirrorUrls =
+ deps.mirrorUrls ?? getEndpointManifestMirrors(deps.region, deps.sourceUrl);
+ const urls = [...new Set([deps.sourceUrl, ...mirrorUrls])].slice(0, 2);
+ let reason = 'fetch-failed';
+ for (const [index, url] of urls.entries()) {
+ let address: URL;
+ try {
+ address = new URL(url);
+ } catch {
+ reason = 'invalid-manifest-url';
+ if (index === 0) return { ok: false, reason };
+ continue;
+ }
+ if (address.protocol !== 'https:' || address.username || address.password) {
+ reason = 'invalid-manifest-url';
+ if (index === 0) return { ok: false, reason };
+ continue;
+ }
+ const fetched = await bounded<EndpointManifestFetchResult>(
+ async () => {
+ try {
+ return await deps.fetchText(url, timeoutMs);
+ } catch (error) {
+ const detail =
+ error instanceof Error
+ ? `${error.name}:${error.message}`
+ : String(error);
+ return {
+ ok: false,
+ detail: detail.replace(/\s+/g, ' ').trim().slice(0, 120),
+ };
+ }
+ },
+ timeoutMs,
+ { ok: false, detail: `timeout-${timeoutMs}ms` },
+ );
+ if (fetched.ok) {
+ const parsed = parseForRegion(fetched.text, deps.region);
+ if (!parsed.ok) {
+ if (index === 0) return parsed;
+ reason = parsed.reason;
+ continue;
+ }
+ const restorable = parseTrustedEndpointSnapshot(
+ fetched.text,
+ deps.region,
+ );
+ // A mirror cannot redirect authentication to another region, even on old region-less manifests.
+ if (index > 0 && !restorable) {
+ reason = 'untrusted-mirror-endpoints';
+ continue;
+ }
+ // Do not persist custom endpoint domains that the offline reader cannot trust.
+ if (restorable)
+ await bounded(
+ () =>
+ deps.writeCache?.({
+ savedAt: new Date().toISOString(),
+ sourceUrl: deps.sourceUrl,
+ manifestText: fetched.text,
+ }),
+ STORAGE_TIMEOUT_MS,
+ undefined,
+ );
+ return {
+ ok: true,
+ parsed,
+ text: fetched.text,
+ source: index === 0 ? 'network' : 'mirror',
+ };
+ }
+ reason = `fetch-failed:${fetched.detail}`;
+ if (index === 0 && classifyEndpointManifestFailure(reason) !== 'network')
+ return { ok: false, reason };
+ }
+ const cached = readTrustedEndpointCache(
+ await bounded(() => deps.readCache?.(), STORAGE_TIMEOUT_MS, undefined),
+ deps.region,
+ deps.sourceUrl,
+ );
+ if (cached) return { ok: true, ...cached, source: 'cache' };
+ const text =
+ deps.bundledText === undefined
+ ? getBundledEndpointManifest(deps.region, deps.sourceUrl)
+ : deps.bundledText;
+ const parsed = text ? parseTrustedEndpointSnapshot(text, deps.region) : null;
+ return parsed && text
+ ? { ok: true, parsed, text, source: 'bundled' }
+ : { ok: false, reason };
+}
diff --git a/packages/maker-shared/src/clientEndpointSchema.ts b/packages/maker-shared/src/clientEndpointSchema.ts
new file mode 100644
index 0000000000..6e09a917d9
--- /dev/null
+++ b/packages/maker-shared/src/clientEndpointSchema.ts
@@ -0,0 +1,321 @@
+/**
+ * clientEndpoints — 客户端远程端点清单的共享 schema / 校验 / 严格解析。
+ *
+ * 背景:desktop / mobile 的生产端点在构建期内联进包体,发版后无法变更。CDN 上
+ * 存放一份公开读的清单(仓内正本 `config/endpoint.json` = cn、
+ * `config/endpoint.global.json` = global,人肉上传各自 region 的 CDN),
+ * 应用启动第一步、**先于检查更新**从 CDN 拉取;CDN 清单修改后重启应用生效。
+ * 完整拉取地址 = `<烘焙的 region 化 hotfix base>/endpoint.json`。
+ *
+ * 在线清单优先;网络失败后允许本区持久缓存、随包完整清单兜底。
+ * JSON/schema/非法 URL/区域不匹配与永久 HTTP 配置错误仍阻断,绝不逐字段合并。
+ * 缓存重新严格解析并按目标区域校验受信任域,来源地址变化即失效。
+ * 备用入口是构建期信任锚点,不能由下载的清单或缓存指定。
+ * 更新端点与审核元数据保持完整快照语义,账号区域切换不改变构建更新身份。
+ * - dev(desktop 未打包 / mobile __DEV__)默认不走 CDN,改读仓内正本文件
+ * (同一套解析,allowHttp 宽松协议见下);`--endpoints-cdn` /
+ * EXPO_PUBLIC_ENDPOINTS_CDN=1 可让 dev 走完整 CDN 链路。
+ *
+ * 职责边界(仓规则 2):本模块是纯逻辑层,不做任何 IO——fetch / 读文件 / 报错
+ * 交互由宿主(desktop main / mobile 启动闸门)实现,这里只提供确定性的解析与
+ * 校验(仓规则 9)。
+ *
+ * 校验语义:
+ * - CLIENT_ENDPOINT_KEYS 中的字段缺失或空白时统一解析为 `''`;不同 region 可以
+ * 不提供不适用的业务端点,不会因此阻断整个客户端启动;
+ * - 未知字段忽略(向前兼容:新客户端加字段后,老清单先补字段再发新客户端;
+ * 新清单多出的字段老客户端不认识但不报错);
+ * - 协议白名单、禁 URL 凭据、
+ * 尾斜杠归一;
+ * - `allowHttp` 宽松模式(仅 dev 本地文件路径允许开启):https-only 字段追加
+ * 接受 http:、wss 字段追加 ws:,让 endpoint.local.json 能填 localhost;
+ * packaged / CDN 路径一律不开,打包校验零放松;
+ * - schemaVersion 缺失、非正整数或大于当前支持版本 → 整份拒绝(breaking change
+ * 才 bump 版本)。2026-07 追加 cdnBaseUrl 时**没有** bump:新字段随全新的
+ * hotfix CDN 域名 + `/endpoint.json` 路径发布,老客户端读的是老 CDN 老路径
+ * (`/config/client-endpoints.json`)看不到新清单;即使把新正本内容双写到
+ * 老路径,多出的字段也会被老 parser 按"未知字段"忽略——bump 的语义是
+ * "同一文件的不兼容重释义",纯增字段 + 换发布地址不构成。
+ * - 2026-07 稍后退役 cdnInternalBaseUrl(内网加速镜像下线,更新链只走
+ * cdnBaseUrl)同样没有 bump:删必填字段对**新客户端**是纯放松(清单里多出
+ * 的该字段按未知字段忽略);退役时新路径清单尚无已发布的 packaged 消费者,
+ * 线上清单已同步删除,无兼容包袱。
+ * - 2026-07-17 追加可选字符串字段 review(手机版审核模式的送审版本号,见
+ * CLIENT_ENDPOINT_REVIEW_KEY)同样没有 bump:可选字段、缺失/空串即关闭,
+ * 老清单不受影响;老客户端按未知字段忽略。
+ * - 2026-07-17 退役 xdGatewayBaseUrl(同样不 bump,理由同上):XD 网关推理
+ * 入口一律由 model-access server 随凭据成对下发(desktop
+ * model-access/effectiveEndpoint.ts),清单不再承载网关端点,杜绝
+ * 「key 与 endpoint 不同租户」的撕裂组合;mobile 语音的网关地址经桌面端
+ * device-link 凭据同步获得,不再吃清单默认值。
+ */
+
+/** 当前客户端支持的清单 schema 版本;清单里更大的版本号会被整份拒绝。 */
+export const CLIENT_ENDPOINTS_SCHEMA_VERSION = 1;
+
+/**
+ * 清单字段全集 = 客户端可能消费的端点集合。不同 region 可缺省或留空不适用的
+ * 字段;解析结果仍补齐所有 key,让既有消费方保持稳定的 string 读取接口。
+ */
+export const CLIENT_ENDPOINT_KEYS = [
+ // apiBaseUrl(老主 server xdt-api)已于 2026-07-18 退役(不 bump,删必填字段
+ // 对新客户端是纯放松):四块业务消费方分批迁至独立服务(chat-data 删除 /
+ // SlackIM→slack-hook / GitHub 反馈→githubApiBaseUrl / Skillhub→
+ // skillhubApiBaseUrl)。退役时清单体系尚无已发布的 packaged/mobile 消费者,
+ // 正本(=CDN 上传源)已同步删值,无兼容包袱(同 cdnInternalBaseUrl 先例)。
+ // 每份清单只描述自身 region 的 auth/业务端点。默认会话读取构建清单;
+ // 跨区域组织登录会先加载目标 region 清单,再整体切换 token 消费端点。
+ 'authApiBaseUrl',
+ // desktop 系统浏览器登录的**服务端托管回调**地址(auth-server 路由,精确值需与
+ // 服务端 redirect_uri allowlist 逐字符一致)。非空 = 走托管回调链路:回调页停在
+ // 自有域名、授权码由客户端轮询取回,浏览器地址栏不再出现 127.0.0.1 与 code;
+ // 空 = 回落到 RFC 8252 loopback(现状行为)。这也是本能力的灰度/回滚开关——
+ // 服务端出问题时清空本字段即可回退,客户端不必发版。
+ // 不 bump schemaVersion:纯增可选字段,老清单缺失即 '',老客户端按未知字段忽略
+ // (同 review / cdnBaseUrl 先例,理由见上方版本注释)。
+ 'authDesktopCallbackUrl',
+ 'deviceLinkApiBaseUrl',
+ 'oauthBrokerApiBaseUrl',
+ // oss-server(公开资产直传预签名,当前场景:头像上传)。
+ 'ossApiBaseUrl',
+ 'heartbeatUrl',
+ // Telegram hook is deployed independently from Slack; empty means the
+ // current environment has not rolled out Telegram yet.
+ 'telegramHookWsUrl',
+ // X (Twitter) hook, same deployment model as Telegram; empty (or a manifest
+ // that omits the key entirely) means X has not rolled out yet — the Settings
+ // card stays hidden, which is the intended gradual-rollout switch.
+ 'xHookWsUrl',
+ 'slackHookWsUrl',
+ 'websiteUrl',
+ // model-access-server(登录后自动下发 LLM 网关凭据)的 API 基址。
+ 'modelAccessApiBaseUrl',
+ // voice-server(一期开通免费语音输入的数据面)API 基址。
+ 'voiceApiBaseUrl',
+ // github-server(用户反馈 → 官方仓 GitHub issue 的薄代理)的 API 基址。
+ 'githubApiBaseUrl',
+ // 旧 xd-skillhub-server 的 API 基址。已发布客户端继续消费这个字段,值不得
+ // 改指新服务;新客户端只消费下方 cindySkillHubApiBaseUrl。
+ 'skillhubApiBaseUrl',
+ // cindy-skill-hub-server 的 API 基址。纯增可选字段,不 bump schemaVersion:
+ // 老客户端按未知字段忽略,新客户端缺失时明确关闭云端 Skill Hub,不回退旧地址。
+ 'cindySkillHubApiBaseUrl',
+ // plugin-server(Plugin/Skill 市场、组织管理与发布)的 API 基址。
+ 'pluginApiBaseUrl',
+ // 更新/hotfix 链的 CDN base(manifest-*.json / hotfix 包 / agent 二进制)。
+ 'cdnBaseUrl',
+ // 自建线手机整包发现的 mobile-update-server 基址(`${base}/latest`)。仅
+ // mobile 自建变体(IS_OTA_SELFHOST)消费,desktop 与 EAS 线不读;清单值
+ // 优先于烧包的 EXPO_PUBLIC_XDT_OTA_URL,让已发自建包可远程迁域名。
+ // 注意热更通道的 updates.url 仍烧在原生层(expo-updates 架构),不吃本字段。
+ 'mobileUpdateBaseUrl',
+] as const;
+
+export type ClientEndpointKey = (typeof CLIENT_ENDPOINT_KEYS)[number];
+
+/** 解析成功后的端点全集(全 key 存在;清单缺失/空白的字段值为 `''`)。 */
+export type ClientEndpointMap = Record<ClientEndpointKey, string>;
+
+/** auth-server 的物理部署区域;与 App 包体的品牌/更新区域是两个独立概念。 */
+export type ClientEndpointRegion = 'cn' | 'global';
+
+export type RealmManifestBaseUrls = Readonly<
+ Record<ClientEndpointRegion, string>
+>;
+
+/**
+ * 可选字符串字段:`review` = 手机版审核模式的**送审版本号**(App 审核期间填
+ * 送审构建的二进制版本号,如 "1.4.0")。mobile 启动时用它与自身二进制版本号
+ * **严格相等匹配**,且 iOS StoreKit 未识别为 TestFlight 时才进入审核模式:
+ * TestFlight 即使版本命中也继续更新;其余命中构建关闭全部 JS 显式更新检查路径(启动
+ * JS 热更门 / 整包检查 / resume 静默检查)直接进主界面,设置页隐藏「检查更新 /
+ * 检查整包更新」;desktop 不消费。按版本定向的意义:清单是 region 级共享文件,
+ * 版本匹配把影响面从"全量用户"收窄到"同版本号的构建"——存量其它版本用户的
+ * 更新检查与强更通道不受影响。注意命中粒度是**版本号而非送审构建本身**:
+ * app.json 的 version 为 iOS/Android 各变体共用,若送审版本号与其它平台/变体
+ * 正在线上跑的版本号相同,这些同版本用户也会进入审核模式(iOS TestFlight 除外);
+ * 填写前需确认送审版本号未与其它线上线重叠,或接受重叠期影响。
+ * **可选、缺失或空串即关闭**——线上已发布的清单没有该字段,若设为必填会让新
+ * 客户端对老清单启动阻断;可选纯增量也是不 bump schemaVersion 的前提(见上方
+ * 版本注释)。存在但非 string 视为配置错,整份拒绝(配置错要炸出来,不静默猜测)。
+ * 覆盖边界与运维义务(填写前必须知晓):
+ * - **管不到 expo-updates 原生层**:CheckOnLaunch 是 build-time 原生配置
+ * (当前烘焙 ALWAYS),冷启动仍会后台静默 check+下载、下次启动生效——
+ * 该缺口无法用运行时清单字段封,审核窗口内需同时冻结热更发布;
+ * - 送审版本过审对外发布后必须及时把该字段清回 ""(或删除),否则线上同
+ * 版本的非 TestFlight 用户会一直处于审核模式、收不到后续 JS 更新检查与强更提示。
+ */
+export const CLIENT_ENDPOINT_REVIEW_KEY = 'review';
+
+/** 各字段允许的 URL 协议白名单。 */
+const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {
+ authApiBaseUrl: ['https:'],
+ authDesktopCallbackUrl: ['https:'],
+ deviceLinkApiBaseUrl: ['https:'],
+ oauthBrokerApiBaseUrl: ['https:'],
+ ossApiBaseUrl: ['https:'],
+ heartbeatUrl: ['https:'],
+ telegramHookWsUrl: ['wss:'],
+ xHookWsUrl: ['wss:'],
+ slackHookWsUrl: ['wss:'],
+ websiteUrl: ['https:'],
+ modelAccessApiBaseUrl: ['https:'],
+ voiceApiBaseUrl: ['https:'],
+ githubApiBaseUrl: ['https:'],
+ skillhubApiBaseUrl: ['https:'],
+ cindySkillHubApiBaseUrl: ['https:'],
+ pluginApiBaseUrl: ['https:'],
+ cdnBaseUrl: ['https:'],
+ mobileUpdateBaseUrl: ['https:'],
+};
+
+/** 解析选项;allowHttp 仅供 dev 本地文件路径(endpoint.local.json 等)开启。 */
+export interface ParseClientEndpointManifestOptions {
+ /** true 时 https-only 字段追加接受 http:、wss 字段追加 ws:(localhost 场景)。 */
+ allowHttp?: boolean;
+ /** 加载指定区域的清单时必须提供;清单自报区域不一致或缺失会整份拒绝。 */
+ expectedRegion?: ClientEndpointRegion;
+}
+
+// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
+function trimTrailingSlashes(s: string): string {
+ let end = s.length;
+ while (end > 0 && s.charCodeAt(end - 1) === 0x2f) end -= 1;
+ return s.slice(0, end);
+}
+
+function allowedProtocols(
+ key: ClientEndpointKey,
+ allowHttp: boolean,
+): readonly string[] {
+ const base = FIELD_PROTOCOLS[key];
+ if (!allowHttp) return base;
+ const relaxed = [...base];
+ if (base.includes('https:') && !base.includes('http:')) relaxed.push('http:');
+ if (base.includes('wss:') && !base.includes('ws:')) relaxed.push('ws:');
+ return relaxed;
+}
+
+export type ParseClientEndpointManifestResult =
+ | {
+ ok: true;
+ endpoints: ClientEndpointMap;
+ reviewVersion: string | null;
+ /** 可选诊断元数据;缺失时由受信任清单地址确定区域。 */
+ region: ClientEndpointRegion | null;
+ }
+ | { ok: false; reason: string };
+
+/**
+ * 解析并校验一份清单原文。纯函数,输入任意文本都不会抛出。
+ * 端点缺失 / 空白时写入 `''` 并继续;非空值仍校验 URL、协议与凭据;
+ * `review` 可选字符串(送审版本号),缺失 / 空白 = null 即审核模式关闭
+ * (语义见 CLIENT_ENDPOINT_REVIEW_KEY)。
+ */
+export function parseClientEndpointManifest(
+ rawText: string,
+ options?: ParseClientEndpointManifestOptions,
+): ParseClientEndpointManifestResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawText);
+ } catch {
+ return { ok: false, reason: 'invalid-json' };
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return { ok: false, reason: 'not-an-object' };
+ }
+ const record = parsed as Record<string, unknown>;
+
+ const schemaVersion = record.schemaVersion;
+ if (
+ typeof schemaVersion !== 'number' ||
+ !Number.isInteger(schemaVersion) ||
+ schemaVersion < 1
+ ) {
+ return { ok: false, reason: 'invalid-schema-version' };
+ }
+ if (schemaVersion > CLIENT_ENDPOINTS_SCHEMA_VERSION) {
+ return { ok: false, reason: `unsupported-schema-version:${schemaVersion}` };
+ }
+
+ const endpoints = {} as ClientEndpointMap;
+ for (const key of CLIENT_ENDPOINT_KEYS) {
+ const raw = record[key];
+ if (raw === undefined || (typeof raw === 'string' && !raw.trim())) {
+ endpoints[key] = '';
+ continue;
+ }
+ if (typeof raw !== 'string') {
+ return { ok: false, reason: `invalid-field:${key}` };
+ }
+ const normalized = trimTrailingSlashes(raw.trim());
+ let url: URL;
+ try {
+ url = new URL(normalized);
+ } catch {
+ return { ok: false, reason: `invalid-field:${key}` };
+ }
+ if (
+ !allowedProtocols(key, options?.allowHttp === true).includes(url.protocol)
+ ) {
+ return { ok: false, reason: `invalid-protocol:${key}` };
+ }
+ if (url.username || url.password) {
+ return { ok: false, reason: `credentials-in-url:${key}` };
+ }
+ endpoints[key] = normalized;
+ }
+
+ const rawReview = record[CLIENT_ENDPOINT_REVIEW_KEY];
+ if (rawReview !== undefined && typeof rawReview !== 'string') {
+ return { ok: false, reason: `invalid-field:${CLIENT_ENDPOINT_REVIEW_KEY}` };
+ }
+ const reviewVersion =
+ typeof rawReview === 'string' && rawReview.trim() ? rawReview.trim() : null;
+
+ const rawRegion = record.region;
+ const region =
+ rawRegion === undefined
+ ? null
+ : rawRegion === 'cn' || rawRegion === 'global'
+ ? rawRegion
+ : null;
+ if (rawRegion !== undefined && region === null) {
+ return { ok: false, reason: 'invalid-field:region' };
+ }
+ if (
+ options?.expectedRegion !== undefined &&
+ region !== options.expectedRegion
+ ) {
+ return {
+ ok: false,
+ reason: `region-mismatch:${options.expectedRegion}:${region ?? 'missing'}`,
+ };
+ }
+
+ return {
+ ok: true,
+ endpoints,
+ reviewVersion,
+ region,
+ };
+}
+
+export type ResolveClientEndpointsResult =
+ | Extract<ParseClientEndpointManifestResult, { ok: true }>
+ | { ok: false; reason: string };
+
+/**
+ * 解析清单原文 → 完整端点 map(缺失/空白字段补 `''`,无任何本地合并)。
+ * rawText 为 null(拉取失败/超时)→ ok:false('fetch-failed'),宿主必须阻断并重试。
+ */
+export function resolveClientEndpointsStrict(
+ rawText: string | null,
+ options?: ParseClientEndpointManifestOptions,
+): ResolveClientEndpointsResult {
+ if (rawText === null) {
+ return { ok: false, reason: 'fetch-failed' };
+ }
+ return parseClientEndpointManifest(rawText, options);
+}
diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.ts
index 533e207eeb..986c910da3 100644
--- a/packages/maker-shared/src/clientEndpoints.ts
+++ b/packages/maker-shared/src/clientEndpoints.ts
@@ -1,338 +1,4 @@
-/**
- * clientEndpoints — 客户端远程端点清单的共享 schema / 校验 / 严格解析。
- *
- * 背景:desktop / mobile 的生产端点在构建期内联进包体,发版后无法变更。CDN 上
- * 存放一份公开读的清单(仓内正本 `config/endpoint.json` = cn、
- * `config/endpoint.global.json` = global,人肉上传各自 region 的 CDN),
- * 应用启动第一步、**先于检查更新**从 CDN 拉取;CDN 清单修改后重启应用生效。
- * 完整拉取地址 = `<烘焙的 region 化 hotfix base>/endpoint.json`。
- *
- * 语义是**清单即唯一事实源**:
- * - 拉不到 / 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)
- * ——清单阻断在一切更新检查之前,更新链拿到的一定是已解析的清单值,
- * 无鸡生蛋问题;
- * - dev(desktop 未打包 / mobile __DEV__)默认不走 CDN,改读仓内正本文件
- * (同一套解析,allowHttp 宽松协议见下);`--endpoints-cdn` /
- * EXPO_PUBLIC_ENDPOINTS_CDN=1 可让 dev 走完整 CDN 链路。
- *
- * 职责边界(仓规则 2):本模块是纯逻辑层,不做任何 IO——fetch / 读文件 / 报错
- * 交互由宿主(desktop main / mobile 启动闸门)实现,这里只提供确定性的解析与
- * 校验(仓规则 9)。
- *
- * 校验语义:
- * - CLIENT_ENDPOINT_KEYS 中的字段缺失或空白时统一解析为 `''`;不同 region 可以
- * 不提供不适用的业务端点,不会因此阻断整个客户端启动;
- * - 未知字段忽略(向前兼容:新客户端加字段后,老清单先补字段再发新客户端;
- * 新清单多出的字段老客户端不认识但不报错);
- * - 协议白名单、禁 URL 凭据、
- * 尾斜杠归一;
- * - `allowHttp` 宽松模式(仅 dev 本地文件路径允许开启):https-only 字段追加
- * 接受 http:、wss 字段追加 ws:,让 endpoint.local.json 能填 localhost;
- * packaged / CDN 路径一律不开,打包校验零放松;
- * - schemaVersion 缺失、非正整数或大于当前支持版本 → 整份拒绝(breaking change
- * 才 bump 版本)。2026-07 追加 cdnBaseUrl 时**没有** bump:新字段随全新的
- * hotfix CDN 域名 + `/endpoint.json` 路径发布,老客户端读的是老 CDN 老路径
- * (`/config/client-endpoints.json`)看不到新清单;即使把新正本内容双写到
- * 老路径,多出的字段也会被老 parser 按"未知字段"忽略——bump 的语义是
- * "同一文件的不兼容重释义",纯增字段 + 换发布地址不构成。
- * - 2026-07 稍后退役 cdnInternalBaseUrl(内网加速镜像下线,更新链只走
- * cdnBaseUrl)同样没有 bump:删必填字段对**新客户端**是纯放松(清单里多出
- * 的该字段按未知字段忽略);退役时新路径清单尚无已发布的 packaged 消费者,
- * 线上清单已同步删除,无兼容包袱。
- * - 2026-07-17 追加可选字符串字段 review(手机版审核模式的送审版本号,见
- * CLIENT_ENDPOINT_REVIEW_KEY)同样没有 bump:可选字段、缺失/空串即关闭,
- * 老清单不受影响;老客户端按未知字段忽略。
- * - 2026-07-17 退役 xdGatewayBaseUrl(同样不 bump,理由同上):XD 网关推理
- * 入口一律由 model-access server 随凭据成对下发(desktop
- * model-access/effectiveEndpoint.ts),清单不再承载网关端点,杜绝
- * 「key 与 endpoint 不同租户」的撕裂组合;mobile 语音的网关地址经桌面端
- * device-link 凭据同步获得,不再吃清单默认值。
- */
-
-/** 当前客户端支持的清单 schema 版本;清单里更大的版本号会被整份拒绝。 */
-export const CLIENT_ENDPOINTS_SCHEMA_VERSION = 1;
-
-/**
- * 清单字段全集 = 客户端可能消费的端点集合。不同 region 可缺省或留空不适用的
- * 字段;解析结果仍补齐所有 key,让既有消费方保持稳定的 string 读取接口。
- */
-export const CLIENT_ENDPOINT_KEYS = [
- // apiBaseUrl(老主 server xdt-api)已于 2026-07-18 退役(不 bump,删必填字段
- // 对新客户端是纯放松):四块业务消费方分批迁至独立服务(chat-data 删除 /
- // SlackIM→slack-hook / GitHub 反馈→githubApiBaseUrl / Skillhub→
- // skillhubApiBaseUrl)。退役时清单体系尚无已发布的 packaged/mobile 消费者,
- // 正本(=CDN 上传源)已同步删值,无兼容包袱(同 cdnInternalBaseUrl 先例)。
- // 每份清单只描述自身 region 的 auth/业务端点。默认会话读取构建清单;
- // 跨区域组织登录会先加载目标 region 清单,再整体切换 token 消费端点。
- 'authApiBaseUrl',
- // desktop 系统浏览器登录的**服务端托管回调**地址(auth-server 路由,精确值需与
- // 服务端 redirect_uri allowlist 逐字符一致)。非空 = 走托管回调链路:回调页停在
- // 自有域名、授权码由客户端轮询取回,浏览器地址栏不再出现 127.0.0.1 与 code;
- // 空 = 回落到 RFC 8252 loopback(现状行为)。这也是本能力的灰度/回滚开关——
- // 服务端出问题时清空本字段即可回退,客户端不必发版。
- // 不 bump schemaVersion:纯增可选字段,老清单缺失即 '',老客户端按未知字段忽略
- // (同 review / cdnBaseUrl 先例,理由见上方版本注释)。
- 'authDesktopCallbackUrl',
- 'deviceLinkApiBaseUrl',
- 'oauthBrokerApiBaseUrl',
- // oss-server(公开资产直传预签名,当前场景:头像上传)。
- 'ossApiBaseUrl',
- 'heartbeatUrl',
- // Telegram hook is deployed independently from Slack; empty means the
- // current environment has not rolled out Telegram yet.
- 'telegramHookWsUrl',
- // X (Twitter) hook, same deployment model as Telegram; empty (or a manifest
- // that omits the key entirely) means X has not rolled out yet — the Settings
- // card stays hidden, which is the intended gradual-rollout switch.
- 'xHookWsUrl',
- 'slackHookWsUrl',
- 'websiteUrl',
- // model-access-server(登录后自动下发 LLM 网关凭据)的 API 基址。
- 'modelAccessApiBaseUrl',
- // voice-server(一期开通免费语音输入的数据面)API 基址。
- 'voiceApiBaseUrl',
- // github-server(用户反馈 → 官方仓 GitHub issue 的薄代理)的 API 基址。
- 'githubApiBaseUrl',
- // 旧 xd-skillhub-server 的 API 基址。已发布客户端继续消费这个字段,值不得
- // 改指新服务;新客户端只消费下方 cindySkillHubApiBaseUrl。
- 'skillhubApiBaseUrl',
- // cindy-skill-hub-server 的 API 基址。纯增可选字段,不 bump schemaVersion:
- // 老客户端按未知字段忽略,新客户端缺失时明确关闭云端 Skill Hub,不回退旧地址。
- 'cindySkillHubApiBaseUrl',
- // plugin-server(Plugin/Skill 市场、组织管理与发布)的 API 基址。
- 'pluginApiBaseUrl',
- // 更新/hotfix 链的 CDN base(manifest-*.json / hotfix 包 / agent 二进制)。
- 'cdnBaseUrl',
- // 自建线手机整包发现的 mobile-update-server 基址(`${base}/latest`)。仅
- // mobile 自建变体(IS_OTA_SELFHOST)消费,desktop 与 EAS 线不读;清单值
- // 优先于烧包的 EXPO_PUBLIC_XDT_OTA_URL,让已发自建包可远程迁域名。
- // 注意热更通道的 updates.url 仍烧在原生层(expo-updates 架构),不吃本字段。
- 'mobileUpdateBaseUrl',
-] as const;
-
-export type ClientEndpointKey = (typeof CLIENT_ENDPOINT_KEYS)[number];
-
-/** 解析成功后的端点全集(全 key 存在;清单缺失/空白的字段值为 `''`)。 */
-export type ClientEndpointMap = Record<ClientEndpointKey, string>;
-
-/** auth-server 的物理部署区域;与 App 包体的品牌/更新区域是两个独立概念。 */
-export type ClientEndpointRegion = 'cn' | 'global';
-
-export type RealmManifestBaseUrls = Readonly<
- Record<ClientEndpointRegion, string>
->;
-
-/**
- * 可选字符串字段:`review` = 手机版审核模式的**送审版本号**(App 审核期间填
- * 送审构建的二进制版本号,如 "1.4.0")。mobile 启动时用它与自身二进制版本号
- * **严格相等匹配**,且 iOS StoreKit 未识别为 TestFlight 时才进入审核模式:
- * TestFlight 即使版本命中也继续更新;其余命中构建关闭全部 JS 显式更新检查路径(启动
- * JS 热更门 / 整包检查 / resume 静默检查)直接进主界面,设置页隐藏「检查更新 /
- * 检查整包更新」;desktop 不消费。按版本定向的意义:清单是 region 级共享文件,
- * 版本匹配把影响面从"全量用户"收窄到"同版本号的构建"——存量其它版本用户的
- * 更新检查与强更通道不受影响。注意命中粒度是**版本号而非送审构建本身**:
- * app.json 的 version 为 iOS/Android 各变体共用,若送审版本号与其它平台/变体
- * 正在线上跑的版本号相同,这些同版本用户也会进入审核模式(iOS TestFlight 除外);
- * 填写前需确认送审版本号未与其它线上线重叠,或接受重叠期影响。
- * **可选、缺失或空串即关闭**——线上已发布的清单没有该字段,若设为必填会让新
- * 客户端对老清单启动阻断;可选纯增量也是不 bump schemaVersion 的前提(见上方
- * 版本注释)。存在但非 string 视为配置错,整份拒绝(配置错要炸出来,不静默猜测)。
- * 覆盖边界与运维义务(填写前必须知晓):
- * - **管不到 expo-updates 原生层**:CheckOnLaunch 是 build-time 原生配置
- * (当前烘焙 ALWAYS),冷启动仍会后台静默 check+下载、下次启动生效——
- * 该缺口无法用运行时清单字段封,审核窗口内需同时冻结热更发布;
- * - 送审版本过审对外发布后必须及时把该字段清回 ""(或删除),否则线上同
- * 版本的非 TestFlight 用户会一直处于审核模式、收不到后续 JS 更新检查与强更提示。
- */
-export const CLIENT_ENDPOINT_REVIEW_KEY = 'review';
-
-/** 各字段允许的 URL 协议白名单。 */
-const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {
- authApiBaseUrl: ['https:'],
- authDesktopCallbackUrl: ['https:'],
- deviceLinkApiBaseUrl: ['https:'],
- oauthBrokerApiBaseUrl: ['https:'],
- ossApiBaseUrl: ['https:'],
- heartbeatUrl: ['https:'],
- telegramHookWsUrl: ['wss:'],
- xHookWsUrl: ['wss:'],
- slackHookWsUrl: ['wss:'],
- websiteUrl: ['https:'],
- modelAccessApiBaseUrl: ['https:'],
- voiceApiBaseUrl: ['https:'],
- githubApiBaseUrl: ['https:'],
- skillhubApiBaseUrl: ['https:'],
- cindySkillHubApiBaseUrl: ['https:'],
- pluginApiBaseUrl: ['https:'],
- cdnBaseUrl: ['https:'],
- mobileUpdateBaseUrl: ['https:'],
-};
-
-/** 解析选项;allowHttp 仅供 dev 本地文件路径(endpoint.local.json 等)开启。 */
-export interface ParseClientEndpointManifestOptions {
- /** true 时 https-only 字段追加接受 http:、wss 字段追加 ws:(localhost 场景)。 */
- allowHttp?: boolean;
- /** 加载指定区域的清单时必须提供;清单自报区域不一致或缺失会整份拒绝。 */
- expectedRegion?: ClientEndpointRegion;
-}
-
-// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
-function trimTrailingSlashes(s: string): string {
- let end = s.length;
- while (end > 0 && s.charCodeAt(end - 1) === 0x2f) end -= 1;
- return s.slice(0, end);
-}
-
-function allowedProtocols(
- key: ClientEndpointKey,
- allowHttp: boolean,
-): readonly string[] {
- const base = FIELD_PROTOCOLS[key];
- if (!allowHttp) return base;
- const relaxed = [...base];
- if (base.includes('https:') && !base.includes('http:')) relaxed.push('http:');
- if (base.includes('wss:') && !base.includes('ws:')) relaxed.push('ws:');
- return relaxed;
-}
-
-export type ParseClientEndpointManifestResult =
- | {
- ok: true;
- endpoints: ClientEndpointMap;
- reviewVersion: string | null;
- /** 可选诊断元数据;缺失时由受信任清单地址确定区域。 */
- region: ClientEndpointRegion | null;
- }
- | { ok: false; reason: string };
-
-/**
- * 解析并校验一份清单原文。纯函数,输入任意文本都不会抛出。
- * 端点缺失 / 空白时写入 `''` 并继续;非空值仍校验 URL、协议与凭据;
- * `review` 可选字符串(送审版本号),缺失 / 空白 = null 即审核模式关闭
- * (语义见 CLIENT_ENDPOINT_REVIEW_KEY)。
- */
-export function parseClientEndpointManifest(
- rawText: string,
- options?: ParseClientEndpointManifestOptions,
-): ParseClientEndpointManifestResult {
- let parsed: unknown;
- try {
- parsed = JSON.parse(rawText);
- } catch {
- return { ok: false, reason: 'invalid-json' };
- }
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
- return { ok: false, reason: 'not-an-object' };
- }
- const record = parsed as Record<string, unknown>;
-
- const schemaVersion = record.schemaVersion;
- if (
- typeof schemaVersion !== 'number' ||
- !Number.isInteger(schemaVersion) ||
- schemaVersion < 1
- ) {
- return { ok: false, reason: 'invalid-schema-version' };
- }
- if (schemaVersion > CLIENT_ENDPOINTS_SCHEMA_VERSION) {
- return { ok: false, reason: `unsupported-schema-version:${schemaVersion}` };
- }
-
- const endpoints = {} as ClientEndpointMap;
- for (const key of CLIENT_ENDPOINT_KEYS) {
- const raw = record[key];
- if (raw === undefined || (typeof raw === 'string' && !raw.trim())) {
- endpoints[key] = '';
- continue;
- }
- if (typeof raw !== 'string') {
- return { ok: false, reason: `invalid-field:${key}` };
- }
- const normalized = trimTrailingSlashes(raw.trim());
- let url: URL;
- try {
- url = new URL(normalized);
- } catch {
- return { ok: false, reason: `invalid-field:${key}` };
- }
- if (
- !allowedProtocols(key, options?.allowHttp === true).includes(url.protocol)
- ) {
- return { ok: false, reason: `invalid-protocol:${key}` };
- }
- if (url.username || url.password) {
- return { ok: false, reason: `credentials-in-url:${key}` };
- }
- endpoints[key] = normalized;
- }
-
- const rawReview = record[CLIENT_ENDPOINT_REVIEW_KEY];
- if (rawReview !== undefined && typeof rawReview !== 'string') {
- return { ok: false, reason: `invalid-field:${CLIENT_ENDPOINT_REVIEW_KEY}` };
- }
- const reviewVersion =
- typeof rawReview === 'string' && rawReview.trim() ? rawReview.trim() : null;
-
- const rawRegion = record.region;
- const region =
- rawRegion === undefined
- ? null
- : rawRegion === 'cn' || rawRegion === 'global'
- ? rawRegion
- : null;
- if (rawRegion !== undefined && region === null) {
- return { ok: false, reason: 'invalid-field:region' };
- }
- if (
- options?.expectedRegion !== undefined &&
- region !== options.expectedRegion
- ) {
- return {
- ok: false,
- reason: `region-mismatch:${options.expectedRegion}:${region ?? 'missing'}`,
- };
- }
-
- return {
- ok: true,
- endpoints,
- reviewVersion,
- region,
- };
-}
-
-export type ResolveClientEndpointsResult =
- | Extract<ParseClientEndpointManifestResult, { ok: true }>
- | { ok: false; reason: string };
-
-/**
- * 解析清单原文 → 完整端点 map(缺失/空白字段补 `''`,无任何本地合并)。
- * rawText 为 null(拉取失败/超时)→ ok:false('fetch-failed'),宿主必须阻断并重试。
- */
-export function resolveClientEndpointsStrict(
- rawText: string | null,
- options?: ParseClientEndpointManifestOptions,
-): ResolveClientEndpointsResult {
- if (rawText === null) {
- return { ok: false, reason: 'fetch-failed' };
- }
- return parseClientEndpointManifest(rawText, options);
-}
+/** Public endpoint contract: schema, trust anchors and discovery without platform IO. */
+export * from './clientEndpointSchema';
+export * from './clientEndpointOrigins';
+export * from './clientEndpointResilience';