live-bigmodel-profile.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { readFile } from "node:fs/promises";
  2. import { platform, userInfo } from "node:os";
  3. import { resolve } from "node:path";
  4. import { createCredentialService, setDataBaseDir } from "@zcode/services/node";
  5. import { createCredentialCipherProvider } from "../../../../services/src/credential/providers/credentialCipherProvider.js";
  6. import { getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  7. const IMPORT_KEYS = [
  8. "oauth:bigmodel:access_token",
  9. "oauth:bigmodel:refresh_token",
  10. "oauth:bigmodel:user_info",
  11. "oauth:active_provider",
  12. "zcodejwttoken",
  13. ];
  14. /**
  15. * 从本机正式凭据库解密 BigModel 登录材料(内存),经正式 Credential Service 用隔离 profile
  16. * 的 cipher 重新保存。默认 cipher 由 platform/homedir/username 派生,两侧显式给出 secret,不猜测 worker 的 HOME。
  17. *
  18. * 同时带回本机 setting.json 的 bigmodel 连接选择。0911 修复:裸 `{ kind: "team-coding-plan" }`
  19. * 不满足 appSettingsSchema(productId/organizationId/projectId 必填),会让 main 侧
  20. * readStartupSettings 校验失败整份回退默认设置——startupWorkspace 走首启分支落在
  21. * conversation 工作区,且 providerFamilyDomain 也丢失。产品 UI(ModelProviderSection)
  22. * 只在三字段齐全时才写该条目,因此这里必须原样拷贝本机真实选择。
  23. */
  24. export async function importLiveBigModelCredentials(caseMarker: string): Promise<{
  25. imported: string[];
  26. refreshTokenPresent: boolean;
  27. teamSelection: {
  28. kind: "team-coding-plan";
  29. productId: string;
  30. organizationId: string;
  31. projectId: string;
  32. };
  33. }> {
  34. const sourceHome = process.env.R3_LIVE_SOURCE_HOME?.trim();
  35. if (!sourceHome) throw new Error(`${caseMarker}: 需设置 R3_LIVE_SOURCE_HOME(本机真实 HOME)`);
  36. const username = userInfo().username;
  37. const sourceCipher = createCredentialCipherProvider({
  38. env: {
  39. ZCODE_CREDENTIAL_SECRET: `zcode-credential-fallback:${platform()}:${sourceHome}:${username}`,
  40. },
  41. });
  42. const original = JSON.parse(
  43. await readFile(resolve(sourceHome, ".zcode", "v2", "credentials.json"), "utf8"),
  44. ) as Record<string, string>;
  45. const values = new Map<string, string>();
  46. for (const [key, value] of Object.entries(original)) {
  47. // 远端已按 OAuth 换证;旧 Team key 缓存既不应下发,也可能因安全存储格式不同而解密失败。
  48. if (IMPORT_KEYS.includes(key)) {
  49. values.set(key, sourceCipher.decrypt(value));
  50. }
  51. }
  52. if (!values.has("oauth:bigmodel:access_token")) {
  53. throw new Error(`${caseMarker}: 本机没有 BigModel 登录材料`);
  54. }
  55. // §49 实锤:本机凭据库可能没有 oauth:bigmodel:refresh_token(产品流是否落盘该 key 未知)。
  56. // access_token 是 opaque token 无法本地判过期——一旦失效且无 refresh_token 续期,
  57. // reloadSession 后 UI 会停在 BigModel 登录引导页(SessionPane 不渲染 → workspace 菜单
  58. // 不可达 → connectSSHWorkspace 超时)。此处只记 facts 线索,不硬性阻断。
  59. if (!values.has("oauth:bigmodel:refresh_token")) {
  60. console.warn(
  61. `[${caseMarker}] 本机凭据缺少 oauth:bigmodel:refresh_token——若 UI 停在登录引导页,需在本机 app 重新登录 BigModel 刷新材料`,
  62. );
  63. }
  64. const paths = getE2EAppDataPaths();
  65. // services 的数据根是 HOME 级目录(其下 .zcode/v2),与 desktop-app helper 的 credentialsFile 同一文件。
  66. setDataBaseDir(paths.homeDir);
  67. const targetCipher = createCredentialCipherProvider({
  68. env: {
  69. ZCODE_CREDENTIAL_SECRET:
  70. process.env.ZCODE_CREDENTIAL_SECRET ||
  71. `zcode-credential-fallback:${platform()}:${paths.homeDir}:${username}`,
  72. },
  73. });
  74. const service = createCredentialService({ cipherProvider: targetCipher });
  75. for (const [key, value] of values) await service.save(key, value);
  76. const written = JSON.parse(await readFile(paths.credentialsFile, "utf8")) as Record<
  77. string,
  78. string
  79. >;
  80. for (const key of values.keys()) {
  81. if (!(key in written)) throw new Error(`${caseMarker}: 凭据未写入隔离 profile: ${key}`);
  82. }
  83. const sourceSettings = JSON.parse(
  84. await readFile(resolve(sourceHome, ".zcode", "v2", "setting.json"), "utf8"),
  85. ) as Record<string, unknown>;
  86. const sourceSelection = (
  87. sourceSettings.providerFamilyConnectionSelections as Record<string, unknown> | undefined
  88. )?.bigmodel as
  89. | { kind?: string; productId?: string; organizationId?: string; projectId?: string }
  90. | undefined;
  91. if (
  92. sourceSelection?.kind !== "team-coding-plan" ||
  93. !sourceSelection.productId ||
  94. !sourceSelection.organizationId ||
  95. !sourceSelection.projectId
  96. ) {
  97. throw new Error(
  98. `${caseMarker}: 本机 setting.json 没有 bigmodel team-coding-plan 连接选择(productId/organizationId/projectId 齐全),无法构造合法窄设置`,
  99. );
  100. }
  101. return {
  102. imported: [...values.keys()],
  103. refreshTokenPresent: values.has("oauth:bigmodel:refresh_token"),
  104. teamSelection: {
  105. kind: "team-coding-plan",
  106. productId: sourceSelection.productId,
  107. organizationId: sourceSelection.organizationId,
  108. projectId: sourceSelection.projectId,
  109. },
  110. };
  111. }