shared-credentials.ts 19 KB

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