live-bigmodel-profile.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 登录材料与 Team 项目 key(内存),经正式 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. teamKeyPresent: boolean;
  28. teamSelection: {
  29. kind: "team-coding-plan";
  30. productId: string;
  31. organizationId: string;
  32. projectId: string;
  33. };
  34. }> {
  35. const sourceHome = process.env.R3_LIVE_SOURCE_HOME?.trim();
  36. if (!sourceHome) throw new Error(`${caseMarker}: 需设置 R3_LIVE_SOURCE_HOME(本机真实 HOME)`);
  37. const username = userInfo().username;
  38. const sourceCipher = createCredentialCipherProvider({
  39. env: {
  40. ZCODE_CREDENTIAL_SECRET: `zcode-credential-fallback:${platform()}:${sourceHome}:${username}`,
  41. },
  42. });
  43. const original = JSON.parse(
  44. await readFile(resolve(sourceHome, ".zcode", "v2", "credentials.json"), "utf8"),
  45. ) as Record<string, string>;
  46. const values = new Map<string, string>();
  47. for (const [key, value] of Object.entries(original)) {
  48. if (
  49. IMPORT_KEYS.includes(key) ||
  50. (key.startsWith("account-provider:coding-plan:account:bigmodel-team-coding-plan:") &&
  51. key.endsWith(":api-key"))
  52. ) {
  53. values.set(key, sourceCipher.decrypt(value));
  54. }
  55. }
  56. if (!values.has("oauth:bigmodel:access_token")) {
  57. throw new Error(`${caseMarker}: 本机没有 BigModel 登录材料`);
  58. }
  59. // §49 实锤:本机凭据库可能没有 oauth:bigmodel:refresh_token(产品流是否落盘该 key 未知)。
  60. // access_token 是 opaque token 无法本地判过期——一旦失效且无 refresh_token 续期,
  61. // reloadSession 后 UI 会停在 BigModel 登录引导页(SessionPane 不渲染 → workspace 菜单
  62. // 不可达 → connectSSHWorkspace 超时)。此处只记 facts 线索,不硬性阻断。
  63. if (!values.has("oauth:bigmodel:refresh_token")) {
  64. console.warn(
  65. `[${caseMarker}] 本机凭据缺少 oauth:bigmodel:refresh_token——若 UI 停在登录引导页,需在本机 app 重新登录 BigModel 刷新材料`,
  66. );
  67. }
  68. const paths = getE2EAppDataPaths();
  69. // services 的数据根是 HOME 级目录(其下 .zcode/v2),与 desktop-app helper 的 credentialsFile 同一文件。
  70. setDataBaseDir(paths.homeDir);
  71. const targetCipher = createCredentialCipherProvider({
  72. env: {
  73. ZCODE_CREDENTIAL_SECRET:
  74. process.env.ZCODE_CREDENTIAL_SECRET ||
  75. `zcode-credential-fallback:${platform()}:${paths.homeDir}:${username}`,
  76. },
  77. });
  78. const service = createCredentialService({ cipherProvider: targetCipher });
  79. for (const [key, value] of values) await service.save(key, value);
  80. const written = JSON.parse(await readFile(paths.credentialsFile, "utf8")) as Record<
  81. string,
  82. string
  83. >;
  84. for (const key of values.keys()) {
  85. if (!(key in written)) throw new Error(`${caseMarker}: 凭据未写入隔离 profile: ${key}`);
  86. }
  87. const sourceSettings = JSON.parse(
  88. await readFile(resolve(sourceHome, ".zcode", "v2", "setting.json"), "utf8"),
  89. ) as Record<string, unknown>;
  90. const sourceSelection = (
  91. sourceSettings.providerFamilyConnectionSelections as Record<string, unknown> | undefined
  92. )?.bigmodel as
  93. | { kind?: string; productId?: string; organizationId?: string; projectId?: string }
  94. | undefined;
  95. if (
  96. sourceSelection?.kind !== "team-coding-plan" ||
  97. !sourceSelection.productId ||
  98. !sourceSelection.organizationId ||
  99. !sourceSelection.projectId
  100. ) {
  101. throw new Error(
  102. `${caseMarker}: 本机 setting.json 没有 bigmodel team-coding-plan 连接选择(productId/organizationId/projectId 齐全),无法构造合法窄设置`,
  103. );
  104. }
  105. return {
  106. imported: [...values.keys()],
  107. refreshTokenPresent: values.has("oauth:bigmodel:refresh_token"),
  108. teamKeyPresent: [...values.keys()].some((key) => key.includes("bigmodel-team-coding-plan")),
  109. teamSelection: {
  110. kind: "team-coding-plan",
  111. productId: sourceSelection.productId,
  112. organizationId: sourceSelection.organizationId,
  113. projectId: sourceSelection.projectId,
  114. },
  115. };
  116. }