sourceServerDirectory.ts 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. /* eslint-disable max-lines -- Source/Profile/Workspace 三实体迁移与凭据重定向需要保持同一事务编排。 */
  2. import { randomUUID } from "node:crypto";
  3. import { join } from "node:path";
  4. import { Emitter, type Event } from "@zcode/rpc";
  5. import {
  6. buildServerRemoteWorkspaceIdentity,
  7. isCredentialDecryptError,
  8. isValidWslUser,
  9. parseRemoteWorkspaceIdentity,
  10. type AppSettings,
  11. type ConnectionProfile,
  12. type DockerProfileTarget,
  13. type SourceServerRecord,
  14. type SourceServerWorkspaceHistoryEntry,
  15. type SSHProfileTarget,
  16. type WSLProfileTarget,
  17. type RemoteWorkspaceSessionEntry,
  18. type RemoteTarget,
  19. type SourceServerDeclaredWorkspaceWire,
  20. } from "@zcode/shared";
  21. import type {
  22. ICredentialService,
  23. ISettingService,
  24. UpdateConnectionProfileInput,
  25. } from "@zcode/services";
  26. import {
  27. getDataBaseDir,
  28. migrateControllerRemoteWorkspaceIdentity,
  29. type ControllerRemoteIdentityMigrationReport,
  30. } from "@zcode/services/node";
  31. export interface SourceServerDirectoryOptions {
  32. settingService: ISettingService;
  33. credentialService: ICredentialService;
  34. createProfileId?: () => string;
  35. now?: () => number;
  36. migrateControllerIdentity?: (input: {
  37. oldWorkspaceKey: string;
  38. newWorkspaceKey: string;
  39. }) => Promise<ControllerRemoteIdentityMigrationReport>;
  40. /** 远端 identity 被 canonical 覆盖等非错误诊断信息;生产环境应注入 no-op。 */
  41. logDebug?: (message: string) => void;
  42. /** 可恢复的降级(如凭据无法解密被跳过);生产环境保留。 */
  43. logWarn?: (message: string) => void;
  44. }
  45. export interface SourceServerHandshakeRecord {
  46. sourceServerId: string;
  47. osUser?: string;
  48. hostname?: string;
  49. version: string;
  50. connectedAt?: number;
  51. workspaces?: readonly SourceServerDeclaredWorkspaceWire[];
  52. }
  53. export interface SourceServerHandshakeResult {
  54. identityChanged: boolean;
  55. migrationFailures: string[];
  56. effectiveProfileId: string;
  57. effectiveProfile: ConnectionProfile;
  58. }
  59. function isActiveProfile(profile: ConnectionProfile): boolean {
  60. return profile.lifecycleState !== "retired";
  61. }
  62. function resolveDefaultSourceDisplayName(
  63. profile: ConnectionProfile,
  64. handshake: SourceServerHandshakeRecord,
  65. ): string {
  66. // Bug 原因:SSH alias 已持久化在线路 Profile 中,但设备首次握手只用 hostname/osUser 生成名称,
  67. // 导致用户精心维护的可读 alias 被随机容器 hostname 覆盖。alias 只作为首次展示默认值,
  68. // 已存在设备仍由调用方优先保留 displayName,且这里不参与任何 identity 计算。
  69. const sshAlias =
  70. profile.target.kind === "ssh" ? profile.target.sshConfigAlias?.trim() : undefined;
  71. return (
  72. sshAlias ||
  73. [handshake.hostname, handshake.osUser]
  74. .filter((value): value is string => Boolean(value?.trim()))
  75. .join(" · ") ||
  76. handshake.sourceServerId
  77. );
  78. }
  79. export interface SourceServerDirectorySnapshot {
  80. profiles: ConnectionProfile[];
  81. servers: SourceServerRecord[];
  82. workspaceHistory: SourceServerWorkspaceHistoryEntry[];
  83. }
  84. export interface SourceServerReconnectCandidate {
  85. profile: ConnectionProfile;
  86. target: Exclude<RemoteTarget, { kind: "server" }>;
  87. }
  88. type LegacySourceWorkspaceEntry = RemoteWorkspaceSessionEntry & {
  89. target: Exclude<RemoteWorkspaceSessionEntry["target"], { kind: "server" }>;
  90. };
  91. function routeKey(
  92. entry: Extract<NonNullable<AppSettings["lastWorkspaceSession"]>[number], { kind: "remote" }>,
  93. ): string | null {
  94. const target = entry.target;
  95. switch (target.kind) {
  96. case "ssh":
  97. return [
  98. "ssh",
  99. target.host.trim().toLowerCase(),
  100. String(target.port ?? 22),
  101. target.username.trim(),
  102. target.privateKeyPath?.trim() ?? "",
  103. ].join("\u0000");
  104. case "wsl":
  105. return [
  106. "wsl",
  107. target.distro?.trim().toLowerCase() ?? "default",
  108. target.user?.trim().toLowerCase() ?? "",
  109. ].join("\u0000");
  110. case "docker":
  111. return ["docker", target.container.trim()].join("\u0000");
  112. case "server":
  113. return null;
  114. }
  115. }
  116. function profileTargetIdentityKey(
  117. target: SSHProfileTarget | WSLProfileTarget | DockerProfileTarget,
  118. ): string {
  119. switch (target.kind) {
  120. case "ssh":
  121. // assetInstallMode、alias 和 resourcePackages 只影响部署/展示,不是连接身份。
  122. return JSON.stringify({
  123. kind: "ssh",
  124. host: target.host.trim().toLowerCase(),
  125. port: target.port ?? 22,
  126. username: target.username.trim(),
  127. privateKeyPath: target.privateKeyPath?.trim() ?? "",
  128. });
  129. case "wsl":
  130. return JSON.stringify({
  131. kind: "wsl",
  132. distro: target.distro?.trim() ?? "",
  133. user: target.user?.trim() ?? "",
  134. });
  135. case "docker":
  136. return JSON.stringify({ kind: "docker", container: target.container.trim() });
  137. }
  138. }
  139. function newCredentialKey(profileId: string, kind: "password" | "private-key-passphrase"): string {
  140. return `connection-profile:${profileId}:${kind}`;
  141. }
  142. export class SourceServerDirectory {
  143. private readonly createProfileId: () => string;
  144. private readonly now: () => number;
  145. private initializePromise: Promise<void> | null = null;
  146. private writeChain = Promise.resolve();
  147. private readonly changeEmitter = new Emitter<void>();
  148. /** 当前 enqueue 操作内是否发生过成功的持久化写入;enqueue 串行执行,实例字段无并发窗口。 */
  149. private didPersistInCurrentOperation = false;
  150. private readonly migrateControllerIdentity: NonNullable<
  151. SourceServerDirectoryOptions["migrateControllerIdentity"]
  152. >;
  153. public constructor(private readonly options: SourceServerDirectoryOptions) {
  154. this.createProfileId = options.createProfileId ?? randomUUID;
  155. this.now = options.now ?? Date.now;
  156. this.migrateControllerIdentity =
  157. options.migrateControllerIdentity ??
  158. (async (input) =>
  159. await migrateControllerRemoteWorkspaceIdentity({
  160. dbPath: join(getDataBaseDir(), ".zcode", "v2", "tasks-index.sqlite"),
  161. ...input,
  162. }));
  163. }
  164. /** 目录持久化成功后的统一变更通知,管理服务负责将其映射为 generation。 */
  165. public readonly onDidChange: Event<void> = this.changeEmitter.event;
  166. public async initialize(): Promise<void> {
  167. if (!this.initializePromise) {
  168. const flight = this.enqueue(async () => {
  169. let settings = await this.options.settingService.get();
  170. if (settings.sourceServerDirectoryMigrationVersion !== 1) {
  171. await this.migrateLegacyRemoteEntries(settings);
  172. settings = await this.options.settingService.get();
  173. }
  174. await this.repairDanglingProfileCredentials(settings);
  175. });
  176. this.initializePromise = flight;
  177. }
  178. const flight = this.initializePromise;
  179. try {
  180. await flight;
  181. } catch (error) {
  182. // Bug 原因:失败 flight 若永久缓存,临时 settings/credential IO 故障会让本 Host
  183. // 生命周期内所有 Source Server 操作持续复用同一个 rejected promise。
  184. if (this.initializePromise === flight) this.initializePromise = null;
  185. throw error;
  186. }
  187. }
  188. public async snapshot(): Promise<SourceServerDirectorySnapshot> {
  189. await this.initialize();
  190. const settings = await this.options.settingService.get();
  191. return {
  192. profiles: [...(settings.connectionProfiles ?? [])],
  193. servers: [...(settings.sourceServers ?? [])],
  194. workspaceHistory: [...(settings.sourceServerWorkspaceHistory ?? [])],
  195. };
  196. }
  197. public async resolveLegacyWorkspaceIdentity(input: {
  198. profileId: string;
  199. workspacePath: string;
  200. fallback: string;
  201. }): Promise<string> {
  202. await this.initialize();
  203. const settings = await this.options.settingService.get();
  204. const historical = (settings.sourceServerWorkspaceHistory ?? []).find(
  205. (entry) => entry.profileId === input.profileId && entry.workspacePath === input.workspacePath,
  206. )?.legacyWorkspaceIdentity;
  207. // Bug 原因:Renderer stable identity 曾覆盖当前 route hint,导致旧 alias 行丢失时无法命中
  208. // 更精确的历史 key。legacy hint 的优先级属于 Host Directory 权威,不允许 UI 决定。
  209. return historical?.trim() || input.fallback;
  210. }
  211. public async ensureProfile(
  212. target: Exclude<RemoteTarget, { kind: "server" }>,
  213. options: { deferCredentials?: boolean } = {},
  214. ): Promise<ConnectionProfile> {
  215. await this.initialize();
  216. return await this.enqueue(async () => {
  217. const settings = await this.options.settingService.get();
  218. const normalizedTarget = this.profileTargetFromRemote(target);
  219. const targetKey = profileTargetIdentityKey(normalizedTarget);
  220. const existing = (settings.connectionProfiles ?? []).find(
  221. (profile) =>
  222. isActiveProfile(profile) &&
  223. profile.transport === target.kind &&
  224. profileTargetIdentityKey(profile.target) === targetKey,
  225. );
  226. // 连接结果尚未确定时不能覆盖凭据;在线 Source 可能完全跳过本次认证。
  227. if (existing && options.deferCredentials) return existing;
  228. if (existing) {
  229. const credentialMutation = await this.persistProfileCredentials(
  230. existing.profileId,
  231. target,
  232. existing.target,
  233. );
  234. const nextTarget =
  235. normalizedTarget.kind === "ssh" && credentialMutation.target.kind === "ssh"
  236. ? {
  237. ...normalizedTarget,
  238. ...(credentialMutation.target.passwordCredentialKey
  239. ? {
  240. passwordCredentialKey: credentialMutation.target.passwordCredentialKey,
  241. }
  242. : {}),
  243. ...(normalizedTarget.privateKeyPath &&
  244. credentialMutation.target.privateKeyPassphraseCredentialKey
  245. ? {
  246. privateKeyPassphraseCredentialKey:
  247. credentialMutation.target.privateKeyPassphraseCredentialKey,
  248. }
  249. : {}),
  250. }
  251. : credentialMutation.target;
  252. if (JSON.stringify(nextTarget) === JSON.stringify(existing.target)) {
  253. return existing;
  254. }
  255. const updated = {
  256. ...existing,
  257. target: nextTarget,
  258. } as ConnectionProfile;
  259. try {
  260. await this.persistSettings({
  261. connectionProfiles: (settings.connectionProfiles ?? []).map((profile) =>
  262. profile.profileId === existing.profileId ? updated : profile,
  263. ),
  264. });
  265. return updated;
  266. } catch (error) {
  267. await credentialMutation.rollback();
  268. throw error;
  269. }
  270. }
  271. const profileId = this.createProfileId();
  272. const credentialMutation = options.deferCredentials
  273. ? { target: normalizedTarget, rollback: async () => undefined }
  274. : await this.persistProfileCredentials(profileId, target, normalizedTarget);
  275. const profile = {
  276. profileId,
  277. transport: target.kind,
  278. target: credentialMutation.target,
  279. displayName:
  280. normalizedTarget.kind === "ssh"
  281. ? (normalizedTarget.sshConfigAlias ?? normalizedTarget.host)
  282. : normalizedTarget.kind === "wsl"
  283. ? (normalizedTarget.distro ?? "WSL")
  284. : normalizedTarget.container,
  285. createdAt: this.now(),
  286. } as ConnectionProfile;
  287. try {
  288. await this.persistSettings({
  289. connectionProfiles: [...(settings.connectionProfiles ?? []), profile],
  290. });
  291. return profile;
  292. } catch (error) {
  293. await credentialMutation.rollback();
  294. throw error;
  295. }
  296. });
  297. }
  298. public async listStartupReconnectCandidates(): Promise<SourceServerReconnectCandidate[]> {
  299. const snapshot = await this.snapshot();
  300. const candidates: SourceServerReconnectCandidate[] = [];
  301. // Bug 原因:Directory 数组按 Source 首次发现顺序持久化。冷启动 worker 有并发上限时,
  302. // 旧 Source 会先占满槽位,最近活动 workspace 的 Source 反而可能排到后面并超时。
  303. // 候选队列以最近在线事实排序;单个 Source 内仍由 preferred Profile 决定连接路由。
  304. // 保存的连接不因七天未使用失去启动重连资格;凭据和全局关闭开关继续由原入口守卫。
  305. const serversByRecentActivity = [...snapshot.servers].sort(
  306. (left, right) => (right.lastOnlineAt ?? 0) - (left.lastOnlineAt ?? 0),
  307. );
  308. for (const server of serversByRecentActivity) {
  309. const candidate = await this.resolveSilentSourceRoute(snapshot, server);
  310. if (candidate) candidates.push(candidate);
  311. }
  312. // 首次握手失败的已保存 Profile 仍是有效连接;是否保留由 Host 的 SQLite 成员表筛选。
  313. for (const profile of snapshot.profiles) {
  314. if (!isActiveProfile(profile) || profile.sourceServerId) continue;
  315. const target = await this.resolveSilentTarget(profile);
  316. if (target) candidates.push({ profile, target });
  317. }
  318. return candidates;
  319. }
  320. /**
  321. * 设备级生命周期操作(停止远端服务等)在设备离线时的路由:与启动静默重连候选同一排序,
  322. * 默认连接优先、再按最近连接时间,取第一条能静默取得凭据的连接;都取不到时返回
  323. * `credentials-required`。在线连接由连接管理器优先使用,不经过这里。
  324. */
  325. public async resolveSourceLifecycleRoute(
  326. sourceServerId: string,
  327. ): Promise<SourceServerReconnectCandidate> {
  328. const snapshot = await this.snapshot();
  329. const server = snapshot.servers.find((entry) => entry.sourceServerId === sourceServerId);
  330. if (!server) throw new Error(`Unknown Source Server: ${sourceServerId}`);
  331. const route = await this.resolveSilentSourceRoute(snapshot, server);
  332. if (route) return route;
  333. throw Object.assign(
  334. new Error(`Source Server requires interactive credentials: ${sourceServerId}`),
  335. { code: "credentials-required" },
  336. );
  337. }
  338. private async resolveSilentSourceRoute(
  339. snapshot: SourceServerDirectorySnapshot,
  340. server: SourceServerRecord,
  341. ): Promise<SourceServerReconnectCandidate | undefined> {
  342. const profiles = snapshot.profiles
  343. .filter(
  344. (profile) => isActiveProfile(profile) && profile.sourceServerId === server.sourceServerId,
  345. )
  346. .sort((left, right) => {
  347. if (left.profileId === server.preferredProfileId) return -1;
  348. if (right.profileId === server.preferredProfileId) return 1;
  349. return (right.lastConnectedAt ?? 0) - (left.lastConnectedAt ?? 0);
  350. });
  351. for (const profile of profiles) {
  352. const target = await this.resolveSilentTarget(profile);
  353. if (target) return { profile, target };
  354. }
  355. return undefined;
  356. }
  357. public async recordLastOnline(sourceServerId: string, timestamp: number): Promise<void> {
  358. await this.initialize();
  359. await this.enqueue(async () => {
  360. const settings = await this.options.settingService.get();
  361. const server = settings.sourceServers?.find(
  362. (entry) => entry.sourceServerId === sourceServerId,
  363. );
  364. // 断线事件可能晚于重连握手或删除;只推进已存在设备的时间,不能倒退或复活记录。
  365. if (!server || timestamp <= (server.lastOnlineAt ?? 0)) return;
  366. await this.persistSettings({
  367. sourceServers: settings.sourceServers!.map((entry) =>
  368. entry === server ? { ...entry, lastOnlineAt: timestamp } : entry,
  369. ),
  370. });
  371. });
  372. }
  373. public async recordHandshake(
  374. profileId: string,
  375. handshake: SourceServerHandshakeRecord,
  376. options: { confirmIdentityChange?: boolean } = {},
  377. ): Promise<SourceServerHandshakeResult> {
  378. await this.initialize();
  379. return await this.enqueue(async () => {
  380. const settings = await this.options.settingService.get();
  381. const profiles = [...(settings.connectionProfiles ?? [])];
  382. const profileIndex = profiles.findIndex((profile) => profile.profileId === profileId);
  383. if (profileIndex < 0) throw new Error(`Unknown Connection Profile: ${profileId}`);
  384. const connectedAt = handshake.connectedAt ?? this.now();
  385. const currentProfile = profiles[profileIndex]!;
  386. if (!isActiveProfile(currentProfile)) {
  387. throw new Error(`Connection Profile is retired: ${profileId}`);
  388. }
  389. const previousSourceServerId = currentProfile.sourceServerId;
  390. const identityChanged =
  391. Boolean(previousSourceServerId) && previousSourceServerId !== handshake.sourceServerId;
  392. if (identityChanged && options.confirmIdentityChange !== true) {
  393. // Bug 根因:旧实现先改绑 Profile/history,再把 identityChanged 返回给上层,用户确认
  394. // 已经来不及。pending 阶段必须严格零写入。
  395. return {
  396. identityChanged: true,
  397. migrationFailures: [],
  398. effectiveProfileId: profileId,
  399. effectiveProfile: currentProfile,
  400. };
  401. }
  402. if (identityChanged) {
  403. return await this.commitIdentityReplacement({
  404. settings,
  405. currentProfile,
  406. handshake,
  407. connectedAt,
  408. });
  409. }
  410. profiles[profileIndex] = {
  411. ...currentProfile,
  412. sourceServerId: handshake.sourceServerId,
  413. lastConnectedAt: connectedAt,
  414. lastConnectError: undefined,
  415. lifecycleState: "active",
  416. } as ConnectionProfile;
  417. const servers = [...(settings.sourceServers ?? [])];
  418. const serverIndex = servers.findIndex(
  419. (server) => server.sourceServerId === handshake.sourceServerId,
  420. );
  421. const defaultDisplayName = resolveDefaultSourceDisplayName(currentProfile, handshake);
  422. const previousServer = serverIndex >= 0 ? servers[serverIndex] : undefined;
  423. const nextServer: SourceServerRecord = {
  424. sourceServerId: handshake.sourceServerId,
  425. displayName: previousServer?.displayName ?? defaultDisplayName,
  426. ...(handshake.osUser ? { osUser: handshake.osUser } : {}),
  427. ...(handshake.hostname ? { hostname: handshake.hostname } : {}),
  428. lastSeenVersion: handshake.version,
  429. lastOnlineAt: connectedAt,
  430. preferredProfileId: previousServer?.preferredProfileId ?? profileId,
  431. installState: "installed",
  432. declaredWorkspaces: projectDeclaredWorkspaces(
  433. handshake.sourceServerId,
  434. handshake.workspaces ?? [],
  435. this.options.logDebug,
  436. ),
  437. };
  438. if (serverIndex >= 0) servers[serverIndex] = nextServer;
  439. else servers.push(nextServer);
  440. const workspaceHistory = (settings.sourceServerWorkspaceHistory ?? []).map((entry) =>
  441. entry.profileId === profileId
  442. ? {
  443. ...entry,
  444. sourceServerId: handshake.sourceServerId,
  445. workspaceIdentity: buildServerRemoteWorkspaceIdentity({
  446. serverId: handshake.sourceServerId,
  447. workspacePath: entry.workspacePath,
  448. }),
  449. }
  450. : entry,
  451. );
  452. const migrationFailures: string[] = [];
  453. for (const entry of workspaceHistory) {
  454. if (
  455. entry.profileId !== profileId ||
  456. !entry.legacyWorkspaceIdentity ||
  457. !entry.workspaceIdentity ||
  458. entry.legacyWorkspaceIdentity === entry.workspaceIdentity
  459. ) {
  460. continue;
  461. }
  462. const report = await this.migrateControllerIdentity({
  463. oldWorkspaceKey: entry.legacyWorkspaceIdentity,
  464. newWorkspaceKey: entry.workspaceIdentity,
  465. });
  466. if (report.status === "failed") {
  467. migrationFailures.push(report.error ?? entry.workspacePath);
  468. }
  469. }
  470. await this.persistSettings({
  471. connectionProfiles: profiles,
  472. sourceServers: servers,
  473. sourceServerWorkspaceHistory: workspaceHistory,
  474. });
  475. return {
  476. identityChanged: false,
  477. migrationFailures,
  478. effectiveProfileId: profileId,
  479. effectiveProfile: profiles[profileIndex]!,
  480. };
  481. });
  482. }
  483. public async recordWorkspaceOpen(input: {
  484. profileId: string;
  485. sourceServerId: string;
  486. workspacePath: string;
  487. workspaceIdentity: string;
  488. workspacePurpose?: "project" | "conversation";
  489. legacyWorkspaceIdentity?: string;
  490. openedAt?: number;
  491. signal?: AbortSignal;
  492. }): Promise<void> {
  493. input.signal?.throwIfAborted();
  494. if (input.workspacePurpose === "conversation") {
  495. // conversation backing workspace 只属于设备级 canonical path,不得污染 strict project history。
  496. return;
  497. }
  498. await this.initialize();
  499. input.signal?.throwIfAborted();
  500. await this.enqueue(async () => {
  501. input.signal?.throwIfAborted();
  502. const settings = await this.options.settingService.get();
  503. input.signal?.throwIfAborted();
  504. const history = [...(settings.sourceServerWorkspaceHistory ?? [])];
  505. const index = history.findIndex(
  506. (entry) =>
  507. entry.sourceServerId === input.sourceServerId &&
  508. entry.workspacePath === input.workspacePath,
  509. );
  510. const existing = index >= 0 ? history[index] : undefined;
  511. const legacyWorkspaceIdentity =
  512. input.legacyWorkspaceIdentity?.trim() || existing?.legacyWorkspaceIdentity?.trim();
  513. const next: SourceServerWorkspaceHistoryEntry = {
  514. workspacePath: input.workspacePath,
  515. workspaceIdentity: input.workspaceIdentity,
  516. // Bug 原因:stable identity 重连不会再次携带 route hint;整行覆盖会抹掉冻结的
  517. // legacy identity,下一次启动无法投影 stable key,也读不到 Profile 密码。
  518. ...(legacyWorkspaceIdentity ? { legacyWorkspaceIdentity } : {}),
  519. profileId: input.profileId,
  520. sourceServerId: input.sourceServerId,
  521. lastOpenedAt: input.openedAt ?? this.now(),
  522. };
  523. if (index >= 0) history[index] = next;
  524. else history.push(next);
  525. // 同一 JS turn 内从最后一次 abort 检查直接发起持久化,不再引入 await 窗口;取消
  526. // 若发生在前一段异步读取期间,会在这里阻止任何 workspace history 写入。
  527. input.signal?.throwIfAborted();
  528. await this.persistSettings({
  529. sourceServerWorkspaceHistory: history,
  530. });
  531. });
  532. }
  533. public async recordConversationWorkspace(
  534. sourceServerId: string,
  535. workspacePath: string,
  536. ): Promise<void> {
  537. const normalizedPath = workspacePath.trim();
  538. if (!sourceServerId.trim() || !normalizedPath) {
  539. throw new Error("Source conversation workspace requires sourceServerId and workspacePath");
  540. }
  541. await this.initialize();
  542. await this.enqueue(async () => {
  543. const settings = await this.options.settingService.get();
  544. const current = settings.remoteConversationWorkspaceBySourceServerId ?? {};
  545. // Bug 原因:旧流程可能先把 backing path 当普通 project 写入 strict history。
  546. // canonical conversation 一旦确认,必须在同一 Directory 写事务中清掉同 Source/path
  547. // 的污染项;其它设备的同路径与同设备真实项目都保留。
  548. const projectHistory = (settings.sourceServerWorkspaceHistory ?? []).filter(
  549. (entry) =>
  550. entry.sourceServerId !== sourceServerId || entry.workspacePath !== normalizedPath,
  551. );
  552. await this.persistSettings({
  553. remoteConversationWorkspaceBySourceServerId: {
  554. ...current,
  555. [sourceServerId]: {
  556. workspacePath: normalizedPath,
  557. lastResolvedAt: this.now(),
  558. },
  559. },
  560. sourceServerWorkspaceHistory: projectHistory,
  561. });
  562. });
  563. }
  564. public async renameSource(sourceServerId: string, displayName: string): Promise<void> {
  565. await this.initialize();
  566. const normalized = displayName.trim();
  567. if (!normalized) throw new Error("Source Server display name is required");
  568. await this.enqueue(async () => {
  569. const settings = await this.options.settingService.get();
  570. const servers = [...(settings.sourceServers ?? [])];
  571. const index = servers.findIndex((server) => server.sourceServerId === sourceServerId);
  572. if (index < 0) throw new Error(`Unknown Source Server: ${sourceServerId}`);
  573. servers[index] = { ...servers[index]!, displayName: normalized };
  574. await this.persistSettings({ sourceServers: servers });
  575. });
  576. }
  577. public async renameProfile(profileId: string, displayName: string): Promise<void> {
  578. await this.initialize();
  579. const normalized = displayName.trim();
  580. if (!normalized) throw new Error("Connection Profile display name is required");
  581. await this.enqueue(async () => {
  582. const settings = await this.options.settingService.get();
  583. const profiles = [...(settings.connectionProfiles ?? [])];
  584. const index = profiles.findIndex((profile) => profile.profileId === profileId);
  585. if (index < 0) throw new Error(`Unknown Connection Profile: ${profileId}`);
  586. profiles[index] = {
  587. ...profiles[index]!,
  588. displayName: normalized,
  589. } as ConnectionProfile;
  590. await this.persistSettings({
  591. connectionProfiles: profiles,
  592. });
  593. });
  594. }
  595. public async updateProfile(input: UpdateConnectionProfileInput): Promise<void> {
  596. await this.initialize();
  597. const profileDisplayName = input.profileDisplayName.trim();
  598. const sourceDisplayName = input.sourceDisplayName?.trim();
  599. if (!profileDisplayName) {
  600. throw new Error("Connection Profile display name is required");
  601. }
  602. if (input.sourceDisplayName !== undefined && !sourceDisplayName) {
  603. throw new Error("Source Server display name is required");
  604. }
  605. await this.enqueue(async () => {
  606. const settings = await this.options.settingService.get();
  607. const profiles = [...(settings.connectionProfiles ?? [])];
  608. const profileIndex = profiles.findIndex((profile) => profile.profileId === input.profileId);
  609. if (profileIndex < 0) {
  610. throw new Error(`Unknown Connection Profile: ${input.profileId}`);
  611. }
  612. const currentProfile = profiles[profileIndex]!;
  613. if (!isActiveProfile(currentProfile)) {
  614. throw new Error(`Connection Profile is retired: ${input.profileId}`);
  615. }
  616. if (currentProfile.transport !== input.target.kind) {
  617. throw new Error("Connection Profile transport cannot be changed");
  618. }
  619. const normalizedTarget = this.profileTargetFromRemote(input.target);
  620. if (
  621. normalizedTarget.kind === "ssh" &&
  622. (!normalizedTarget.host ||
  623. !normalizedTarget.username ||
  624. normalizedTarget.port === undefined ||
  625. !Number.isInteger(normalizedTarget.port) ||
  626. normalizedTarget.port <= 0 ||
  627. normalizedTarget.port > 65_535)
  628. ) {
  629. throw new Error("SSH connection details are invalid");
  630. }
  631. if (
  632. normalizedTarget.kind === "wsl" &&
  633. normalizedTarget.user &&
  634. !isValidWslUser(normalizedTarget.user)
  635. ) {
  636. throw new Error("WSL user is invalid");
  637. }
  638. if (normalizedTarget.kind === "docker" && !normalizedTarget.container) {
  639. throw new Error("Docker container is required");
  640. }
  641. const previousCredentials = new Map<string, string | null>();
  642. const rememberCredential = async (key: string) => {
  643. if (previousCredentials.has(key)) return;
  644. previousCredentials.set(key, await this.loadUsableCredential(key));
  645. };
  646. const saveCredential = async (key: string, value: string) => {
  647. await rememberCredential(key);
  648. await this.options.credentialService.save(key, value);
  649. };
  650. const deleteCredential = async (key?: string) => {
  651. if (!key) return;
  652. await rememberCredential(key);
  653. await this.options.credentialService.delete(key);
  654. };
  655. let nextTarget = normalizedTarget;
  656. try {
  657. if (
  658. currentProfile.target.kind === "ssh" &&
  659. normalizedTarget.kind === "ssh" &&
  660. input.target.kind === "ssh"
  661. ) {
  662. if (!input.sshAuthMethod) {
  663. throw new Error("SSH authentication method is required");
  664. }
  665. if (input.sshAuthMethod === "password") {
  666. const { privateKeyPath: _privateKeyPath, ...passwordTarget } = normalizedTarget;
  667. const passwordCredentialKey =
  668. currentProfile.target.passwordCredentialKey ??
  669. newCredentialKey(input.profileId, "password");
  670. const password = input.target.password?.trim();
  671. const savedPassword = currentProfile.target.passwordCredentialKey
  672. ? await this.loadUsableCredential(currentProfile.target.passwordCredentialKey)
  673. : null;
  674. if (!password && !savedPassword) {
  675. throw new Error("SSH password is required");
  676. }
  677. if (password) {
  678. await saveCredential(passwordCredentialKey, password);
  679. }
  680. await deleteCredential(currentProfile.target.privateKeyPassphraseCredentialKey);
  681. nextTarget = {
  682. ...passwordTarget,
  683. passwordCredentialKey,
  684. } as SSHProfileTarget;
  685. } else {
  686. if (!normalizedTarget.privateKeyPath?.trim()) {
  687. throw new Error("SSH private key path is required");
  688. }
  689. await deleteCredential(currentProfile.target.passwordCredentialKey);
  690. let privateKeyPassphraseCredentialKey: string | undefined;
  691. const privateKeyPassphrase = input.target.privateKeyPassphrase?.trim();
  692. if (privateKeyPassphrase) {
  693. privateKeyPassphraseCredentialKey =
  694. currentProfile.target.privateKeyPassphraseCredentialKey ??
  695. newCredentialKey(input.profileId, "private-key-passphrase");
  696. await saveCredential(privateKeyPassphraseCredentialKey, privateKeyPassphrase);
  697. } else if (
  698. currentProfile.target.privateKeyPath === normalizedTarget.privateKeyPath &&
  699. currentProfile.target.privateKeyPassphraseCredentialKey
  700. ) {
  701. privateKeyPassphraseCredentialKey =
  702. currentProfile.target.privateKeyPassphraseCredentialKey;
  703. } else {
  704. await deleteCredential(currentProfile.target.privateKeyPassphraseCredentialKey);
  705. }
  706. nextTarget = {
  707. ...normalizedTarget,
  708. ...(privateKeyPassphraseCredentialKey ? { privateKeyPassphraseCredentialKey } : {}),
  709. } as SSHProfileTarget;
  710. }
  711. }
  712. profiles[profileIndex] = {
  713. ...currentProfile,
  714. displayName: profileDisplayName,
  715. target: nextTarget,
  716. lastConnectError: undefined,
  717. } as ConnectionProfile;
  718. let servers = settings.sourceServers;
  719. if (sourceDisplayName !== undefined) {
  720. if (!currentProfile.sourceServerId) {
  721. throw new Error("Unidentified Connection Profile cannot rename a Source Server");
  722. }
  723. servers = [...(settings.sourceServers ?? [])];
  724. const serverIndex = servers.findIndex(
  725. (server) => server.sourceServerId === currentProfile.sourceServerId,
  726. );
  727. if (serverIndex < 0) {
  728. throw new Error(`Unknown Source Server: ${currentProfile.sourceServerId}`);
  729. }
  730. servers[serverIndex] = {
  731. ...servers[serverIndex]!,
  732. displayName: sourceDisplayName,
  733. };
  734. }
  735. // 根因:旧管理面只能改线路别名,用户修改地址时只能新建 Profile,进而把同一
  736. // Source 的 workspace/task 历史割裂。这里原位更新 Profile,并把凭据与 settings
  737. // 放在同一回滚边界内,确保 profileId/sourceServerId/history 全部保持稳定。
  738. await this.persistSettings({
  739. connectionProfiles: profiles,
  740. ...(servers ? { sourceServers: servers } : {}),
  741. });
  742. } catch (error) {
  743. await this.restoreCredentials(previousCredentials);
  744. throw error;
  745. }
  746. });
  747. }
  748. public async setPreferredProfile(sourceServerId: string, profileId: string): Promise<void> {
  749. await this.initialize();
  750. await this.enqueue(async () => {
  751. const settings = await this.options.settingService.get();
  752. const profile = (settings.connectionProfiles ?? []).find(
  753. (candidate) => candidate.profileId === profileId && isActiveProfile(candidate),
  754. );
  755. if (!profile || profile.sourceServerId !== sourceServerId) {
  756. throw new Error(`Connection Profile ${profileId} does not belong to ${sourceServerId}`);
  757. }
  758. const servers = [...(settings.sourceServers ?? [])];
  759. const index = servers.findIndex((server) => server.sourceServerId === sourceServerId);
  760. if (index < 0) throw new Error(`Unknown Source Server: ${sourceServerId}`);
  761. servers[index] = { ...servers[index]!, preferredProfileId: profileId };
  762. await this.persistSettings({ sourceServers: servers });
  763. });
  764. }
  765. public async resolveProfileTarget(
  766. profileOrId: string | ConnectionProfile,
  767. ): Promise<Exclude<RemoteTarget, { kind: "server" }>> {
  768. // 更新入口传入已核验的同一 Profile,避免凭据异步读取前再次按 ID 改选执行目标。
  769. const profile =
  770. typeof profileOrId === "string"
  771. ? (await this.snapshot()).profiles.find((candidate) => candidate.profileId === profileOrId)
  772. : profileOrId;
  773. if (!profile) throw new Error(`Unknown Connection Profile: ${profileOrId}`);
  774. const profileId = profile.profileId;
  775. if (!isActiveProfile(profile)) throw new Error(`Connection Profile is retired: ${profileId}`);
  776. const target = await this.resolveSilentTarget(profile);
  777. if (!target)
  778. // 普通 Error 丢失“需要人工凭据”的语义,项目入口无法交接向导;沿用公开认证码。
  779. throw Object.assign(
  780. new Error(`Connection Profile requires interactive credentials: ${profileId}`),
  781. { code: "credentials-required" },
  782. );
  783. return target;
  784. }
  785. public async removeProfile(profileId: string): Promise<void> {
  786. await this.initialize();
  787. await this.enqueue(async () => {
  788. const settings = await this.options.settingService.get();
  789. const profiles = [...(settings.connectionProfiles ?? [])];
  790. const profile = profiles.find((candidate) => candidate.profileId === profileId);
  791. if (!profile) return;
  792. const credentialKeys =
  793. profile.target.kind === "ssh"
  794. ? [
  795. profile.target.passwordCredentialKey,
  796. profile.target.privateKeyPassphraseCredentialKey,
  797. ].filter((key): key is string => Boolean(key))
  798. : [];
  799. const previousCredentials = new Map<string, string | null>();
  800. try {
  801. for (const key of credentialKeys) {
  802. previousCredentials.set(key, await this.loadUsableCredential(key));
  803. await this.options.credentialService.delete(key);
  804. }
  805. const remainingProfiles = profiles.filter((candidate) => candidate.profileId !== profileId);
  806. await this.persistSettings({
  807. connectionProfiles: remainingProfiles,
  808. sourceServerWorkspaceHistory: (settings.sourceServerWorkspaceHistory ?? []).filter(
  809. (entry) => entry.profileId !== profileId,
  810. ),
  811. sourceServers: (settings.sourceServers ?? []).map((server) =>
  812. server.preferredProfileId === profileId
  813. ? {
  814. ...server,
  815. preferredProfileId: remainingProfiles.find(
  816. (candidate) =>
  817. isActiveProfile(candidate) &&
  818. candidate.sourceServerId === server.sourceServerId,
  819. )?.profileId,
  820. }
  821. : server,
  822. ),
  823. });
  824. } catch (error) {
  825. await this.restoreCredentials(previousCredentials);
  826. throw error;
  827. }
  828. });
  829. }
  830. public async removeSourceServer(sourceServerId: string): Promise<void> {
  831. await this.initialize();
  832. await this.enqueue(async () => {
  833. const settings = await this.options.settingService.get();
  834. const profiles = [...(settings.connectionProfiles ?? [])];
  835. const removedProfiles = profiles.filter(
  836. (profile) => profile.sourceServerId === sourceServerId,
  837. );
  838. // 幂等空操作:设备无任何本地记录时直接成功返回,不产生写入也不发布变更事件。
  839. const hasAnyRecord =
  840. removedProfiles.length > 0 ||
  841. (settings.sourceServers ?? []).some((server) => server.sourceServerId === sourceServerId) ||
  842. (settings.sourceServerWorkspaceHistory ?? []).some(
  843. (entry) => entry.sourceServerId === sourceServerId,
  844. ) ||
  845. Boolean(settings.remoteConversationWorkspaceBySourceServerId?.[sourceServerId]);
  846. if (!hasAnyRecord) return;
  847. // Bug 原因:识别前写入的 workspace history 尚未回填 sourceServerId,只按设备 id 过滤
  848. // 会留下指向已删 Profile 的孤儿条目;删除面必须同时覆盖被删设备全部 Profile 的条目。
  849. const removedProfileIds = new Set(removedProfiles.map((profile) => profile.profileId));
  850. const credentialKeys = removedProfiles.flatMap((profile) =>
  851. profile.target.kind === "ssh"
  852. ? [
  853. profile.target.passwordCredentialKey,
  854. profile.target.privateKeyPassphraseCredentialKey,
  855. ].filter((key): key is string => Boolean(key))
  856. : [],
  857. );
  858. const previousCredentials = new Map<string, string | null>();
  859. try {
  860. for (const key of credentialKeys) {
  861. previousCredentials.set(key, await this.loadUsableCredential(key));
  862. await this.options.credentialService.delete(key);
  863. }
  864. await this.persistSettings({
  865. connectionProfiles: profiles.filter(
  866. (profile) => profile.sourceServerId !== sourceServerId,
  867. ),
  868. sourceServers: (settings.sourceServers ?? []).filter(
  869. (server) => server.sourceServerId !== sourceServerId,
  870. ),
  871. sourceServerWorkspaceHistory: (settings.sourceServerWorkspaceHistory ?? []).filter(
  872. (entry) =>
  873. entry.sourceServerId !== sourceServerId && !removedProfileIds.has(entry.profileId),
  874. ),
  875. remoteConversationWorkspaceBySourceServerId: Object.fromEntries(
  876. Object.entries(settings.remoteConversationWorkspaceBySourceServerId ?? {}).filter(
  877. ([key]) => key !== sourceServerId,
  878. ),
  879. ),
  880. });
  881. } catch (error) {
  882. await this.restoreCredentials(previousCredentials);
  883. throw error;
  884. }
  885. });
  886. }
  887. public async markSourceUninstalled(profileId: string): Promise<void> {
  888. await this.initialize();
  889. await this.enqueue(async () => {
  890. const settings = await this.options.settingService.get();
  891. const profile = (settings.connectionProfiles ?? []).find(
  892. (candidate) => candidate.profileId === profileId && isActiveProfile(candidate),
  893. );
  894. if (!profile?.sourceServerId) return;
  895. await this.persistSettings({
  896. sourceServers: (settings.sourceServers ?? []).map((server) =>
  897. server.sourceServerId === profile.sourceServerId
  898. ? { ...server, installState: "uninstalled" as const }
  899. : server,
  900. ),
  901. });
  902. });
  903. }
  904. private async commitIdentityReplacement(input: {
  905. settings: AppSettings;
  906. currentProfile: ConnectionProfile;
  907. handshake: SourceServerHandshakeRecord;
  908. connectedAt: number;
  909. }): Promise<SourceServerHandshakeResult> {
  910. const previousSourceServerId = input.currentProfile.sourceServerId!;
  911. const newProfileId = this.createProfileId();
  912. if (newProfileId === input.currentProfile.profileId) {
  913. throw new Error("Identity replacement requires a new Connection Profile id");
  914. }
  915. const createdCredentialKeys: string[] = [];
  916. let target = input.currentProfile.target;
  917. try {
  918. if (input.currentProfile.target.kind === "ssh") {
  919. const password = input.currentProfile.target.passwordCredentialKey
  920. ? await this.loadUsableCredential(input.currentProfile.target.passwordCredentialKey)
  921. : null;
  922. const passphrase = input.currentProfile.target.privateKeyPassphraseCredentialKey
  923. ? await this.loadUsableCredential(
  924. input.currentProfile.target.privateKeyPassphraseCredentialKey,
  925. )
  926. : null;
  927. const passwordCredentialKey =
  928. password === null ? undefined : newCredentialKey(newProfileId, "password");
  929. const privateKeyPassphraseCredentialKey =
  930. passphrase === null
  931. ? undefined
  932. : newCredentialKey(newProfileId, "private-key-passphrase");
  933. if (passwordCredentialKey) {
  934. createdCredentialKeys.push(passwordCredentialKey);
  935. await this.options.credentialService.save(passwordCredentialKey, password!);
  936. }
  937. if (privateKeyPassphraseCredentialKey) {
  938. createdCredentialKeys.push(privateKeyPassphraseCredentialKey);
  939. await this.options.credentialService.save(privateKeyPassphraseCredentialKey, passphrase!);
  940. }
  941. target = {
  942. ...input.currentProfile.target,
  943. passwordCredentialKey,
  944. privateKeyPassphraseCredentialKey,
  945. };
  946. }
  947. const retiredProfile: ConnectionProfile = {
  948. ...input.currentProfile,
  949. lifecycleState: "retired",
  950. retiredReason: "source-reinstalled",
  951. retiredAt: input.connectedAt,
  952. };
  953. const newProfile: ConnectionProfile = {
  954. ...input.currentProfile,
  955. profileId: newProfileId,
  956. sourceServerId: input.handshake.sourceServerId,
  957. target,
  958. lifecycleState: "active",
  959. retiredReason: undefined,
  960. retiredAt: undefined,
  961. lastConnectedAt: input.connectedAt,
  962. lastConnectError: undefined,
  963. createdAt: input.connectedAt,
  964. } as ConnectionProfile;
  965. const profiles = (input.settings.connectionProfiles ?? []).map((profile) =>
  966. profile.profileId === input.currentProfile.profileId ? retiredProfile : profile,
  967. );
  968. profiles.push(newProfile);
  969. const defaultDisplayName = resolveDefaultSourceDisplayName(newProfile, input.handshake);
  970. const servers = [...(input.settings.sourceServers ?? [])];
  971. const oldServerIndex = servers.findIndex(
  972. (server) => server.sourceServerId === previousSourceServerId,
  973. );
  974. if (oldServerIndex >= 0) {
  975. const oldServer = servers[oldServerIndex]!;
  976. servers[oldServerIndex] = {
  977. ...oldServer,
  978. installState: "uninstalled",
  979. preferredProfileId: profiles.find(
  980. (profile) =>
  981. isActiveProfile(profile) && profile.sourceServerId === previousSourceServerId,
  982. )?.profileId,
  983. };
  984. }
  985. const newServerIndex = servers.findIndex(
  986. (server) => server.sourceServerId === input.handshake.sourceServerId,
  987. );
  988. const existingNewServer = newServerIndex >= 0 ? servers[newServerIndex] : undefined;
  989. const newServer: SourceServerRecord = {
  990. sourceServerId: input.handshake.sourceServerId,
  991. displayName: existingNewServer?.displayName ?? defaultDisplayName,
  992. ...(input.handshake.osUser ? { osUser: input.handshake.osUser } : {}),
  993. ...(input.handshake.hostname ? { hostname: input.handshake.hostname } : {}),
  994. lastSeenVersion: input.handshake.version,
  995. lastOnlineAt: input.connectedAt,
  996. preferredProfileId: newProfileId,
  997. installState: "installed",
  998. declaredWorkspaces: projectDeclaredWorkspaces(
  999. input.handshake.sourceServerId,
  1000. input.handshake.workspaces ?? [],
  1001. this.options.logDebug,
  1002. ),
  1003. };
  1004. if (newServerIndex >= 0) servers[newServerIndex] = newServer;
  1005. else servers.push(newServer);
  1006. await this.persistSettings({
  1007. connectionProfiles: profiles,
  1008. sourceServers: servers,
  1009. // 旧 history 保持旧 Source/Profile 身份,不允许随新安装静默改写。
  1010. sourceServerWorkspaceHistory: input.settings.sourceServerWorkspaceHistory ?? [],
  1011. });
  1012. return {
  1013. identityChanged: true,
  1014. migrationFailures: [],
  1015. effectiveProfileId: newProfileId,
  1016. effectiveProfile: newProfile,
  1017. };
  1018. } catch (error) {
  1019. await Promise.all(
  1020. createdCredentialKeys.map(
  1021. async (key) => await this.options.credentialService.delete(key).catch(() => undefined),
  1022. ),
  1023. );
  1024. throw error;
  1025. }
  1026. }
  1027. private async migrateLegacyRemoteEntries(settings: AppSettings): Promise<void> {
  1028. const previousCredentials = new Map<string, string | null>();
  1029. try {
  1030. await this.persistLegacyRemoteEntries(settings, previousCredentials);
  1031. } catch (error) {
  1032. // Bug 原因:legacy 迁移先落新 Profile 凭据、最后提交 Directory settings;settings
  1033. // 写入失败后重试会生成新 profileId,旧 key 因无人引用而永久残留。迁移失败必须在
  1034. // 返回前恢复本轮所有凭据写入,保留 legacy key 供下一次初始化重新迁移。
  1035. await this.restoreCredentials(previousCredentials);
  1036. throw error;
  1037. }
  1038. }
  1039. private async persistLegacyRemoteEntries(
  1040. settings: AppSettings,
  1041. previousCredentials: Map<string, string | null>,
  1042. ): Promise<void> {
  1043. const remoteEntries = (settings.lastWorkspaceSession ?? [])
  1044. .filter((entry) => entry.kind === "remote" && entry.target.kind !== "server")
  1045. .map((entry) => entry as LegacySourceWorkspaceEntry);
  1046. const groups = new Map<string, typeof remoteEntries>();
  1047. for (const entry of remoteEntries) {
  1048. const key = routeKey(entry);
  1049. if (!key) continue;
  1050. const values = groups.get(key) ?? [];
  1051. values.push(entry);
  1052. groups.set(key, values);
  1053. }
  1054. const profiles: ConnectionProfile[] = [];
  1055. const workspaceHistory: SourceServerWorkspaceHistoryEntry[] = [];
  1056. const shouldMigrateProfiles = !settings.connectionProfiles?.length;
  1057. for (const entries of groups.values()) {
  1058. const ordered = [...entries].sort((left, right) => right.lastOpenedAt - left.lastOpenedAt);
  1059. const latest = ordered[0]!;
  1060. const profileId = this.createProfileId();
  1061. // 既有 Profile 会作为本次 settings patch 的权威值保留;为随后被丢弃的临时 Profile
  1062. // 复制凭据会在成功迁移时也制造 orphan key,因此只有真正进入提交集的 Profile 才落 secret。
  1063. const target = shouldMigrateProfiles
  1064. ? await this.migrateProfileTarget(
  1065. profileId,
  1066. latest.target,
  1067. previousCredentials,
  1068. ordered.map((entry) => entry.target),
  1069. )
  1070. : this.profileTargetFromRemote(latest.target);
  1071. const transport = target.kind;
  1072. profiles.push({
  1073. profileId,
  1074. transport,
  1075. target,
  1076. displayName:
  1077. target.kind === "ssh"
  1078. ? (target.sshConfigAlias ?? target.host)
  1079. : target.kind === "wsl"
  1080. ? (target.distro ?? "WSL")
  1081. : target.container,
  1082. createdAt: Math.min(...entries.map((entry) => entry.lastOpenedAt)),
  1083. lastConnectedAt:
  1084. latest.lastConnectionStatus === "connected" ? latest.lastOpenedAt : undefined,
  1085. lastConnectError: latest.lastConnectionError,
  1086. } as ConnectionProfile);
  1087. for (const entry of entries) {
  1088. workspaceHistory.push({
  1089. workspacePath: entry.workspacePath,
  1090. ...(entry.workspaceIdentity ? { legacyWorkspaceIdentity: entry.workspaceIdentity } : {}),
  1091. profileId,
  1092. lastOpenedAt: entry.lastOpenedAt,
  1093. });
  1094. }
  1095. }
  1096. await this.persistSettings({
  1097. sourceServers: settings.sourceServers ?? [],
  1098. connectionProfiles: settings.connectionProfiles?.length
  1099. ? settings.connectionProfiles
  1100. : profiles,
  1101. sourceServerWorkspaceHistory: settings.sourceServerWorkspaceHistory?.length
  1102. ? settings.sourceServerWorkspaceHistory
  1103. : workspaceHistory.sort((left, right) => left.lastOpenedAt - right.lastOpenedAt),
  1104. sourceServerDirectoryMigrationVersion: 1,
  1105. });
  1106. }
  1107. private async repairDanglingProfileCredentials(settings: AppSettings): Promise<void> {
  1108. // Bug 原因:旧 Desktop 写回 settings 会剥离 Source Directory,新版再次迁移时可能已把
  1109. // 空 legacy key 变成 canonical Profile ref。migrationVersion=1 也必须按精确 route 幂等
  1110. // 审计并恢复真实 value;禁止根据 alias/hostname 猜测其它连接的 secret。
  1111. const legacyEntriesByRoute = new Map<string, LegacySourceWorkspaceEntry[]>();
  1112. for (const entry of settings.lastWorkspaceSession ?? []) {
  1113. if (entry.kind !== "remote" || entry.target.kind === "server") continue;
  1114. const key = routeKey(entry);
  1115. if (!key) continue;
  1116. const entries = legacyEntriesByRoute.get(key) ?? [];
  1117. entries.push(entry as LegacySourceWorkspaceEntry);
  1118. legacyEntriesByRoute.set(key, entries);
  1119. }
  1120. for (const entries of legacyEntriesByRoute.values()) {
  1121. entries.sort((left, right) => right.lastOpenedAt - left.lastOpenedAt);
  1122. }
  1123. for (const profile of settings.connectionProfiles ?? []) {
  1124. if (!isActiveProfile(profile) || profile.target.kind !== "ssh") continue;
  1125. const entries = legacyEntriesByRoute.get(
  1126. [
  1127. "ssh",
  1128. profile.target.host.trim().toLowerCase(),
  1129. String(profile.target.port ?? 22),
  1130. profile.target.username.trim(),
  1131. profile.target.privateKeyPath?.trim() ?? "",
  1132. ].join("\u0000"),
  1133. );
  1134. if (!entries?.length) continue;
  1135. const passwordCredentialKey = profile.target.passwordCredentialKey;
  1136. if (
  1137. passwordCredentialKey &&
  1138. (await this.loadUsableCredential(passwordCredentialKey)) === null
  1139. ) {
  1140. await this.copyFirstAvailableCredential(
  1141. entries.flatMap((entry) =>
  1142. entry.target.kind === "ssh" && entry.target.passwordCredentialKey
  1143. ? [entry.target.passwordCredentialKey]
  1144. : [],
  1145. ),
  1146. passwordCredentialKey,
  1147. );
  1148. }
  1149. const privateKeyPassphraseCredentialKey =
  1150. profile.target.privateKeyPath && profile.target.privateKeyPassphraseCredentialKey;
  1151. if (
  1152. privateKeyPassphraseCredentialKey &&
  1153. (await this.loadUsableCredential(privateKeyPassphraseCredentialKey)) === null
  1154. ) {
  1155. await this.copyFirstAvailableCredential(
  1156. entries.flatMap((entry) =>
  1157. entry.target.kind === "ssh" &&
  1158. entry.target.privateKeyPath &&
  1159. entry.target.privateKeyPassphraseCredentialKey
  1160. ? [entry.target.privateKeyPassphraseCredentialKey]
  1161. : [],
  1162. ),
  1163. privateKeyPassphraseCredentialKey,
  1164. );
  1165. }
  1166. }
  1167. }
  1168. private async migrateProfileTarget(
  1169. profileId: string,
  1170. target: LegacySourceWorkspaceEntry["target"],
  1171. previousCredentials: Map<string, string | null>,
  1172. credentialSources: readonly LegacySourceWorkspaceEntry["target"][] = [target],
  1173. ): Promise<SSHProfileTarget | WSLProfileTarget | DockerProfileTarget> {
  1174. if (target.kind === "ssh") {
  1175. const nextPasswordCredentialKey = newCredentialKey(profileId, "password");
  1176. const nextPrivateKeyPassphraseCredentialKey = newCredentialKey(
  1177. profileId,
  1178. "private-key-passphrase",
  1179. );
  1180. const passwordCopied = await this.copyFirstAvailableCredential(
  1181. credentialSources.flatMap((candidate) =>
  1182. candidate.kind === "ssh" && candidate.passwordCredentialKey
  1183. ? [candidate.passwordCredentialKey]
  1184. : [],
  1185. ),
  1186. nextPasswordCredentialKey,
  1187. previousCredentials,
  1188. );
  1189. // 两类凭据必须顺序等待:并行 Promise 提前 reject 时,另一条迟到 save 可能越过
  1190. // migration rollback 再落盘,重新制造无人引用的 key。
  1191. const privateKeyPassphraseCopied = target.privateKeyPath
  1192. ? await this.copyFirstAvailableCredential(
  1193. credentialSources.flatMap((candidate) =>
  1194. candidate.kind === "ssh" &&
  1195. candidate.privateKeyPath &&
  1196. candidate.privateKeyPassphraseCredentialKey
  1197. ? [candidate.privateKeyPassphraseCredentialKey]
  1198. : [],
  1199. ),
  1200. nextPrivateKeyPassphraseCredentialKey,
  1201. previousCredentials,
  1202. )
  1203. : false;
  1204. // Bug 原因:旧 snapshot 可能在密码认证时仍携带私钥口令 ref。
  1205. // 口令只有在 privateKeyPath 存在时才属于当前认证方式,否则迁移后会平白阻断完整密码。
  1206. // 实际私钥认证的 ref 仍保留:若对应值缺失,它必须继续触发交互凭据,不能静默降级。
  1207. return {
  1208. kind: "ssh",
  1209. host: target.host.trim().toLowerCase(),
  1210. port: target.port ?? 22,
  1211. username: target.username.trim(),
  1212. ...(target.sshConfigAlias ? { sshConfigAlias: target.sshConfigAlias } : {}),
  1213. ...(target.privateKeyPath ? { privateKeyPath: target.privateKeyPath } : {}),
  1214. ...(target.assetInstallMode ? { assetInstallMode: target.assetInstallMode } : {}),
  1215. ...(passwordCopied ? { passwordCredentialKey: nextPasswordCredentialKey } : {}),
  1216. ...(privateKeyPassphraseCopied
  1217. ? {
  1218. privateKeyPassphraseCredentialKey: nextPrivateKeyPassphraseCredentialKey,
  1219. }
  1220. : {}),
  1221. };
  1222. }
  1223. if (target.kind === "wsl") {
  1224. return {
  1225. kind: "wsl",
  1226. ...(target.distro ? { distro: target.distro.trim() } : {}),
  1227. ...(target.user ? { user: target.user.trim() } : {}),
  1228. };
  1229. }
  1230. return { kind: "docker", container: target.container.trim() };
  1231. }
  1232. private profileTargetFromRemote(
  1233. target: Exclude<RemoteTarget, { kind: "server" }>,
  1234. ): SSHProfileTarget | WSLProfileTarget | DockerProfileTarget {
  1235. if (target.kind === "ssh") {
  1236. return {
  1237. kind: "ssh",
  1238. host: target.host.trim().toLowerCase(),
  1239. port: target.port ?? 22,
  1240. username: target.username.trim(),
  1241. ...(target.sshConfigAlias ? { sshConfigAlias: target.sshConfigAlias } : {}),
  1242. ...(target.privateKeyPath ? { privateKeyPath: target.privateKeyPath } : {}),
  1243. ...(target.assetInstallMode ? { assetInstallMode: target.assetInstallMode } : {}),
  1244. };
  1245. }
  1246. if (target.kind === "wsl") {
  1247. return {
  1248. kind: "wsl",
  1249. ...(target.distro ? { distro: target.distro.trim() } : {}),
  1250. ...(target.user ? { user: target.user.trim() } : {}),
  1251. };
  1252. }
  1253. return { kind: "docker", container: target.container.trim() };
  1254. }
  1255. /** Directory 内全部凭据读取的唯一入口:本机无法解密的记录视为“无可用值”。 */
  1256. private async loadUsableCredential(key: string): Promise<string | null> {
  1257. try {
  1258. return await this.options.credentialService.load(key);
  1259. } catch (error) {
  1260. // Bug 原因:3.15 凭据文件里可能残留本机密钥无法解密的旧远程密码。这里曾把解密错误
  1261. // 一路上抛,legacy 迁移回滚且版本号不落盘,每次启动重败,Source Directory 整体不可用,
  1262. // 侧栏连同本地项目一起为空。不可解密与缺失对连接的含义相同:都需要交互凭据。
  1263. // 所以只跳过该来源,原记录不删除;文件损坏、IO 等其他错误仍让迁移失败回滚。
  1264. // Bug 原因:~/.zcode 换机/换用户后,已有 Profile 的密码同样解不开;连接、启动重连、
  1265. // 补充凭据、编辑和删除曾直接读取并上抛,一个坏 Profile 卡住整批启动重连,用户也无法
  1266. // 自助修复。所以这些读取也走这里:连接得到 credentials-required;回滚快照记为无值,
  1267. // 回滚时删除本机无法解密的密文而不是恢复它。
  1268. if (!isCredentialDecryptError(error)) throw error;
  1269. this.options.logWarn?.(
  1270. "Source Directory skipped an undecryptable credential; treating it as unavailable",
  1271. );
  1272. return null;
  1273. }
  1274. }
  1275. private async copyFirstAvailableCredential(
  1276. sourceKeys: readonly string[],
  1277. destinationKey: string,
  1278. previousCredentials?: Map<string, string | null>,
  1279. ): Promise<boolean> {
  1280. for (const sourceKey of sourceKeys) {
  1281. const value = await this.loadUsableCredential(sourceKey);
  1282. if (value === null) continue;
  1283. // Bug 原因:旧迁移只看最新 workspace 的 key,源值为空时仍生成新的 Profile ref。
  1284. // 同 route 按 lastOpenedAt 顺序寻找首个真实值,且只有复制成功才允许调用方写引用。
  1285. if (previousCredentials && !previousCredentials.has(destinationKey)) {
  1286. previousCredentials.set(destinationKey, await this.loadUsableCredential(destinationKey));
  1287. }
  1288. await this.options.credentialService.save(destinationKey, value);
  1289. return true;
  1290. }
  1291. return false;
  1292. }
  1293. private async persistProfileCredentials(
  1294. profileId: string,
  1295. target: Exclude<RemoteTarget, { kind: "server" }>,
  1296. profileTarget: SSHProfileTarget | WSLProfileTarget | DockerProfileTarget,
  1297. ): Promise<{
  1298. target: SSHProfileTarget | WSLProfileTarget | DockerProfileTarget;
  1299. rollback: () => Promise<void>;
  1300. }> {
  1301. if (target.kind !== "ssh" || profileTarget.kind !== "ssh") {
  1302. return { target: profileTarget, rollback: async () => undefined };
  1303. }
  1304. const passwordCredentialKey = target.password?.length
  1305. ? (profileTarget.passwordCredentialKey ?? newCredentialKey(profileId, "password"))
  1306. : profileTarget.passwordCredentialKey;
  1307. const privateKeyPassphraseCredentialKey = target.privateKeyPassphrase?.length
  1308. ? (profileTarget.privateKeyPassphraseCredentialKey ??
  1309. newCredentialKey(profileId, "private-key-passphrase"))
  1310. : profileTarget.privateKeyPassphraseCredentialKey;
  1311. const writes = [
  1312. ...(target.password?.length && passwordCredentialKey
  1313. ? [{ key: passwordCredentialKey, value: target.password }]
  1314. : []),
  1315. ...(target.privateKeyPassphrase?.length && privateKeyPassphraseCredentialKey
  1316. ? [
  1317. {
  1318. key: privateKeyPassphraseCredentialKey,
  1319. value: target.privateKeyPassphrase,
  1320. },
  1321. ]
  1322. : []),
  1323. ];
  1324. const previous = new Map<string, string | null>();
  1325. try {
  1326. for (const write of writes) {
  1327. previous.set(write.key, await this.loadUsableCredential(write.key));
  1328. await this.options.credentialService.save(write.key, write.value);
  1329. }
  1330. } catch (error) {
  1331. await this.restoreCredentials(previous);
  1332. throw error;
  1333. }
  1334. const nextTarget: SSHProfileTarget = {
  1335. ...profileTarget,
  1336. ...(passwordCredentialKey ? { passwordCredentialKey } : {}),
  1337. ...(privateKeyPassphraseCredentialKey ? { privateKeyPassphraseCredentialKey } : {}),
  1338. };
  1339. const changed =
  1340. nextTarget.passwordCredentialKey !== profileTarget.passwordCredentialKey ||
  1341. nextTarget.privateKeyPassphraseCredentialKey !==
  1342. profileTarget.privateKeyPassphraseCredentialKey;
  1343. return {
  1344. target: changed ? nextTarget : profileTarget,
  1345. rollback: async () => await this.restoreCredentials(previous),
  1346. };
  1347. }
  1348. private async restoreCredentials(previous: ReadonlyMap<string, string | null>): Promise<void> {
  1349. await Promise.all(
  1350. [...previous].map(async ([key, value]) => {
  1351. if (value === null) await this.options.credentialService.delete(key);
  1352. else await this.options.credentialService.save(key, value);
  1353. }),
  1354. );
  1355. }
  1356. private async resolveSilentTarget(
  1357. profile: ConnectionProfile,
  1358. ): Promise<Exclude<RemoteTarget, { kind: "server" }> | null> {
  1359. if (profile.target.kind === "wsl" || profile.target.kind === "docker") {
  1360. return profile.target;
  1361. }
  1362. const password = profile.target.passwordCredentialKey
  1363. ? await this.loadUsableCredential(profile.target.passwordCredentialKey)
  1364. : null;
  1365. const privateKeyPassphrase =
  1366. profile.target.privateKeyPath && profile.target.privateKeyPassphraseCredentialKey
  1367. ? await this.loadUsableCredential(profile.target.privateKeyPassphraseCredentialKey)
  1368. : null;
  1369. // Bug 原因:legacy workspace 迁移可能留下没有 privateKeyPath 的私钥口令引用。
  1370. // 旧逻辑要求所有引用都有值,把已完整的密码认证也误判为需要交互凭据。
  1371. // SSH 密码和私钥是可替代方案;只要其中一条认证链完整即可静默连接。
  1372. const hasPasswordAuth = Boolean(password);
  1373. const hasPrivateKeyAuth = Boolean(
  1374. profile.target.privateKeyPath &&
  1375. (!profile.target.privateKeyPassphraseCredentialKey || privateKeyPassphrase),
  1376. );
  1377. if (!hasPasswordAuth && !hasPrivateKeyAuth) return null;
  1378. return {
  1379. kind: "ssh",
  1380. host: profile.target.host,
  1381. port: profile.target.port,
  1382. username: profile.target.username,
  1383. ...(profile.target.sshConfigAlias ? { sshConfigAlias: profile.target.sshConfigAlias } : {}),
  1384. ...(hasPrivateKeyAuth && profile.target.privateKeyPath
  1385. ? { privateKeyPath: profile.target.privateKeyPath }
  1386. : {}),
  1387. ...(profile.target.assetInstallMode
  1388. ? { assetInstallMode: profile.target.assetInstallMode }
  1389. : {}),
  1390. ...(password ? { password } : {}),
  1391. ...(hasPrivateKeyAuth && privateKeyPassphrase ? { privateKeyPassphrase } : {}),
  1392. };
  1393. }
  1394. private async enqueue<T>(operation: () => Promise<T>): Promise<T> {
  1395. // Bug 原因:过去 enqueue 完成后无条件 fire onDidChange,未写入的操作(已迁移短路、
  1396. // identity-pending 零写入分支、目标不存在的 no-op)也会驱动全部消费方权威重读快照。
  1397. // 事件语义收敛为「确有持久化写入成功才通知」;写入统一走 persistSettings 打标。
  1398. const run = async (): Promise<{ value: T; didPersist: boolean }> => {
  1399. this.didPersistInCurrentOperation = false;
  1400. const value = await operation();
  1401. return { value, didPersist: this.didPersistInCurrentOperation };
  1402. };
  1403. const result = this.writeChain.then(run, run);
  1404. this.writeChain = result.then(
  1405. () => undefined,
  1406. () => undefined,
  1407. );
  1408. const { value, didPersist } = await result;
  1409. if (didPersist) this.changeEmitter.fire();
  1410. return value;
  1411. }
  1412. /** 目录持久化写入的唯一入口:写入成功即标记本次 enqueue 操作需要发布变更事件。 */
  1413. private async persistSettings(patch: Partial<AppSettings>): Promise<void> {
  1414. await this.options.settingService.update(patch);
  1415. this.didPersistInCurrentOperation = true;
  1416. }
  1417. }
  1418. function projectDeclaredWorkspaces(
  1419. sourceServerId: string,
  1420. workspaces: readonly SourceServerDeclaredWorkspaceWire[],
  1421. logDebug?: (message: string) => void,
  1422. ): SourceServerRecord["declaredWorkspaces"] {
  1423. const canonicalServerIdentity = buildServerRemoteWorkspaceIdentity({
  1424. serverId: sourceServerId,
  1425. workspacePath: "/",
  1426. });
  1427. const canonicalServerId = parseRemoteWorkspaceIdentity(canonicalServerIdentity)?.sourceServerId;
  1428. const result: NonNullable<SourceServerRecord["declaredWorkspaces"]> = [];
  1429. const seen = new Set<string>();
  1430. for (const workspace of workspaces) {
  1431. const workspacePath = workspace.path.trim();
  1432. if (!workspacePath) continue;
  1433. const canonicalIdentity = buildServerRemoteWorkspaceIdentity({
  1434. serverId: sourceServerId,
  1435. workspacePath,
  1436. });
  1437. const parsedIdentity = workspace.workspaceIdentity
  1438. ? parseRemoteWorkspaceIdentity(workspace.workspaceIdentity)
  1439. : null;
  1440. const identityIsValid =
  1441. parsedIdentity?.kind === "server" &&
  1442. parsedIdentity.sourceServerId === canonicalServerId &&
  1443. parsedIdentity.workspacePath ===
  1444. parseRemoteWorkspaceIdentity(canonicalIdentity)?.workspacePath;
  1445. // 设备记录必须使用设备级 canonical identity;不信任远端传回的线路级或跨设备 identity。
  1446. const workspaceIdentity =
  1447. identityIsValid && workspace.workspaceIdentity === canonicalIdentity
  1448. ? workspace.workspaceIdentity
  1449. : canonicalIdentity;
  1450. // 合同 §8.1.1:远端 identity 校验不通过被 canonical 覆盖时仅记 debug 日志、不报错。
  1451. if (workspace.workspaceIdentity && workspace.workspaceIdentity !== workspaceIdentity) {
  1452. logDebug?.(
  1453. `Source Server declared workspace identity overridden by canonical: server=${sourceServerId} path=${workspacePath} remote=${workspace.workspaceIdentity}`,
  1454. );
  1455. }
  1456. if (seen.has(workspaceIdentity)) continue;
  1457. seen.add(workspaceIdentity);
  1458. result.push({
  1459. workspacePath,
  1460. workspaceIdentity,
  1461. ...(workspace.label ? { label: workspace.label } : {}),
  1462. });
  1463. if (result.length >= 20) break;
  1464. }
  1465. return result;
  1466. }