shared-credentials.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import { existsSync, readFileSync } from "node:fs";
  2. import { readFile } from "node:fs/promises";
  3. import { homedir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import { atomicWritePrivateTextFile, backupCorruptFile, withFileLock } from "@zcode/shared/node";
  6. import { createZCodeCredentialCipher, type ZCodeCredentialCipher } from "./credential-cipher.js";
  7. const ZCODE_DATA_BASE_DIR_ENV_KEY = "ZCODE_DATA_BASE_DIR";
  8. const ZAI_PROVIDER_ID = "zai";
  9. const credentialChangeListeners = new Map<
  10. string,
  11. Set<() => void | Promise<void>>
  12. >();
  13. export const SHARED_ZCODE_CREDENTIAL_KEYS = {
  14. activeProvider: "oauth:active_provider",
  15. bigmodelAccessToken: "oauth:bigmodel:access_token",
  16. bigmodelRefreshToken: "oauth:bigmodel:refresh_token",
  17. bigmodelUserInfo: "oauth:bigmodel:user_info",
  18. zaiAccessToken: "oauth:zai:access_token",
  19. zaiRefreshToken: "oauth:zai:refresh_token",
  20. zaiUserInfo: "oauth:zai:user_info",
  21. zcodeJwtToken: "zcodejwttoken",
  22. } as const;
  23. export interface SharedZCodeCredentialStoreOptions {
  24. baseDir?: string;
  25. cipher?: ZCodeCredentialCipher;
  26. env?: Record<string, string | undefined>;
  27. filePath?: string;
  28. }
  29. export interface ZaiLoginCredentialUser {
  30. avatar?: string;
  31. email?: string;
  32. name?: string;
  33. user_id: string;
  34. }
  35. export interface ZaiLoginCredentialPayload {
  36. accessToken: string;
  37. jwtToken: string;
  38. user: ZaiLoginCredentialUser;
  39. }
  40. export interface SharedZCodeCredentialStore {
  41. readonly filePath: string;
  42. clearZaiLoginCredentials(): Promise<void>;
  43. delete(key: string): Promise<void>;
  44. deleteIfValue(key: string, expectedValue: string): Promise<boolean>;
  45. deleteIfValues(
  46. expectedValues: Readonly<Record<string, string>>,
  47. ): Promise<Record<string, boolean>>;
  48. deleteManyIfValue(
  49. guardKey: string,
  50. expectedGuardValue: string,
  51. keysToDelete: readonly string[],
  52. ): Promise<boolean>;
  53. load(key: string): Promise<string | null>;
  54. loadMany(keys: readonly string[]): Promise<Record<string, string | null>>;
  55. onDidChange?(listener: () => void | Promise<void>): () => void;
  56. save(key: string, value: string): Promise<void>;
  57. saveMany(entries: Readonly<Record<string, string>>): Promise<void>;
  58. saveReplacing(key: string, value: string, replacedKeys: readonly string[]): Promise<void>;
  59. saveZaiLoginCredentials(payload: ZaiLoginCredentialPayload): Promise<void>;
  60. }
  61. export function createSharedZCodeCredentialStore(
  62. options: SharedZCodeCredentialStoreOptions = {},
  63. ): SharedZCodeCredentialStore {
  64. const env = options.env ?? process.env;
  65. const filePath = resolveSharedZCodeCredentialsPath(options);
  66. const cipher = options.cipher ?? createZCodeCredentialCipher({ env });
  67. return {
  68. filePath,
  69. async clearZaiLoginCredentials(): Promise<void> {
  70. await mutateRawCredentialRecord(filePath, async (rawCredentials) => {
  71. const activeProviderRaw = rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
  72. const activeProvider = activeProviderRaw ? cipher.decrypt(activeProviderRaw) : null;
  73. delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken];
  74. delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiRefreshToken];
  75. delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo];
  76. delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken];
  77. if (activeProvider === ZAI_PROVIDER_ID) {
  78. delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
  79. }
  80. });
  81. },
  82. async delete(key: string): Promise<void> {
  83. const validatedKey = validateCredentialKey(key);
  84. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  85. delete rawCredentials[validatedKey];
  86. });
  87. },
  88. async deleteIfValue(key: string, expectedValue: string): Promise<boolean> {
  89. const validatedKey = validateCredentialKey(key);
  90. const validatedExpectedValue = validateCredentialValue(expectedValue);
  91. let deleted = false;
  92. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  93. const encryptedValue = rawCredentials[validatedKey];
  94. if (
  95. encryptedValue === undefined ||
  96. cipher.decrypt(encryptedValue) !== validatedExpectedValue
  97. ) {
  98. return;
  99. }
  100. delete rawCredentials[validatedKey];
  101. deleted = true;
  102. });
  103. return deleted;
  104. },
  105. async deleteIfValues(
  106. expectedValues: Readonly<Record<string, string>>,
  107. ): Promise<Record<string, boolean>> {
  108. const validatedEntries = Object.entries(expectedValues).map(
  109. ([key, value]) => [validateCredentialKey(key), validateCredentialValue(value)] as const,
  110. );
  111. if (validatedEntries.length === 0) return {};
  112. const deleted: Record<string, boolean> = {};
  113. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  114. for (const [key, expectedValue] of validatedEntries) {
  115. const encryptedValue = rawCredentials[key];
  116. const matches =
  117. encryptedValue !== undefined && cipher.decrypt(encryptedValue) === expectedValue;
  118. deleted[key] = matches;
  119. if (matches) delete rawCredentials[key];
  120. }
  121. });
  122. return deleted;
  123. },
  124. /**
  125. * 条件事务:`guardKey` 当前值与期望值相等才删除 `keysToDelete` 全部 key,否则一个都不删。
  126. *
  127. * `deleteIfValues` 是逐 key 比较、逐 key 删除,无法表达「canonical generation 匹配
  128. * 才整体失效」——canonical 比较失败时 legacy 镜像仍可能被删掉,反之亦然。OAuth 凭据失效必须
  129. * 是整对的:stale 事务不能删掉 winner 的 canonical,也不能只删掉它的一半镜像。
  130. */
  131. async deleteManyIfValue(
  132. guardKey: string,
  133. expectedGuardValue: string,
  134. keysToDelete: readonly string[],
  135. ): Promise<boolean> {
  136. const validatedGuardKey = validateCredentialKey(guardKey);
  137. const validatedExpectedValue = validateCredentialValue(expectedGuardValue);
  138. const validatedKeys = keysToDelete.map(validateCredentialKey);
  139. let deleted = false;
  140. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  141. const encryptedGuard = rawCredentials[validatedGuardKey];
  142. if (
  143. encryptedGuard === undefined ||
  144. cipher.decrypt(encryptedGuard) !== validatedExpectedValue
  145. ) {
  146. return;
  147. }
  148. for (const key of validatedKeys) delete rawCredentials[key];
  149. deleted = true;
  150. });
  151. return deleted;
  152. },
  153. async load(key: string): Promise<string | null> {
  154. const rawCredentials = await readRawCredentialRecord(filePath);
  155. const rawValue = rawCredentials[validateCredentialKey(key)];
  156. if (rawValue === undefined) {
  157. return null;
  158. }
  159. return cipher.decrypt(rawValue);
  160. },
  161. async loadMany(keys: readonly string[]): Promise<Record<string, string | null>> {
  162. const validatedKeys = keys.map(validateCredentialKey);
  163. const rawCredentials = await readRawCredentialRecord(filePath);
  164. return Object.fromEntries(
  165. validatedKeys.map((key) => {
  166. const rawValue = rawCredentials[key];
  167. return [key, rawValue === undefined ? null : cipher.decrypt(rawValue)];
  168. }),
  169. );
  170. },
  171. onDidChange(listener: () => void | Promise<void>): () => void {
  172. let listeners = credentialChangeListeners.get(filePath);
  173. if (!listeners) {
  174. listeners = new Set();
  175. credentialChangeListeners.set(filePath, listeners);
  176. }
  177. listeners.add(listener);
  178. return () => {
  179. listeners?.delete(listener);
  180. if (listeners?.size === 0) credentialChangeListeners.delete(filePath);
  181. };
  182. },
  183. async save(key: string, value: string): Promise<void> {
  184. const validatedKey = validateCredentialKey(key);
  185. const encryptedValue = cipher.encrypt(validateCredentialValue(value));
  186. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  187. rawCredentials[validatedKey] = encryptedValue;
  188. });
  189. },
  190. async saveMany(entries: Readonly<Record<string, string>>): Promise<void> {
  191. const encryptedEntries = Object.entries(entries).map(
  192. ([key, value]) =>
  193. [validateCredentialKey(key), cipher.encrypt(validateCredentialValue(value))] as const,
  194. );
  195. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  196. for (const [key, encryptedValue] of encryptedEntries) {
  197. rawCredentials[key] = encryptedValue;
  198. }
  199. });
  200. },
  201. async saveReplacing(
  202. key: string,
  203. value: string,
  204. replacedKeys: readonly string[],
  205. ): Promise<void> {
  206. const validatedKey = validateCredentialKey(key);
  207. const encryptedValue = cipher.encrypt(validateCredentialValue(value));
  208. const validatedReplacedKeys = replacedKeys.map(validateCredentialKey);
  209. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  210. rawCredentials[validatedKey] = encryptedValue;
  211. for (const replacedKey of validatedReplacedKeys) {
  212. if (replacedKey !== validatedKey) delete rawCredentials[replacedKey];
  213. }
  214. });
  215. },
  216. async saveZaiLoginCredentials(payload: ZaiLoginCredentialPayload): Promise<void> {
  217. const encryptedCredentials = {
  218. activeProvider: cipher.encrypt(ZAI_PROVIDER_ID),
  219. accessToken: cipher.encrypt(validateCredentialValue(payload.accessToken)),
  220. jwtToken: cipher.encrypt(validateCredentialValue(payload.jwtToken)),
  221. userInfo: cipher.encrypt(JSON.stringify(payload.user)),
  222. };
  223. await mutateRawCredentialRecord(filePath, (rawCredentials) => {
  224. rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider] =
  225. encryptedCredentials.activeProvider;
  226. rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken] =
  227. encryptedCredentials.accessToken;
  228. rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken] = encryptedCredentials.jwtToken;
  229. rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo] = encryptedCredentials.userInfo;
  230. });
  231. },
  232. };
  233. }
  234. export function loadSharedZCodeCredentialSync(
  235. key: string,
  236. options: SharedZCodeCredentialStoreOptions = {},
  237. ): string | undefined {
  238. const filePath = resolveSharedZCodeCredentialsPath(options);
  239. if (!existsSync(filePath)) {
  240. return undefined;
  241. }
  242. try {
  243. const raw = readFileSync(filePath, "utf-8");
  244. const parsed = JSON.parse(raw);
  245. const record = parseCredentialRecord(parsed);
  246. const rawValue = record[validateCredentialKey(key)];
  247. if (rawValue === undefined) {
  248. return undefined;
  249. }
  250. const cipher = options.cipher ?? createZCodeCredentialCipher({ env: options.env });
  251. const decrypted = cipher.decrypt(rawValue);
  252. return decrypted.trim().length > 0 ? decrypted : undefined;
  253. } catch {
  254. return undefined;
  255. }
  256. }
  257. export function resolveSharedZCodeCredentialsPath(
  258. options: SharedZCodeCredentialStoreOptions = {},
  259. ): string {
  260. if (options.filePath) {
  261. return resolveUserPath(options.filePath);
  262. }
  263. const env = options.env ?? process.env;
  264. const baseDir = options.baseDir ?? env[ZCODE_DATA_BASE_DIR_ENV_KEY] ?? homedir();
  265. return join(resolveUserPath(baseDir), ".zcode", "v2", "credentials.json");
  266. }
  267. async function readRawCredentialRecord(filePath: string): Promise<Record<string, string>> {
  268. let raw: string;
  269. try {
  270. raw = await readFile(filePath, "utf-8");
  271. } catch (error) {
  272. if (getErrorCode(error) === "ENOENT") {
  273. return {};
  274. }
  275. throw new Error(`Unable to read shared ZCode credentials: ${filePath}`, { cause: error });
  276. }
  277. try {
  278. return parseCredentialRecord(JSON.parse(raw));
  279. } catch (error) {
  280. // 损坏的凭据文件若被当成空对象继续保存,会一次性抹掉其他进程的全部凭据。
  281. // 先保留现场再失败,调用方必须显式处理恢复,不能静默覆盖。
  282. const backupPath = await backupCorruptFile(filePath).catch(() => undefined);
  283. const evidence = backupPath ? ` Backup: ${backupPath}` : "";
  284. throw new Error(`Shared ZCode credentials are corrupt: ${filePath}.${evidence}`, {
  285. cause: error,
  286. });
  287. }
  288. }
  289. async function mutateRawCredentialRecord(
  290. filePath: string,
  291. mutation: (value: Record<string, string>) => void | Promise<void>,
  292. ): Promise<void> {
  293. // CLI、设置页和 session 可能位于不同 Node 进程;锁必须覆盖完整的
  294. // read-modify-write,单独原子 rename 只能防半写,不能防旧快照覆盖新 key。
  295. await withFileLock(filePath, async () => {
  296. const value = await readRawCredentialRecord(filePath);
  297. await mutation(value);
  298. await atomicWritePrivateTextFile(filePath, `${JSON.stringify(value, null, 2)}\n`);
  299. });
  300. const listeners = [...(credentialChangeListeners.get(filePath) ?? [])];
  301. // 同进程的 Registry Source 需要在登录返回前观察到新凭据;单个监听者失败不应
  302. // 把已经原子落盘的 Credential 伪装成写入失败。
  303. await Promise.allSettled(listeners.map((listener) => listener()));
  304. }
  305. function parseCredentialRecord(value: unknown): Record<string, string> {
  306. if (!isRecord(value)) {
  307. throw new Error("Credential record must be an object");
  308. }
  309. const result: Record<string, string> = {};
  310. for (const [key, entry] of Object.entries(value)) {
  311. if (typeof entry !== "string") {
  312. throw new Error(`Credential record value must be a string: ${key}`);
  313. }
  314. result[key] = entry;
  315. }
  316. return result;
  317. }
  318. function getErrorCode(error: unknown): string | undefined {
  319. if (typeof error !== "object" || error === null || !("code" in error)) {
  320. return undefined;
  321. }
  322. const code = (error as { code?: unknown }).code;
  323. return typeof code === "string" ? code : undefined;
  324. }
  325. function validateCredentialKey(key: string): string {
  326. const trimmed = key.trim();
  327. if (trimmed.length === 0) {
  328. throw new Error("Credential key must not be empty");
  329. }
  330. return trimmed;
  331. }
  332. function validateCredentialValue(value: string): string {
  333. if (value.length === 0) {
  334. throw new Error("Credential value must not be empty");
  335. }
  336. return value;
  337. }
  338. function resolveUserPath(value: string): string {
  339. if (value === "~") {
  340. return homedir();
  341. }
  342. if (value.startsWith("~/")) {
  343. return join(homedir(), value.slice(2));
  344. }
  345. return resolve(value);
  346. }
  347. function isRecord(value: unknown): value is Record<string, unknown> {
  348. return typeof value === "object" && value !== null && !Array.isArray(value);
  349. }