coding-plan-api-key.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { AsyncLocalStorage } from "node:async_hooks";
  2. import {
  3. isHttpClientPortError,
  4. type HttpClientPort,
  5. type HttpClientRunOptions,
  6. type TraceContext,
  7. } from "@zcode/contracts";
  8. import {
  9. ProjectAccessTokenClient,
  10. ProjectAccessTokenTransientError,
  11. resolveBigModelApiOrigin,
  12. type ProjectAccessTokenMaterial,
  13. } from "@zcode/shared";
  14. import { ZaiBusinessTokenCache, type ZaiBusinessToken } from "./zai-business-token-cache.js";
  15. const BUSINESS_AUTH_MAX_ATTEMPTS = 2;
  16. const SINGLE_ATTEMPT = 1;
  17. const PROJECT_TOKEN_REQUEST_TIMEOUT_MS = 15_000;
  18. const ZAI_API_HOST = "https://api.z.ai";
  19. export type CodingPlanFamily = "bigmodel" | "zai";
  20. export interface CodingPlanApiKeyResolverOptions {
  21. httpClient: HttpClientPort;
  22. trace?: TraceContext;
  23. locationStore?: {
  24. load(key: string): Promise<string | null>;
  25. save(key: string, value: string): Promise<void>;
  26. delete(key: string): Promise<void>;
  27. };
  28. observe?(event: { family: string; stage: "resolve"; code: string }): void;
  29. }
  30. export interface ResolveCodingPlanApiKeyInput {
  31. accessToken: string;
  32. family: CodingPlanFamily;
  33. accountIdentity?: string;
  34. rejectedProjectTokenFingerprint?: string;
  35. trace?: TraceContext;
  36. }
  37. export interface CodingPlanApiKeyResolver {
  38. resolve(input: ResolveCodingPlanApiKeyInput, options?: HttpClientRunOptions): Promise<string>;
  39. resolveMaterial(
  40. input: ResolveCodingPlanApiKeyInput,
  41. options?: HttpClientRunOptions,
  42. ): Promise<ProjectAccessTokenMaterial>;
  43. clear(): void;
  44. }
  45. export class CodingPlanApiKeyError extends Error {
  46. constructor(message: string) {
  47. super(message);
  48. this.name = "CodingPlanApiKeyError";
  49. }
  50. }
  51. /** CLI 进程内唯一换证入口;保留旧导出名兼容调用方,返回值已是短期 Token。 */
  52. export function createCodingPlanApiKeyResolver(
  53. options: CodingPlanApiKeyResolverOptions,
  54. ): CodingPlanApiKeyResolver {
  55. const execution = new AsyncLocalStorage<{
  56. context?: HttpClientRunOptions["context"];
  57. trace?: TraceContext;
  58. business?: ZaiBusinessToken;
  59. }>();
  60. const businessTokens = new ZaiBusinessTokenCache(() =>
  61. options.observe?.({
  62. family: "zai",
  63. stage: "resolve",
  64. code: "project_token_business_login_refresh_deferred",
  65. }),
  66. );
  67. const request = async (url: string, init: RequestInit) => {
  68. const response = await options.httpClient
  69. .request(
  70. {
  71. url,
  72. method: init.method === "POST" ? "POST" : "GET",
  73. headers: Object.fromEntries(new Headers(init.headers)),
  74. ...(typeof init.body === "string" ? { body: new TextEncoder().encode(init.body) } : {}),
  75. maxResponseBytes: 64 * 1024,
  76. timeoutMs: PROJECT_TOKEN_REQUEST_TIMEOUT_MS,
  77. trace: execution.getStore()?.trace ?? options.trace,
  78. },
  79. { context: execution.getStore()?.context },
  80. )
  81. .catch((error: unknown) => {
  82. if (
  83. isHttpClientPortError(error) &&
  84. (error.code === "network_error" || error.code === "timeout")
  85. )
  86. throw new ProjectAccessTokenTransientError();
  87. throw error;
  88. });
  89. if (response.status === 401 && new URL(url).pathname.startsWith("/api/biz/")) {
  90. const run = execution.getStore();
  91. if (
  92. run?.business &&
  93. new Headers(init.headers).get("Authorization") === `Bearer ${run.business.token}`
  94. )
  95. businessTokens.invalidate(run.business);
  96. }
  97. if (response.status === 404) return { code: 404 };
  98. if (response.status === 429 || (response.status >= 500 && response.status < 600))
  99. throw new ProjectAccessTokenTransientError();
  100. if (response.status < 200 || response.status >= 300)
  101. throw new CodingPlanApiKeyError("project_token_request_failed");
  102. return JSON.parse(new TextDecoder().decode(response.body)) as unknown;
  103. };
  104. const client = new ProjectAccessTokenClient({
  105. request,
  106. observe: options.observe,
  107. locationStore: options.locationStore,
  108. });
  109. let generation = 0;
  110. const resolveMaterial = async (
  111. input: ResolveCodingPlanApiKeyInput,
  112. ): Promise<ProjectAccessTokenMaterial> => {
  113. const oauth = input.accessToken.trim();
  114. if (!oauth) throw new CodingPlanApiKeyError("project_token_login_required");
  115. const capturedGeneration = generation;
  116. const maxAttempts = input.family === "zai" ? BUSINESS_AUTH_MAX_ATTEMPTS : SINGLE_ATTEMPT;
  117. for (let attempt = 0; attempt < maxAttempts; attempt++) {
  118. if (generation !== capturedGeneration)
  119. throw new CodingPlanApiKeyError("project_token_scope_invalidated");
  120. const business =
  121. input.family === "zai"
  122. ? await businessTokens
  123. .resolve(oauth, () =>
  124. request(`${ZAI_API_HOST}/api/auth/z/login`, {
  125. method: "POST",
  126. headers: { "Content-Type": "application/json" },
  127. body: JSON.stringify({ token: oauth }),
  128. }),
  129. )
  130. .catch(() => {
  131. options.observe?.({
  132. family: input.family,
  133. stage: "resolve",
  134. code: "project_token_login_failed",
  135. });
  136. throw new CodingPlanApiKeyError("project_token_login_failed");
  137. })
  138. : undefined;
  139. if (generation !== capturedGeneration)
  140. throw new CodingPlanApiKeyError("project_token_scope_invalidated");
  141. const loginToken = business?.token ?? oauth;
  142. const run = execution.getStore();
  143. if (run) run.business = business;
  144. try {
  145. const result = await client.resolve({
  146. origin: input.family === "zai" ? ZAI_API_HOST : resolveBigModelApiOrigin(process.env),
  147. family: input.family,
  148. loginToken,
  149. accountId: input.accountIdentity ?? input.family,
  150. personalProjectSelection: "default",
  151. rejectedProjectTokenFingerprint: input.rejectedProjectTokenFingerprint,
  152. });
  153. if (generation !== capturedGeneration)
  154. throw new CodingPlanApiKeyError("project_token_scope_invalidated");
  155. return result;
  156. } catch (error) {
  157. // 只恢复业务 JWT 的明确 HTTP 401;不把模型 401、403 或网络故障猜成过期。
  158. if (!business || !businessTokens.wasRejected(business)) throw error;
  159. businessTokens.invalidate(business);
  160. if (attempt + 1 === maxAttempts) throw error;
  161. options.observe?.({
  162. family: input.family,
  163. stage: "resolve",
  164. code: "project_token_business_login_refresh",
  165. });
  166. }
  167. }
  168. throw new CodingPlanApiKeyError("project_token_request_failed");
  169. };
  170. const resolveForCaller = (
  171. input: ResolveCodingPlanApiKeyInput,
  172. runOptions?: HttpClientRunOptions,
  173. ) =>
  174. waitForProjectToken(
  175. () =>
  176. execution.run(
  177. {
  178. // 单飞属于鉴权 owner,不继承会话 signal 或 context.abortSignal;只保留观测上下文。
  179. context: runOptions?.context
  180. ? { trace: runOptions.context.trace, logger: runOptions.context.logger }
  181. : undefined,
  182. trace: input.trace ?? runOptions?.context?.trace,
  183. },
  184. () => resolveMaterial(input),
  185. ),
  186. runOptions?.signal,
  187. );
  188. return {
  189. resolveMaterial: resolveForCaller,
  190. async resolve(input, runOptions) {
  191. const value = await resolveForCaller(input, runOptions);
  192. return value.token;
  193. },
  194. clear() {
  195. generation++;
  196. businessTokens.clear();
  197. client.clear();
  198. },
  199. };
  200. }
  201. /** 仅取消当前调用方的等待;底层 Promise 始终有拒绝处理器,不误伤共享换证。 */
  202. async function waitForProjectToken<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
  203. if (!signal) return run();
  204. signal.throwIfAborted();
  205. const value = await new Promise<T>((resolve, reject) => {
  206. const cleanup = () => signal.removeEventListener("abort", onAbort);
  207. const onAbort = () => {
  208. cleanup();
  209. reject(signal.reason);
  210. };
  211. signal.addEventListener("abort", onAbort, { once: true });
  212. Promise.resolve()
  213. .then(() => {
  214. signal.throwIfAborted();
  215. return run();
  216. })
  217. .then(
  218. (result) => {
  219. cleanup();
  220. resolve(result);
  221. },
  222. (error: unknown) => {
  223. cleanup();
  224. reject(error);
  225. },
  226. );
  227. });
  228. signal.throwIfAborted();
  229. return value;
  230. }