openai.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { createServer } from "node:http"
  2. import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/v2/effect/integration"
  3. import { define } from "@opencode-ai/plugin/v2/effect/plugin"
  4. import { Deferred, Effect } from "effect"
  5. import type { Scope } from "effect"
  6. import { Credential } from "../../credential"
  7. import { InstallationVersion } from "../../installation/version"
  8. import { Integration } from "../../integration"
  9. import { ModelV2 } from "../../model"
  10. import { OauthCallbackPage } from "../../oauth/page"
  11. import { ProviderV2 } from "../../provider"
  12. import type { PluginInternal } from "../internal"
  13. const clientID = "app_EMoamEEZ73f0CkXaXp7hrann"
  14. const issuer = "https://auth.openai.com"
  15. const callbackPort = 1455
  16. const pollingSafetyMargin = 3000
  17. const browserMethodID = Integration.MethodID.make("chatgpt-browser")
  18. const headlessMethodID = Integration.MethodID.make("chatgpt-headless")
  19. type Pkce = {
  20. verifier: string
  21. challenge: string
  22. }
  23. type TokenResponse = {
  24. id_token: string
  25. access_token: string
  26. refresh_token: string
  27. expires_in?: number
  28. }
  29. type Claims = {
  30. chatgpt_account_id?: string
  31. organizations?: Array<{ id: string }>
  32. "https://api.openai.com/auth"?: { chatgpt_account_id?: string }
  33. }
  34. const browser = {
  35. integrationID: Integration.ID.make("openai"),
  36. method: {
  37. id: browserMethodID,
  38. type: "oauth",
  39. label: "ChatGPT Pro/Plus (browser)",
  40. },
  41. authorize: () =>
  42. Effect.gen(function* () {
  43. const pkce = yield* Effect.promise(generatePKCE)
  44. const state = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
  45. const code = yield* Deferred.make<string, Error>()
  46. const redirect = `http://localhost:${callbackPort}/auth/callback`
  47. const server = createServer((request, response) => {
  48. const url = new URL(request.url ?? "/", `http://localhost:${callbackPort}`)
  49. if (url.pathname !== "/auth/callback") {
  50. response.writeHead(404).end("Not found")
  51. return
  52. }
  53. const error = url.searchParams.get("error_description") ?? url.searchParams.get("error")
  54. const value = url.searchParams.get("code")
  55. if (error) {
  56. Effect.runFork(Deferred.fail(code, new Error(error)))
  57. response
  58. .writeHead(400, { "Content-Type": "text/html" })
  59. .end(OauthCallbackPage.error(error, { provider: "ChatGPT" }))
  60. return
  61. }
  62. if (!value || url.searchParams.get("state") !== state) {
  63. const message = value ? "Invalid OAuth state" : "Missing authorization code"
  64. Effect.runFork(Deferred.fail(code, new Error(message)))
  65. response
  66. .writeHead(400, { "Content-Type": "text/html" })
  67. .end(OauthCallbackPage.error(message, { provider: "ChatGPT" }))
  68. return
  69. }
  70. Effect.runFork(Deferred.succeed(code, value))
  71. response.writeHead(200, { "Content-Type": "text/html" }).end(OauthCallbackPage.success({ provider: "ChatGPT" }))
  72. })
  73. yield* Effect.callback<void, Error>((resume) => {
  74. server.once("error", (error) => resume(Effect.fail(error)))
  75. server.listen(callbackPort, "localhost", () => resume(Effect.void))
  76. })
  77. yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))
  78. return {
  79. mode: "auto" as const,
  80. url: authorizeURL(redirect, pkce, state),
  81. instructions: "Complete authorization in your browser. This window will close automatically.",
  82. callback: Deferred.await(code).pipe(
  83. Effect.flatMap((value) => exchange(value, redirect, pkce)),
  84. Effect.map((tokens) => credential(browserMethodID, tokens)),
  85. ),
  86. }
  87. }),
  88. refresh: (value) => refresh(browserMethodID, value),
  89. } satisfies IntegrationOAuthMethodRegistration
  90. const headless = {
  91. integrationID: Integration.ID.make("openai"),
  92. method: {
  93. id: headlessMethodID,
  94. type: "oauth",
  95. label: "ChatGPT Pro/Plus (headless)",
  96. },
  97. authorize: () =>
  98. Effect.gen(function* () {
  99. const device = yield* request<{ device_auth_id: string; user_code: string; interval: string }>(
  100. `${issuer}/api/accounts/deviceauth/usercode`,
  101. {
  102. method: "POST",
  103. headers: headers("application/json"),
  104. body: JSON.stringify({ client_id: clientID }),
  105. },
  106. )
  107. const interval = Math.max(Number.parseInt(device.interval) || 5, 1) * 1000
  108. return {
  109. mode: "auto" as const,
  110. url: `${issuer}/codex/device`,
  111. instructions: `Enter code: ${device.user_code}`,
  112. callback: Effect.gen(function* () {
  113. while (true) {
  114. const response = yield* Effect.tryPromise({
  115. try: (signal) =>
  116. fetch(`${issuer}/api/accounts/deviceauth/token`, {
  117. method: "POST",
  118. headers: headers("application/json"),
  119. body: JSON.stringify({ device_auth_id: device.device_auth_id, user_code: device.user_code }),
  120. signal,
  121. }),
  122. catch: (cause) => cause,
  123. })
  124. if (response.ok) {
  125. const data = (yield* Effect.promise(() => response.json())) as {
  126. authorization_code: string
  127. code_verifier: string
  128. }
  129. return credential(
  130. headlessMethodID,
  131. yield* exchange(data.authorization_code, `${issuer}/deviceauth/callback`, {
  132. verifier: data.code_verifier,
  133. challenge: "",
  134. }),
  135. )
  136. }
  137. if (response.status !== 403 && response.status !== 404) {
  138. return yield* Effect.fail(new Error(`Device authorization failed: ${response.status}`))
  139. }
  140. yield* Effect.sleep(interval + pollingSafetyMargin)
  141. }
  142. }),
  143. }
  144. }),
  145. refresh: (value) => refresh(headlessMethodID, value),
  146. } satisfies IntegrationOAuthMethodRegistration
  147. export const OpenAIPlugin = define({
  148. id: "openai",
  149. effect: Effect.fn(function* (ctx) {
  150. yield* ctx.integration.transform((draft) => {
  151. draft.method.update(browser)
  152. draft.method.update(headless)
  153. })
  154. yield* ctx.catalog.transform(
  155. Effect.fn(function* (evt) {
  156. for (const item of evt.provider.list()) {
  157. if (item.provider.api.type !== "aisdk") continue
  158. if (item.provider.api.package !== "@ai-sdk/openai") continue
  159. if (!item.models.has(ModelV2.ID.make("gpt-5-chat-latest"))) continue
  160. evt.model.update(item.provider.id, ModelV2.ID.make("gpt-5-chat-latest"), (model) => {
  161. // OpenAIPlugin sends OpenAI models through Responses; this alias is a
  162. // chat-completions-only model, so hide it only from OpenAI's catalog.
  163. model.enabled = false
  164. })
  165. }
  166. }),
  167. )
  168. yield* ctx.aisdk.sdk(
  169. Effect.fn(function* (evt) {
  170. if (evt.package !== "@ai-sdk/openai") return
  171. const mod = yield* Effect.promise(() => import("@ai-sdk/openai"))
  172. evt.sdk = mod.createOpenAI(evt.options)
  173. }),
  174. )
  175. yield* ctx.aisdk.language(
  176. Effect.fn(function* (evt) {
  177. if (evt.model.providerID !== ProviderV2.ID.openai) return
  178. evt.language = evt.sdk.responses(evt.model.api.id)
  179. }),
  180. )
  181. }),
  182. } satisfies PluginInternal.Plugin<PluginInternal.Requirements | Scope.Scope>)
  183. function headers(contentType: string) {
  184. return { "Content-Type": contentType, "User-Agent": `opencode/${InstallationVersion}` }
  185. }
  186. function exchange(code: string, redirect: string, pkce: Pkce) {
  187. return request<TokenResponse>(`${issuer}/oauth/token`, {
  188. method: "POST",
  189. headers: headers("application/x-www-form-urlencoded"),
  190. body: new URLSearchParams({
  191. grant_type: "authorization_code",
  192. code,
  193. redirect_uri: redirect,
  194. client_id: clientID,
  195. code_verifier: pkce.verifier,
  196. }).toString(),
  197. })
  198. }
  199. function refresh(methodID: Integration.MethodID, value: Pick<Credential.OAuth, "refresh" | "metadata">) {
  200. return request<TokenResponse>(`${issuer}/oauth/token`, {
  201. method: "POST",
  202. headers: headers("application/x-www-form-urlencoded"),
  203. body: new URLSearchParams({
  204. grant_type: "refresh_token",
  205. refresh_token: value.refresh,
  206. client_id: clientID,
  207. }).toString(),
  208. }).pipe(
  209. Effect.map((tokens) => {
  210. const next = credential(methodID, tokens)
  211. return Credential.OAuth.make({ ...next, metadata: next.metadata ?? value.metadata })
  212. }),
  213. )
  214. }
  215. function request<A>(url: string, init: RequestInit) {
  216. return Effect.tryPromise({
  217. try: async (signal) => {
  218. const response = await fetch(url, { ...init, signal })
  219. if (!response.ok) throw new Error(`Request failed: ${response.status}`)
  220. return response.json() as Promise<A>
  221. },
  222. catch: (cause) => cause,
  223. })
  224. }
  225. function credential(methodID: Integration.MethodID, tokens: TokenResponse) {
  226. const accountID = extractAccountID(tokens)
  227. return Credential.OAuth.make({
  228. type: "oauth",
  229. methodID,
  230. refresh: tokens.refresh_token,
  231. access: tokens.access_token,
  232. expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
  233. metadata: accountID ? { accountID } : undefined,
  234. })
  235. }
  236. async function generatePKCE(): Promise<Pkce> {
  237. const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
  238. const verifier = Array.from(crypto.getRandomValues(new Uint8Array(43)), (byte) => chars[byte % chars.length]).join("")
  239. const challenge = base64UrlEncode(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)))
  240. return { verifier, challenge }
  241. }
  242. function base64UrlEncode(buffer: ArrayBuffer) {
  243. return Buffer.from(buffer).toString("base64url")
  244. }
  245. function authorizeURL(redirect: string, pkce: Pkce, state: string) {
  246. return `${issuer}/oauth/authorize?${new URLSearchParams({
  247. response_type: "code",
  248. client_id: clientID,
  249. redirect_uri: redirect,
  250. scope: "openid profile email offline_access",
  251. code_challenge: pkce.challenge,
  252. code_challenge_method: "S256",
  253. id_token_add_organizations: "true",
  254. codex_cli_simplified_flow: "true",
  255. state,
  256. originator: "opencode",
  257. })}`
  258. }
  259. function extractAccountID(tokens: TokenResponse) {
  260. return claim(tokens.id_token) ?? claim(tokens.access_token)
  261. }
  262. function claim(token: string) {
  263. const part = token.split(".")[1]
  264. if (!part) return
  265. try {
  266. const claims = JSON.parse(Buffer.from(part, "base64url").toString()) as Claims
  267. return (
  268. claims.chatgpt_account_id ??
  269. claims["https://api.openai.com/auth"]?.chatgpt_account_id ??
  270. claims.organizations?.[0]?.id
  271. )
  272. } catch {
  273. return
  274. }
  275. }