nodeApiClient.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import {
  2. ApiError,
  3. DEFAULT_ZCODE_ENDPOINT_ORIGIN,
  4. normalizeZCodeEndpointOrigin,
  5. rewriteZCodeEndpointUrl,
  6. type ApiClient,
  7. type ApiRequestInit,
  8. } from "@zcode/shared";
  9. import { createServiceLogger } from "#src/logger/serviceLogger.js";
  10. import { buildZCodeSourceHeaders } from "../sourceHeaders.js";
  11. import { withRequestIdHeader } from "./requestIdHeaders.js";
  12. const log = createServiceLogger("node-api-client");
  13. interface NodeApiClientOptions {
  14. fetchImpl?: typeof fetch;
  15. onZcodeJwtInvalid?: (input: string | URL, headers: Headers) => void;
  16. isZcodeJwtRequest?: (input: string | URL, headers: Headers) => boolean | Promise<boolean>;
  17. isBusinessUnauthorizedRequest?: (
  18. input: string | URL,
  19. headers: Headers,
  20. ) => boolean | Promise<boolean>;
  21. businessUnauthorizedObservationTimeoutMs?: number;
  22. resolveZCodeEndpointOrigin?: () => Promise<string> | string;
  23. }
  24. const DEFAULT_BUSINESS_UNAUTHORIZED_OBSERVATION_TIMEOUT_MS = 1000;
  25. const MAX_BUSINESS_UNAUTHORIZED_OBSERVATION_BYTES = 64 * 1024;
  26. function readChunkWithinTimeout(
  27. reader: ReadableStreamDefaultReader<Uint8Array>,
  28. timeoutMs: number,
  29. ): Promise<{ done: boolean; value?: Uint8Array } | null> {
  30. return new Promise((resolve) => {
  31. let settled = false;
  32. const timer = setTimeout(() => {
  33. settled = true;
  34. resolve(null);
  35. }, timeoutMs);
  36. reader.read().then(
  37. (result) => {
  38. if (settled) return;
  39. settled = true;
  40. clearTimeout(timer);
  41. resolve(result);
  42. },
  43. () => {
  44. if (settled) return;
  45. settled = true;
  46. clearTimeout(timer);
  47. resolve(null);
  48. },
  49. );
  50. });
  51. }
  52. function resolveMethod(init?: ApiRequestInit): string {
  53. return (init?.method ?? "GET").toUpperCase();
  54. }
  55. function resolveUrl(input: string | URL): string {
  56. return typeof input === "string" ? input : input.toString();
  57. }
  58. async function hasBusinessUnauthorizedCode(
  59. response: Response,
  60. timeoutMs: number,
  61. ): Promise<boolean> {
  62. // 业务接口把登录过期封装成 HTTP 200,不能只看 status;读副本避免抢走调用方正文。
  63. // continuous SSE 没有完整 JSON 正文,观察器不能等待流结束或引入恢复语义。
  64. if (response.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream"))
  65. return false;
  66. let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
  67. try {
  68. const body = response.clone().body;
  69. if (!body) return false;
  70. reader = body.getReader();
  71. const decoder = new TextDecoder();
  72. const deadline = Date.now() + timeoutMs;
  73. let bytes = 0;
  74. let text = "";
  75. while (true) {
  76. const remainingMs = deadline - Date.now();
  77. if (remainingMs <= 0) return false;
  78. const result = await readChunkWithinTimeout(reader, remainingMs);
  79. if (!result) return false;
  80. if (result.done) break;
  81. if (!result.value) return false;
  82. bytes += result.value.byteLength;
  83. if (bytes > MAX_BUSINESS_UNAUTHORIZED_OBSERVATION_BYTES) return false;
  84. text += decoder.decode(result.value, { stream: true });
  85. }
  86. text += decoder.decode();
  87. const payload: unknown = JSON.parse(text);
  88. return (
  89. typeof payload === "object" && payload !== null && "code" in payload && payload.code === 401
  90. );
  91. } catch {
  92. // 空正文/HTML/损坏 JSON 只能证明请求异常,不能据此清理登录态。
  93. return false;
  94. } finally {
  95. // 观察副本是 best-effort;超时、超限或解析失败时及时取消,不能占用连接。
  96. if (reader) void reader.cancel().catch(() => undefined);
  97. }
  98. }
  99. function readHeaderKeys(headers: RequestInit["headers"] | undefined): string[] {
  100. if (!headers) {
  101. return [];
  102. }
  103. return [...new Headers(headers).keys()].sort();
  104. }
  105. function isRequestForEndpoint(input: string | URL, endpointOrigin: string): boolean {
  106. try {
  107. return new URL(resolveUrl(input)).origin === normalizeZCodeEndpointOrigin(endpointOrigin);
  108. } catch {
  109. return false;
  110. }
  111. }
  112. function withZCodeEndpointHeaders(
  113. headers: RequestInit["headers"] | undefined,
  114. endpointOrigin: string,
  115. ): RequestInit["headers"] {
  116. const next = new Headers(buildZCodeSourceHeaders());
  117. if (headers) {
  118. new Headers(headers).forEach((value, key) => {
  119. next.set(key, value);
  120. });
  121. }
  122. if (next.get("HTTP-Referer") === DEFAULT_ZCODE_ENDPOINT_ORIGIN) {
  123. next.set("HTTP-Referer", endpointOrigin);
  124. }
  125. return next;
  126. }
  127. function resolveRequestHeaders(
  128. requestInput: string | URL,
  129. headers: RequestInit["headers"] | undefined,
  130. endpointOrigin: string,
  131. ): RequestInit["headers"] | undefined {
  132. if (!isRequestForEndpoint(requestInput, endpointOrigin)) {
  133. return headers;
  134. }
  135. // ZCode 后端请求以前只有部分业务路径手动补来源头。
  136. // 统一在 ApiClient 出口按 endpoint origin 注入,避免 OAuth/config/billing/snapshot 等链路遗漏。
  137. return withZCodeEndpointHeaders(headers, endpointOrigin);
  138. }
  139. export class NodeApiClient implements ApiClient {
  140. private readonly fetchImpl?: typeof fetch;
  141. private readonly resolveZCodeEndpointOrigin?: () => Promise<string> | string;
  142. private readonly onZcodeJwtInvalid?: (input: string | URL, headers: Headers) => void;
  143. private readonly isZcodeJwtRequest?: NodeApiClientOptions["isZcodeJwtRequest"];
  144. private readonly isBusinessUnauthorizedRequest?: NodeApiClientOptions["isBusinessUnauthorizedRequest"];
  145. private readonly businessUnauthorizedObservationTimeoutMs: number;
  146. constructor(options: NodeApiClientOptions = {}) {
  147. this.fetchImpl = options.fetchImpl;
  148. this.onZcodeJwtInvalid = options.onZcodeJwtInvalid;
  149. this.isZcodeJwtRequest = options.isZcodeJwtRequest;
  150. this.isBusinessUnauthorizedRequest = options.isBusinessUnauthorizedRequest;
  151. this.businessUnauthorizedObservationTimeoutMs =
  152. options.businessUnauthorizedObservationTimeoutMs ??
  153. DEFAULT_BUSINESS_UNAUTHORIZED_OBSERVATION_TIMEOUT_MS;
  154. this.resolveZCodeEndpointOrigin = options.resolveZCodeEndpointOrigin;
  155. }
  156. async request(input: string | URL, init?: ApiRequestInit): Promise<Response> {
  157. const endpointOrigin = this.resolveZCodeEndpointOrigin
  158. ? await this.resolveZCodeEndpointOrigin()
  159. : undefined;
  160. const activeEndpointOrigin = endpointOrigin ?? DEFAULT_ZCODE_ENDPOINT_ORIGIN;
  161. const requestInput = rewriteZCodeEndpointUrl(input, activeEndpointOrigin);
  162. const url = resolveUrl(requestInput);
  163. const method = resolveMethod(init);
  164. const timeoutMs = init?.timeoutMs;
  165. const controller = timeoutMs && timeoutMs > 0 ? new AbortController() : null;
  166. let didTimeout = false;
  167. const timer =
  168. controller && timeoutMs
  169. ? setTimeout(() => {
  170. didTimeout = true;
  171. controller.abort();
  172. }, timeoutMs)
  173. : null;
  174. try {
  175. const signal = controller
  176. ? init?.signal
  177. ? AbortSignal.any([init.signal, controller.signal])
  178. : controller.signal
  179. : init?.signal;
  180. if (signal?.aborted) {
  181. throw new DOMException("The operation was aborted.", "AbortError");
  182. }
  183. const fetchImpl = this.fetchImpl ?? globalThis.fetch;
  184. const requestHeaders = withRequestIdHeader(
  185. resolveRequestHeaders(requestInput, init?.headers, activeEndpointOrigin),
  186. );
  187. if (isRequestForEndpoint(requestInput, activeEndpointOrigin)) {
  188. // 调试说明:这里只记录 header key,避免 Authorization / token 等敏感值落盘。
  189. log.debug(undefined, "zcode endpoint request headers prepared", {
  190. headerKeys: readHeaderKeys(requestHeaders),
  191. method,
  192. url,
  193. });
  194. }
  195. const response = await fetchImpl(requestInput, {
  196. ...init,
  197. headers: requestHeaders,
  198. ...(signal ? { signal } : {}),
  199. });
  200. if ((response.status === 401 || response.status === 200) && this.onZcodeJwtInvalid) {
  201. try {
  202. const requestHeadersForObservation = new Headers(requestHeaders);
  203. const isCurrentZCodeJwtRequest = await this.isZcodeJwtRequest?.(
  204. requestInput,
  205. requestHeadersForObservation,
  206. );
  207. if (
  208. isCurrentZCodeJwtRequest &&
  209. (response.status === 401 ||
  210. ((await this.isBusinessUnauthorizedRequest?.(
  211. requestInput,
  212. requestHeadersForObservation,
  213. )) &&
  214. (await hasBusinessUnauthorizedCode(
  215. response,
  216. this.businessUnauthorizedObservationTimeoutMs,
  217. ))))
  218. ) {
  219. this.onZcodeJwtInvalid(requestInput, requestHeadersForObservation);
  220. }
  221. } catch (error) {
  222. log.warn("zcode jwt invalid response observation failed", { error });
  223. }
  224. }
  225. return response;
  226. } catch (error) {
  227. if (error instanceof ApiError) {
  228. throw error;
  229. }
  230. if (error instanceof DOMException && error.name === "AbortError") {
  231. throw new ApiError({
  232. message:
  233. didTimeout && timeoutMs ? `Request timed out after ${timeoutMs}ms` : error.message,
  234. url,
  235. method,
  236. cause: error,
  237. });
  238. }
  239. const message = error instanceof Error ? error.message : String(error);
  240. throw new ApiError({
  241. message,
  242. url,
  243. method,
  244. cause: error,
  245. });
  246. } finally {
  247. if (timer) {
  248. clearTimeout(timer);
  249. }
  250. }
  251. }
  252. }
  253. export function createNodeApiClient(options: NodeApiClientOptions = {}): ApiClient {
  254. return new NodeApiClient(options);
  255. }