shared-credentials.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import { randomUUID } from "node:crypto";
  2. import { OAUTH_SESSION_REVISION_KEY, OAUTH_LINKED_BIGMODEL_KEY } from "@zcode/shared";
  3. import { readFile } from "node:fs/promises";
  4. import { homedir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import {
  7. backupCorruptFile,
  8. captureCredentialFileGuard,
  9. type CredentialFileGuard,
  10. withCredentialFileRead,
  11. withCredentialFileMutation,
  12. withCredentialGeneration,
  13. withFileLock,
  14. } from "@zcode/shared/node";
  15. import type { ZCodeCredentialCipher } from "./credential-cipher.js";
  16. import {
  17. createSystemCredentialCipher,
  18. migrateCredentialRecord,
  19. readAssignedCredentialsFile,
  20. writeCredentialRecordLocked,
  21. } from "@zcode/shared/credential-security";
  22. const ZCODE_DATA_BASE_DIR_ENV_KEY = "ZCODE_DATA_BASE_DIR";
  23. const ZAI_PROVIDER_ID = "zai";
  24. const WRITE_PROBE_VALUE = "zcode-credential-write-probe";
  25. const credentialChangeListeners = new Map<string, Set<() => void | Promise<void>>>();
  26. export const SHARED_ZCODE_CREDENTIAL_KEYS = {
  27. activeProvider: "oauth:active_provider",
  28. sessionRevision: OAUTH_SESSION_REVISION_KEY,
  29. linkedBigModel: OAUTH_LINKED_BIGMODEL_KEY,
  30. zaiCnAccessToken: "oauth:zai_cn:access_token",
  31. zaiCnRefreshToken: "oauth:zai_cn:refresh_token",
  32. zaiCnUserInfo: "oauth:zai_cn:user_info",
  33. bigmodelAccessToken: "oauth:bigmodel:access_token",
  34. bigmodelRefreshToken: "oauth:bigmodel:refresh_token",
  35. bigmodelUserInfo: "oauth:bigmodel:user_info",
  36. zaiAccessToken: "oauth:zai:access_token",
  37. zaiRefreshToken: "oauth:zai:refresh_token",
  38. zaiUserInfo: "oauth:zai:user_info",
  39. zcodeJwtToken: "zcodejwttoken",
  40. } as const;
  41. export interface SharedZCodeCredentialStoreOptions {
  42. baseDir?: string;
  43. cipher?: ZCodeCredentialCipher;
  44. env?: Record<string, string | undefined>;
  45. filePath?: string;
  46. }
  47. export interface ZaiLoginCredentialUser {
  48. avatar?: string;
  49. email?: string;
  50. name?: string;
  51. user_id: string;
  52. }
  53. export interface ZaiLoginCredentialPayload {
  54. accessToken: string;
  55. jwtToken: string;
  56. user: ZaiLoginCredentialUser;
  57. }
  58. export interface SharedCredentialRecoveryGuard {
  59. readonly run: CredentialFileGuard;
  60. /** 仅保护其它文件的最终提交;调用方先取得其它文件锁,回调不能再次写凭据库。 */
  61. readonly commit: CredentialFileGuard;
  62. }
  63. export interface SharedZCodeCredentialStore {
  64. readonly filePath: string;
  65. /** 用首次写入的同一密钥路径确认可写;不写凭据文件,不可用时抛出原始安全存储错误。 */
  66. assertWritable(): Promise<void>;
  67. /** 跨请求流程在启动时捕获,不能等网络返回后领取恢复后的新代次。 */
  68. captureRecoveryGuard(): Promise<SharedCredentialRecoveryGuard>;
  69. clearZaiLoginCredentials(): Promise<void>;
  70. delete(key: string): Promise<void>;
  71. deleteIfValue(key: string, expectedValue: string): Promise<boolean>;
  72. deleteIfValues(
  73. expectedValues: Readonly<Record<string, string>>,
  74. ): Promise<Record<string, boolean>>;
  75. deleteManyIfValue(
  76. guardKey: string,
  77. expectedGuardValue: string,
  78. keysToDelete: readonly string[],
  79. ): Promise<boolean>;
  80. updateMany(
  81. changes: Readonly<Record<string, string | null>>,
  82. options?: { expected?: Readonly<Record<string, string | null>>; assertCurrent?: () => void },
  83. ): Promise<boolean>;
  84. load(key: string): Promise<string | null>;
  85. loadMany(keys: readonly string[]): Promise<Record<string, string | null>>;
  86. loadOAuthSessionSnapshot(): Promise<Record<string, string | null>>;
  87. onDidChange?(listener: () => void | Promise<void>): () => void;
  88. save(key: string, value: string): Promise<void>;
  89. saveMany(entries: Readonly<Record<string, string>>): Promise<void>;
  90. saveReplacing(key: string, value: string, replacedKeys: readonly string[]): Promise<void>;
  91. saveZaiLoginCredentials(
  92. payload: ZaiLoginCredentialPayload,
  93. expected?: Readonly<Record<string, string | null>>,
  94. assertCurrent?: () => void,
  95. ): Promise<void>;
  96. }
  97. export function createSharedZCodeCredentialStore(
  98. options: SharedZCodeCredentialStoreOptions = {},
  99. ): SharedZCodeCredentialStore {
  100. const env = options.env ?? process.env;
  101. const filePath = resolveSharedZCodeCredentialsPath(options);
  102. const cipher = options.cipher ?? createSystemCredentialCipher({ env, filePath });
  103. const readCurrent = async () => {
  104. // 普通读取不取得写锁(慢写入曾让登录读取等锁超时),由读取前后的恢复代次校验拒绝旧结果。
  105. // 只有仍含旧格式值时才进入变更锁迁移,迁移写入与恢复共用同一代次屏障。
  106. const current = await readRawCredentialRecord(filePath);
  107. if (!Object.values(current).some((value) => cipher.needsMigration?.(value))) return current;
  108. return withCredentialFileMutation(filePath, async () => {
  109. const locked = await readRawCredentialRecord(filePath, true);
  110. const migrated = await migrateCredentialRecord(locked, cipher);
  111. if (migrated) await writeCredentialRecordLocked(filePath, migrated);
  112. return migrated ?? locked;
  113. });
  114. };
  115. type RawMutation = (raw: Record<string, string>) => void | boolean | Promise<void | boolean>;
  116. const commit = (mutation: RawMutation) =>
  117. commitRawCredentialRecord(filePath, async (raw) => {
  118. const migrated = await migrateCredentialRecord(raw, cipher);
  119. if (migrated) Object.assign(raw, migrated);
  120. return mutation(raw);
  121. });
  122. const mutate = async (mutation: RawMutation) => {
  123. if (await commit(mutation)) await notifyCredentialChange(filePath);
  124. };
  125. const loadMany = async (keys: readonly string[]): Promise<Record<string, string | null>> => {
  126. const raw = await readCurrent();
  127. return Object.fromEntries(
  128. await Promise.all(
  129. keys.map(async (key) => {
  130. const value = raw[validateCredentialKey(key)];
  131. return [key, value === undefined ? null : await cipher.decrypt(value)];
  132. }),
  133. ),
  134. );
  135. };
  136. // Bug 原因:先加密后取文件锁领取代次;经凭据桥由 Main 加密的内置 CLI,加密在自动重置前、
  137. // 写盘在重置后时,旧密钥密文会覆盖新登录且返回成功。修复:加密前领取代次,由锁内代次
  138. // 屏障保护到写盘;期间发生重置即拒绝,调用方重试。
  139. // 代次作用域只覆盖加密与锁内写盘:提交后的变更通知若留在作用域内,监听启动的后台任务
  140. // (如账号刷新链)会一直带着本次领取的代次,之后的恢复或重置使其读写被误判为存储已变化。
  141. const updateMany: SharedZCodeCredentialStore["updateMany"] = async (changes, options) => {
  142. const committed = await withCredentialGeneration(filePath, async () => {
  143. const entries = await Promise.all(
  144. Object.entries(changes).map(
  145. async ([key, value]) =>
  146. [
  147. validateCredentialKey(key),
  148. value === null ? null : await cipher.encrypt(validateCredentialValue(value)),
  149. ] as const,
  150. ),
  151. );
  152. const expected = Object.entries(options?.expected ?? {}).map(
  153. ([key, value]) =>
  154. [
  155. validateCredentialKey(key),
  156. value === null ? null : validateCredentialValue(value),
  157. ] as const,
  158. );
  159. return commit(async (raw) => {
  160. for (const [key, value] of expected) {
  161. if ((raw[key] === undefined ? null : await cipher.decrypt(raw[key])) !== value)
  162. return false;
  163. }
  164. options?.assertCurrent?.();
  165. for (const [key, value] of entries) {
  166. if (value === null) delete raw[key];
  167. else raw[key] = value;
  168. }
  169. if (entries.some(([key]) => key === "zcodejwttoken" || key.startsWith("oauth:")))
  170. raw[OAUTH_SESSION_REVISION_KEY] = await cipher.encrypt(randomUUID());
  171. options?.assertCurrent?.();
  172. });
  173. });
  174. if (committed) await notifyCredentialChange(filePath);
  175. return committed;
  176. };
  177. const loadOAuthSessionSnapshot = async (): Promise<Record<string, string | null>> => {
  178. const raw = await readCurrent();
  179. const activeRaw = raw[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
  180. const provider = activeRaw === undefined ? null : await cipher.decrypt(activeRaw);
  181. const keys = [
  182. SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider,
  183. SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken,
  184. OAUTH_SESSION_REVISION_KEY,
  185. ...(provider
  186. ? [
  187. `oauth:${provider}:access_token`,
  188. `oauth:${provider}:refresh_token`,
  189. `oauth:${provider}:user_info`,
  190. ]
  191. : []),
  192. ];
  193. return Object.fromEntries(
  194. await Promise.all(
  195. keys.map(async (key) => [
  196. key,
  197. raw[key] === undefined ? null : await cipher.decrypt(raw[key]),
  198. ]),
  199. ),
  200. );
  201. };
  202. return {
  203. filePath,
  204. async assertWritable() {
  205. // Bug 原因:空库读取不调用 cipher,首次访问系统库发生在登录授权之后的写入时。
  206. // 加密探针值走与首次写入相同的取密钥路径(必要时创建密钥),结果丢弃。
  207. await cipher.encrypt(WRITE_PROBE_VALUE);
  208. },
  209. async captureRecoveryGuard() {
  210. const run = await captureCredentialFileGuard(filePath);
  211. return { run, commit: (operation) => withFileLock(filePath, () => run(operation)) };
  212. },
  213. updateMany,
  214. loadOAuthSessionSnapshot,
  215. async clearZaiLoginCredentials(): Promise<void> {
  216. const expected = await loadOAuthSessionSnapshot();
  217. await updateMany(
  218. {
  219. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: null,
  220. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiRefreshToken]: null,
  221. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo]: null,
  222. ...(expected[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider] === ZAI_PROVIDER_ID
  223. ? {
  224. [SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider]: null,
  225. [SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken]: null,
  226. [SHARED_ZCODE_CREDENTIAL_KEYS.linkedBigModel]: null,
  227. }
  228. : {}),
  229. },
  230. { expected },
  231. );
  232. },
  233. async delete(key: string): Promise<void> {
  234. const validatedKey = validateCredentialKey(key);
  235. await mutate(async (rawCredentials) => {
  236. delete rawCredentials[validatedKey];
  237. });
  238. },
  239. async deleteIfValue(key: string, expectedValue: string): Promise<boolean> {
  240. const validatedKey = validateCredentialKey(key);
  241. const validatedExpectedValue = validateCredentialValue(expectedValue);
  242. let deleted = false;
  243. await mutate(async (rawCredentials) => {
  244. const encryptedValue = rawCredentials[validatedKey];
  245. if (
  246. encryptedValue === undefined ||
  247. (await cipher.decrypt(encryptedValue)) !== validatedExpectedValue
  248. ) {
  249. return;
  250. }
  251. delete rawCredentials[validatedKey];
  252. deleted = true;
  253. });
  254. return deleted;
  255. },
  256. async deleteIfValues(
  257. expectedValues: Readonly<Record<string, string>>,
  258. ): Promise<Record<string, boolean>> {
  259. const validatedEntries = Object.entries(expectedValues).map(
  260. ([key, value]) => [validateCredentialKey(key), validateCredentialValue(value)] as const,
  261. );
  262. if (validatedEntries.length === 0) return {};
  263. const deleted: Record<string, boolean> = {};
  264. await mutate(async (rawCredentials) => {
  265. for (const [key, expectedValue] of validatedEntries) {
  266. const encryptedValue = rawCredentials[key];
  267. const matches =
  268. encryptedValue !== undefined &&
  269. (await cipher.decrypt(encryptedValue)) === expectedValue;
  270. deleted[key] = matches;
  271. if (matches) delete rawCredentials[key];
  272. }
  273. });
  274. return deleted;
  275. },
  276. /**
  277. * 条件事务:`guardKey` 当前值与期望值相等才删除 `keysToDelete` 全部 key,否则一个都不删。
  278. *
  279. * `deleteIfValues` 是逐 key 比较、逐 key 删除,无法表达「canonical generation 匹配
  280. * 才整体失效」——canonical 比较失败时 legacy 镜像仍可能被删掉,反之亦然。OAuth 凭据失效必须
  281. * 是整对的:stale 事务不能删掉 winner 的 canonical,也不能只删掉它的一半镜像。
  282. */
  283. async deleteManyIfValue(
  284. guardKey: string,
  285. expectedGuardValue: string,
  286. keysToDelete: readonly string[],
  287. ): Promise<boolean> {
  288. const validatedGuardKey = validateCredentialKey(guardKey);
  289. const validatedExpectedValue = validateCredentialValue(expectedGuardValue);
  290. const validatedKeys = keysToDelete.map(validateCredentialKey);
  291. let deleted = false;
  292. await mutate(async (rawCredentials) => {
  293. const encryptedGuard = rawCredentials[validatedGuardKey];
  294. if (
  295. encryptedGuard === undefined ||
  296. (await cipher.decrypt(encryptedGuard)) !== validatedExpectedValue
  297. ) {
  298. return;
  299. }
  300. for (const key of validatedKeys) delete rawCredentials[key];
  301. deleted = true;
  302. });
  303. return deleted;
  304. },
  305. async load(key: string): Promise<string | null> {
  306. const rawCredentials = await readCurrent();
  307. const rawValue = rawCredentials[validateCredentialKey(key)];
  308. if (rawValue === undefined) {
  309. return null;
  310. }
  311. return cipher.decrypt(rawValue);
  312. },
  313. loadMany,
  314. onDidChange(listener: () => void | Promise<void>): () => void {
  315. let listeners = credentialChangeListeners.get(filePath);
  316. if (!listeners) {
  317. listeners = new Set();
  318. credentialChangeListeners.set(filePath, listeners);
  319. }
  320. listeners.add(listener);
  321. return () => {
  322. listeners?.delete(listener);
  323. if (listeners?.size === 0) credentialChangeListeners.delete(filePath);
  324. };
  325. },
  326. async save(key: string, value: string): Promise<void> {
  327. await updateMany({ [key]: value });
  328. },
  329. async saveMany(entries: Readonly<Record<string, string>>): Promise<void> {
  330. await updateMany(entries);
  331. },
  332. async saveReplacing(
  333. key: string,
  334. value: string,
  335. replacedKeys: readonly string[],
  336. ): Promise<void> {
  337. const validatedKey = validateCredentialKey(key);
  338. const validatedReplacedKeys = replacedKeys.map(validateCredentialKey);
  339. // 与 updateMany 相同:加密前领取代次,避免重置前产生的密文在重置后写盘;通知在作用域外。
  340. const committed = await withCredentialGeneration(filePath, async () => {
  341. const encryptedValue = await cipher.encrypt(validateCredentialValue(value));
  342. return commit(async (rawCredentials) => {
  343. rawCredentials[validatedKey] = encryptedValue;
  344. for (const replacedKey of validatedReplacedKeys) {
  345. if (replacedKey !== validatedKey) delete rawCredentials[replacedKey];
  346. }
  347. });
  348. });
  349. if (committed) await notifyCredentialChange(filePath);
  350. },
  351. async saveZaiLoginCredentials(payload, expected, assertCurrent): Promise<void> {
  352. const snapshot = expected ?? (await loadOAuthSessionSnapshot());
  353. const committed = await updateMany(
  354. {
  355. ...Object.fromEntries(
  356. Object.values(SHARED_ZCODE_CREDENTIAL_KEYS).map((key) => [key, null]),
  357. ),
  358. [SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider]: ZAI_PROVIDER_ID,
  359. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: payload.accessToken,
  360. [SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken]: payload.jwtToken,
  361. [SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo]: JSON.stringify(payload.user),
  362. },
  363. { expected: snapshot, assertCurrent },
  364. );
  365. if (!committed) throw new Error("OAuth session changed before login commit");
  366. },
  367. };
  368. }
  369. /** 所有凭据读取均为异步,避免系统密钥库阻塞 UI 或 CLI 事件循环。 */
  370. export async function loadSharedZCodeCredential(
  371. key: string,
  372. options: SharedZCodeCredentialStoreOptions = {},
  373. ): Promise<string | undefined> {
  374. const value = await createSharedZCodeCredentialStore(options).load(key);
  375. return value?.trim() ? value : undefined;
  376. }
  377. export function resolveSharedZCodeCredentialsPath(
  378. options: SharedZCodeCredentialStoreOptions = {},
  379. ): string {
  380. if (options.filePath) {
  381. return resolveUserPath(options.filePath);
  382. }
  383. const env = options.env ?? process.env;
  384. if (options.baseDir === undefined) {
  385. // Source Server Core 使用自有凭据库时经 ZCODE_CREDENTIALS_FILE 指定文件(ZCT-2120452663971209216),
  386. // 由其拉起的 Agent 必须读写同一文件;显式调用参数仍然优先。
  387. const assigned = readAssignedCredentialsFile(env);
  388. if (assigned) return assigned;
  389. }
  390. const baseDir = options.baseDir ?? env[ZCODE_DATA_BASE_DIR_ENV_KEY] ?? homedir();
  391. return join(resolveUserPath(baseDir), ".zcode", "v2", "credentials.json");
  392. }
  393. async function readRawCredentialRecord(
  394. filePath: string,
  395. locked = false,
  396. ): Promise<Record<string, string>> {
  397. if (locked) return readRawCredentialRecordUnchecked(filePath);
  398. return withCredentialFileRead(filePath, () => readRawCredentialRecordUnchecked(filePath));
  399. }
  400. async function readRawCredentialRecordUnchecked(filePath: string): Promise<Record<string, string>> {
  401. let raw: Buffer;
  402. try {
  403. raw = await readFile(filePath);
  404. } catch (error) {
  405. if (getErrorCode(error) === "ENOENT") {
  406. return {};
  407. }
  408. throw new Error(`Unable to read shared ZCode credentials: ${filePath}`, { cause: error });
  409. }
  410. try {
  411. // 宽松 UTF-8 解码会把坏字节替换后继续使用或写回,违背与 Desktop 共用的损坏边界。
  412. return parseCredentialRecord(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)));
  413. } catch (error) {
  414. // 损坏的凭据文件若被当成空对象继续保存,会一次性抹掉其他进程的全部凭据。
  415. // 先保留现场再失败,调用方必须显式处理恢复,不能静默覆盖。
  416. const backupPath = await backupCorruptFile(filePath).catch(() => undefined);
  417. const evidence = backupPath ? ` Backup: ${backupPath}` : "";
  418. throw new Error(`Shared ZCode credentials are corrupt: ${filePath}.${evidence}`, {
  419. cause: error,
  420. });
  421. }
  422. }
  423. async function commitRawCredentialRecord(
  424. filePath: string,
  425. mutation: (value: Record<string, string>) => void | boolean | Promise<void | boolean>,
  426. ): Promise<boolean> {
  427. // CLI、设置页和 session 可能位于不同 Node 进程;锁必须覆盖完整的
  428. // read-modify-write,单独原子 rename 只能防半写,不能防旧快照覆盖新 key。
  429. return withCredentialFileMutation(filePath, async () => {
  430. const value = await readRawCredentialRecord(filePath, true);
  431. if ((await mutation(value)) === false) return false;
  432. await writeCredentialRecordLocked(filePath, value);
  433. return true;
  434. });
  435. }
  436. async function notifyCredentialChange(filePath: string): Promise<void> {
  437. const listeners = [...(credentialChangeListeners.get(filePath) ?? [])];
  438. // 同进程的 Registry Source 需要在登录返回前观察到新凭据;单个监听者失败不应
  439. // 把已经原子落盘的 Credential 伪装成写入失败。
  440. await Promise.allSettled(listeners.map((listener) => listener()));
  441. }
  442. function parseCredentialRecord(value: unknown): Record<string, string> {
  443. if (!isRecord(value)) {
  444. throw new Error("Credential record must be an object");
  445. }
  446. const result: Record<string, string> = {};
  447. for (const [key, entry] of Object.entries(value)) {
  448. if (typeof entry !== "string") {
  449. throw new Error(`Credential record value must be a string: ${key}`);
  450. }
  451. result[key] = entry;
  452. }
  453. return result;
  454. }
  455. function getErrorCode(error: unknown): string | undefined {
  456. if (typeof error !== "object" || error === null || !("code" in error)) {
  457. return undefined;
  458. }
  459. const code = (error as { code?: unknown }).code;
  460. return typeof code === "string" ? code : undefined;
  461. }
  462. function validateCredentialKey(key: string): string {
  463. const trimmed = key.trim();
  464. if (trimmed.length === 0) {
  465. throw new Error("Credential key must not be empty");
  466. }
  467. return trimmed;
  468. }
  469. function validateCredentialValue(value: string): string {
  470. if (value.length === 0) {
  471. throw new Error("Credential value must not be empty");
  472. }
  473. return value;
  474. }
  475. function resolveUserPath(value: string): string {
  476. if (value === "~") {
  477. return homedir();
  478. }
  479. if (value.startsWith("~/")) {
  480. return join(homedir(), value.slice(2));
  481. }
  482. return resolve(value);
  483. }
  484. function isRecord(value: unknown): value is Record<string, unknown> {
  485. return typeof value === "object" && value !== null && !Array.isArray(value);
  486. }