cli-oauth.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import { randomBytes } from "node:crypto";
  2. import type { HttpClientPort, HttpClientRunOptions, TraceContext } from "@zcode/contracts";
  3. const DEFAULT_ZCODE_OAUTH_BASE_URL = "https://zcode.z.ai/api/v1";
  4. export type CliOAuthProviderId = "zai" | "bigmodel";
  5. const POLL_TOKEN_BYTES = 32;
  6. const JSON_CONTENT_TYPE = "application/json";
  7. export interface CliOAuthClientOptions {
  8. baseUrl?: string;
  9. providerId: CliOAuthProviderId;
  10. httpClient: HttpClientPort;
  11. trace?: TraceContext;
  12. }
  13. export interface CliOAuthInitInput {
  14. pollToken: string;
  15. }
  16. export interface CliOAuthInitData {
  17. authorize_url: string;
  18. expires_at: number;
  19. flow_id: string;
  20. poll_interval_sec: number;
  21. }
  22. export interface CliOAuthPollInput {
  23. flowId: string;
  24. pollToken: string;
  25. }
  26. export interface CliOAuthUser {
  27. avatar?: string;
  28. email?: string;
  29. name?: string;
  30. user_id: string;
  31. }
  32. export interface CliOAuthReadyData {
  33. status: "ready";
  34. token: string;
  35. user: CliOAuthUser;
  36. providerId: CliOAuthProviderId;
  37. accessToken: string;
  38. refreshToken?: string;
  39. }
  40. export interface CliOAuthPendingData {
  41. status: "pending";
  42. }
  43. export interface CliOAuthFailedData {
  44. status: "failed";
  45. }
  46. export type CliOAuthPollData = CliOAuthFailedData | CliOAuthPendingData | CliOAuthReadyData;
  47. export interface CliOAuthClient {
  48. init(input: CliOAuthInitInput, options?: HttpClientRunOptions): Promise<CliOAuthInitData>;
  49. poll(input: CliOAuthPollInput, options?: HttpClientRunOptions): Promise<CliOAuthPollData>;
  50. }
  51. export class CliOAuthError extends Error {
  52. readonly businessCode?: number;
  53. readonly httpStatus?: number;
  54. constructor(message: string, details: { businessCode?: number; httpStatus?: number } = {}) {
  55. super(message);
  56. this.name = "CliOAuthError";
  57. this.businessCode = details.businessCode;
  58. this.httpStatus = details.httpStatus;
  59. }
  60. }
  61. export function createCliOAuthClient(options: CliOAuthClientOptions): CliOAuthClient {
  62. const baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_ZCODE_OAUTH_BASE_URL);
  63. const encoder = new TextEncoder();
  64. return {
  65. async init(
  66. input: CliOAuthInitInput,
  67. runOptions?: HttpClientRunOptions,
  68. ): Promise<CliOAuthInitData> {
  69. const envelope = await requestJsonEnvelope(
  70. options.httpClient,
  71. {
  72. body: encoder.encode(JSON.stringify({ provider: options.providerId })),
  73. headers: {
  74. Authorization: `Bearer ${input.pollToken}`,
  75. "Content-Type": JSON_CONTENT_TYPE,
  76. },
  77. method: "POST",
  78. trace: options.trace,
  79. url: `${baseUrl}/oauth/cli/init`,
  80. },
  81. runOptions,
  82. );
  83. return parseInitData(envelope.data);
  84. },
  85. async poll(
  86. input: CliOAuthPollInput,
  87. runOptions?: HttpClientRunOptions,
  88. ): Promise<CliOAuthPollData> {
  89. const flowId = encodeURIComponent(input.flowId);
  90. const envelope = await requestJsonEnvelope(
  91. options.httpClient,
  92. {
  93. headers: {
  94. Authorization: `Bearer ${input.pollToken}`,
  95. },
  96. method: "GET",
  97. trace: options.trace,
  98. url: `${baseUrl}/oauth/cli/poll/${flowId}`,
  99. },
  100. runOptions,
  101. );
  102. return parsePollData(envelope.data, options.providerId);
  103. },
  104. };
  105. }
  106. export function createCliOAuthPollToken(): string {
  107. return randomBytes(POLL_TOKEN_BYTES).toString("hex");
  108. }
  109. function normalizeBaseUrl(baseUrl: string): string {
  110. return baseUrl.replace(/\/+$/u, "");
  111. }
  112. async function requestJsonEnvelope(
  113. httpClient: HttpClientPort,
  114. request: Parameters<HttpClientPort["request"]>[0],
  115. options?: HttpClientRunOptions,
  116. ): Promise<{ code: number; data?: unknown; msg?: string }> {
  117. const response = await httpClient.request(
  118. {
  119. maxResponseBytes: 64 * 1024,
  120. ...request,
  121. },
  122. options,
  123. );
  124. if (response.status < 200 || response.status >= 300) {
  125. throw new CliOAuthError(`OAuth HTTP error ${response.status}`, {
  126. httpStatus: response.status,
  127. });
  128. }
  129. const bodyText = new TextDecoder().decode(response.body);
  130. const parsed = parseJson(bodyText);
  131. const envelope = asRecord(parsed);
  132. if (!envelope || typeof envelope.code !== "number") {
  133. throw new CliOAuthError("Invalid OAuth response envelope", {
  134. httpStatus: response.status,
  135. });
  136. }
  137. const responseMessage = typeof envelope.msg === "string" ? envelope.msg : undefined;
  138. if (envelope.code !== 0) {
  139. throw new CliOAuthError(responseMessage ?? `OAuth business error ${envelope.code}`, {
  140. businessCode: envelope.code,
  141. httpStatus: response.status,
  142. });
  143. }
  144. return {
  145. code: envelope.code,
  146. data: envelope.data,
  147. msg: responseMessage,
  148. };
  149. }
  150. function parseInitData(value: unknown): CliOAuthInitData {
  151. const data = asRecord(value);
  152. if (
  153. !data ||
  154. !readString(data.flow_id) ||
  155. !readString(data.authorize_url) ||
  156. typeof data.expires_at !== "number" ||
  157. !Number.isFinite(data.expires_at) ||
  158. typeof data.poll_interval_sec !== "number" ||
  159. !Number.isFinite(data.poll_interval_sec) ||
  160. data.poll_interval_sec < 1
  161. ) {
  162. throw new CliOAuthError("Invalid OAuth init response data");
  163. }
  164. try {
  165. if (new URL(readString(data.authorize_url)!).protocol !== "https:") throw new Error();
  166. } catch {
  167. throw new CliOAuthError("Invalid OAuth authorization URL");
  168. }
  169. return {
  170. authorize_url: readString(data.authorize_url)!,
  171. expires_at: data.expires_at,
  172. flow_id: readString(data.flow_id)!,
  173. poll_interval_sec: data.poll_interval_sec,
  174. };
  175. }
  176. function parsePollData(value: unknown, providerId: CliOAuthProviderId): CliOAuthPollData {
  177. const data = asRecord(value);
  178. const status = data?.status;
  179. if (status === "pending" || status === "failed") {
  180. return { status };
  181. }
  182. if (status === "ready" && data) {
  183. return parseReadyData(data, providerId);
  184. }
  185. throw new CliOAuthError("Invalid OAuth poll response data");
  186. }
  187. function parseReadyData(
  188. data: Record<string, unknown>,
  189. providerId: CliOAuthProviderId,
  190. ): CliOAuthReadyData {
  191. const user = asRecord(data.user);
  192. const provider = asRecord(data[providerId]);
  193. const accessToken = readString(provider?.access_token) ?? readString(provider?.accessToken);
  194. const refreshToken = readString(provider?.refresh_token) ?? readString(provider?.refreshToken);
  195. if (!readString(data.token) || !user || !readString(user.user_id) || !accessToken) {
  196. throw new CliOAuthError("Invalid OAuth ready response data");
  197. }
  198. return {
  199. status: "ready",
  200. token: readString(data.token)!,
  201. user: {
  202. ...(typeof user.avatar === "string" ? { avatar: user.avatar } : {}),
  203. ...(typeof user.email === "string" ? { email: user.email } : {}),
  204. ...(typeof user.name === "string" ? { name: user.name } : {}),
  205. user_id: readString(user.user_id)!,
  206. },
  207. providerId,
  208. accessToken,
  209. ...(refreshToken ? { refreshToken } : {}),
  210. };
  211. }
  212. function parseJson(value: string): unknown {
  213. try {
  214. return JSON.parse(value);
  215. } catch {
  216. throw new CliOAuthError("OAuth response is not valid JSON", {
  217. httpStatus: undefined,
  218. });
  219. }
  220. }
  221. function asRecord(value: unknown): Record<string, unknown> | undefined {
  222. return typeof value === "object" && value !== null && !Array.isArray(value)
  223. ? (value as Record<string, unknown>)
  224. : undefined;
  225. }
  226. function readString(value: unknown): string | undefined {
  227. return typeof value === "string" && value.trim() ? value.trim() : undefined;
  228. }