standalone-account-provider-runtime.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import { createHash } from "node:crypto";
  2. import {
  3. createCodingPlanApiKeyResolver,
  4. SHARED_ZCODE_CREDENTIAL_KEYS,
  5. type SharedZCodeCredentialStore,
  6. } from "@zcode/adapters/auth";
  7. import { createNodeHttpClientAdapter } from "@zcode/adapters/http";
  8. import { createConfig } from "@zcode/adapters/config";
  9. import type { ProviderRuntimeHeadersPort } from "@zcode/core";
  10. import {
  11. createAccountProviderConfigSnapshot,
  12. ProviderConfig,
  13. ProviderConfigMap,
  14. ZhipuAccountAccessConfig,
  15. type AccountProviderConfigSnapshot,
  16. type ProviderConfigLayerSnapshot,
  17. } from "@zcode/provider";
  18. import {
  19. NodeZCodeBuiltinProviderConfigSource,
  20. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV,
  21. } from "@zcode/provider-node";
  22. import type { ProviderFamilyDomain } from "@zcode/shared";
  23. export interface StandaloneCodingPlanProvider {
  24. readonly family: ProviderFamilyDomain;
  25. readonly modelId: string;
  26. readonly providerId: string;
  27. }
  28. export async function readStandaloneCodingPlanProviders(
  29. env: Readonly<Record<string, string | undefined>>,
  30. ): Promise<readonly StandaloneCodingPlanProvider[]> {
  31. return (await readStandaloneCodingPlanCatalog(env)).providers;
  32. }
  33. async function readStandaloneCodingPlanCatalog(
  34. env: Readonly<Record<string, string | undefined>>,
  35. config?: Pick<ProviderConfigLayerSnapshot, "revision" | "providers">,
  36. ): Promise<{
  37. readonly zcodeBuiltinRevision: string;
  38. readonly providers: readonly StandaloneCodingPlanProvider[];
  39. }> {
  40. if (config)
  41. return {
  42. zcodeBuiltinRevision: config.revision,
  43. providers: config.providers.entries().flatMap(([providerId, provider]) => {
  44. const access = provider.access;
  45. const modelId = provider.builtinModelIds?.find((candidate) => candidate.trim())?.trim();
  46. return access?.type === "zhipu-account" &&
  47. access.mode === "individual-coding-plan" &&
  48. access.accountType &&
  49. modelId
  50. ? [{ family: access.accountType, modelId, providerId }]
  51. : [];
  52. }),
  53. };
  54. const filePath = env[ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV]?.trim();
  55. if (!filePath) {
  56. throw new Error(`${ZCODE_BUILTIN_PROVIDER_CONFIG_FILE_ENV} is required for login`);
  57. }
  58. const source = new NodeZCodeBuiltinProviderConfigSource({
  59. bundledFilePath: filePath,
  60. watch: false,
  61. });
  62. try {
  63. const snapshot = await source.read();
  64. return readStandaloneCodingPlanCatalog(env, snapshot);
  65. } finally {
  66. source.dispose();
  67. }
  68. }
  69. export async function resolveStandaloneCodingPlanProvider(
  70. family: ProviderFamilyDomain,
  71. env: Readonly<Record<string, string | undefined>>,
  72. ): Promise<StandaloneCodingPlanProvider> {
  73. const matches = (await readStandaloneCodingPlanProviders(env)).filter(
  74. (provider) => provider.family === family,
  75. );
  76. if (matches.length !== 1) {
  77. throw new Error(
  78. `ZCode Built-in Config 必须为 ${family} 声明唯一 Individual Coding Plan Provider`,
  79. );
  80. }
  81. return matches[0]!;
  82. }
  83. export function standaloneAccountIdentityCredentialKey(providerId: string): string {
  84. const normalized = providerId.trim();
  85. if (!normalized) throw new Error("Standalone Account Provider ID 不能为空");
  86. return `account-provider:${normalized}:identity`;
  87. }
  88. export function standaloneAccountAuthSourceCredentialKey(providerId: string): string {
  89. return `account-provider:${providerId}:auth-source`;
  90. }
  91. function oauthCredentialKey(family: ProviderFamilyDomain): string {
  92. return family === "zai"
  93. ? SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken
  94. : SHARED_ZCODE_CREDENTIAL_KEYS.bigmodelAccessToken;
  95. }
  96. /** Standalone Credential Store 私有键;不得进入 Provider Config、Model 或 Protocol。 */
  97. export function standaloneAccountProviderCredentialKey(input: {
  98. readonly providerId: string;
  99. readonly accountIdentity: string;
  100. }): string {
  101. const providerId = input.providerId.trim();
  102. const accountIdentity = input.accountIdentity.trim();
  103. if (!providerId) throw new Error("Standalone Account Provider ID 不能为空");
  104. if (!accountIdentity) throw new Error("Standalone Account Identity 不能为空");
  105. return `account-provider:coding-plan:${providerId}:account:${encodeURIComponent(accountIdentity)}:api-key`;
  106. }
  107. /** 没有账号 Profile 的手工 Key 登录使用稳定、不可逆的连接身份。 */
  108. export function createStandaloneAccountIdentityFromSecret(secret: string): string {
  109. const normalized = secret.trim();
  110. if (!normalized) throw new Error("Standalone Account Secret 不能为空");
  111. return `key-${createHash("sha256").update(normalized).digest("hex").slice(0, 24)}`;
  112. }
  113. export async function readStandaloneAccountProviderConfigSnapshot(
  114. credentialStore: Pick<SharedZCodeCredentialStore, "loadMany">,
  115. env: Readonly<Record<string, string | undefined>>,
  116. config?: Pick<ProviderConfigLayerSnapshot, "revision" | "providers">,
  117. ): Promise<AccountProviderConfigSnapshot> {
  118. const catalog = await readStandaloneCodingPlanCatalog(env, config);
  119. const configuredProviders = catalog.providers;
  120. const identityKeys = configuredProviders.map(({ providerId }) =>
  121. standaloneAccountIdentityCredentialKey(providerId),
  122. );
  123. const identities = await credentialStore.loadMany(identityKeys);
  124. const candidates = configuredProviders.flatMap(({ family, providerId }) => {
  125. const accountIdentity = identities[standaloneAccountIdentityCredentialKey(providerId)]?.trim();
  126. if (!accountIdentity) return [];
  127. const credentialKey = standaloneAccountProviderCredentialKey({
  128. providerId,
  129. accountIdentity,
  130. });
  131. return [{ accountIdentity, credentialKey, family, providerId }] as const;
  132. });
  133. const sources = await credentialStore.loadMany(
  134. candidates.map(({ providerId }) => standaloneAccountAuthSourceCredentialKey(providerId)),
  135. );
  136. // 先按来源选择读取范围;OAuth 不解密旧 Key,手工模式也不依赖无关 OAuth 密文。
  137. const credentials = await credentialStore.loadMany(
  138. candidates.map(({ credentialKey, providerId, family }) =>
  139. sources[standaloneAccountAuthSourceCredentialKey(providerId)] === "manual"
  140. ? credentialKey
  141. : oauthCredentialKey(family),
  142. ),
  143. );
  144. const candidateByProviderId = new Map(
  145. candidates.map((candidate) => [candidate.providerId, candidate]),
  146. );
  147. const providers = new ProviderConfigMap(
  148. configuredProviders.map(({ family, providerId }) => {
  149. const candidate = candidateByProviderId.get(providerId);
  150. const source = sources[standaloneAccountAuthSourceCredentialKey(providerId)];
  151. const requestCredentialKey =
  152. source === "manual" ? candidate?.credentialKey : oauthCredentialKey(family);
  153. const authorized = Boolean(requestCredentialKey && credentials[requestCredentialKey]?.trim());
  154. if (!candidate || !authorized) {
  155. // Bug 根因:账号 Overlay 缺少成员表示“不覆盖”,不能表达账号已断开;必须显式
  156. // entitled=false,才能让 Built-in 账号 Provider 在凭据删除后从 Registry 退出。
  157. return [
  158. providerId,
  159. new ProviderConfig({
  160. access: new ZhipuAccountAccessConfig({ entitled: false }),
  161. }),
  162. ] as const;
  163. }
  164. return [
  165. providerId,
  166. new ProviderConfig({
  167. access: new ZhipuAccountAccessConfig({ entitled: true }),
  168. }),
  169. ] as const;
  170. }),
  171. );
  172. return createAccountProviderConfigSnapshot(catalog.zcodeBuiltinRevision, providers);
  173. }
  174. export async function hasStandaloneCodingPlanAccess(
  175. credentialStore: Pick<SharedZCodeCredentialStore, "loadMany">,
  176. env: Readonly<Record<string, string | undefined>>,
  177. ): Promise<boolean> {
  178. return (await readStandaloneAccountProviderConfigSnapshot(credentialStore, env)).providers
  179. .entries()
  180. .some(([, provider]) =>
  181. provider.access?.type === "zhipu-account" ? provider.access.entitled === true : false,
  182. );
  183. }
  184. export function createStandaloneProviderRuntimeHeadersPort(
  185. credentialStore: Pick<SharedZCodeCredentialStore, "load" | "loadMany" | "save" | "delete">,
  186. env: Readonly<Record<string, string | undefined>>,
  187. injectedResolver?: ReturnType<typeof createCodingPlanApiKeyResolver>,
  188. ): ProviderRuntimeHeadersPort & {
  189. clearProjectTokens(): void;
  190. invalidateChangedCredentials(): Promise<void>;
  191. } {
  192. const config = createConfig({ env }).config;
  193. const resolver =
  194. injectedResolver ??
  195. createCodingPlanApiKeyResolver({
  196. httpClient: createNodeHttpClientAdapter({
  197. env,
  198. proxyUrl: config.network.httpProxy,
  199. noProxy: config.network.noProxy,
  200. caCertFile: config.network.caCertFile,
  201. timeoutMs: config.network.timeout,
  202. }),
  203. locationStore: credentialStore,
  204. observe: (event) => console.warn("[project-access-token]", event),
  205. });
  206. const authSnapshots = new Map<string, string>();
  207. return {
  208. clearProjectTokens() {
  209. authSnapshots.clear();
  210. resolver.clear();
  211. },
  212. async invalidateChangedCredentials() {
  213. const values = await credentialStore.loadMany([...authSnapshots.keys()]);
  214. if ([...authSnapshots].some(([key, value]) => values[key]?.trim() !== value)) {
  215. authSnapshots.clear();
  216. resolver.clear();
  217. }
  218. },
  219. shouldRefreshBeforeModelRequest() {
  220. return true;
  221. },
  222. async refreshBeforeModelRequest(input) {
  223. input.abortSignal?.throwIfAborted();
  224. const providerId = input.providerId.trim();
  225. const access = input.accountAccess;
  226. if (!access || access.mode !== "individual-coding-plan") {
  227. throw new Error(`Standalone Account Provider 请求身份无效: ${providerId}`);
  228. }
  229. const currentIdentity = (
  230. await credentialStore.load(standaloneAccountIdentityCredentialKey(providerId))
  231. )?.trim();
  232. if (!currentIdentity)
  233. throw new Error(`Standalone Account Provider 凭据已经失效: ${providerId}`);
  234. const family = access.accountType;
  235. if (!family) throw new Error("project_token_account_required");
  236. const sourceKey = standaloneAccountAuthSourceCredentialKey(providerId);
  237. const source = await credentialStore.load(sourceKey);
  238. const oauthKey = oauthCredentialKey(family);
  239. const oauth =
  240. source === "manual" ? undefined : (await credentialStore.load(oauthKey))?.trim();
  241. const useOAuth = source === "oauth" || (source !== "manual" && Boolean(oauth));
  242. let apiKey: string | undefined;
  243. let apiKeyId: string | undefined;
  244. let accountScope: string | undefined;
  245. if (useOAuth) {
  246. if (!oauth) {
  247. resolver.clear();
  248. throw new Error("project_token_login_required");
  249. }
  250. accountScope = createHash("sha256")
  251. .update(JSON.stringify([providerId, family, currentIdentity, oauth]))
  252. .digest("hex");
  253. if (
  254. (input.expectedAccountScope && input.expectedAccountScope !== accountScope) ||
  255. (input.rejectedProjectTokenFingerprint && !input.expectedAccountScope)
  256. )
  257. throw new Error("project_token_scope_invalidated");
  258. if (source !== "oauth") await credentialStore.save(sourceKey, "oauth");
  259. authSnapshots.set(oauthKey, oauth);
  260. authSnapshots.set(standaloneAccountIdentityCredentialKey(providerId), currentIdentity);
  261. authSnapshots.set(sourceKey, "oauth");
  262. const material = await resolver.resolveMaterial(
  263. {
  264. family,
  265. accessToken: oauth,
  266. accountIdentity: currentIdentity,
  267. rejectedProjectTokenFingerprint: input.rejectedProjectTokenFingerprint,
  268. trace: input.traceContext,
  269. },
  270. { signal: input.abortSignal },
  271. );
  272. apiKey = material.token;
  273. apiKeyId = material.apiKeyId;
  274. // 请求期只交付当前账号的 Token;迟到签发不能覆盖已退出/切换的登录态。
  275. if (
  276. (await credentialStore.load(oauthKey))?.trim() !== oauth ||
  277. (
  278. await credentialStore.load(standaloneAccountIdentityCredentialKey(providerId))
  279. )?.trim() !== currentIdentity ||
  280. (await credentialStore.load(sourceKey)) !== "oauth"
  281. ) {
  282. resolver.clear();
  283. throw new Error("project_token_scope_invalidated");
  284. }
  285. } else if (source === "manual") {
  286. if (input.expectedAccountScope || input.rejectedProjectTokenFingerprint)
  287. throw new Error("project_token_scope_invalidated");
  288. apiKey = (
  289. await credentialStore.load(
  290. standaloneAccountProviderCredentialKey({
  291. providerId,
  292. accountIdentity: currentIdentity,
  293. }),
  294. )
  295. )?.trim();
  296. }
  297. if (!useOAuth && source !== "manual") {
  298. // 旧格式无法区分手工和 OAuth 派生 Key;无登录态时要求重新选择登录方式,禁止猜测回退。
  299. resolver.clear();
  300. throw new Error("project_token_login_required");
  301. }
  302. input.abortSignal?.throwIfAborted();
  303. if (!apiKey) {
  304. throw new Error(`Standalone Account Provider 缺少请求凭据: ${providerId}`);
  305. }
  306. return {
  307. headersApplied: true,
  308. requestAuth: {
  309. apiKey,
  310. ...(apiKeyId ? { apiKeyId } : {}),
  311. ...(accountScope ? { accountScope } : {}),
  312. },
  313. };
  314. },
  315. };
  316. }