auth.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { Auth } from "../../auth"
  2. import { cmd } from "./cmd"
  3. import * as prompts from "@clack/prompts"
  4. import { UI } from "../ui"
  5. import { ModelsDev } from "../../provider/models"
  6. import { map, pipe, sortBy, values } from "remeda"
  7. import path from "path"
  8. import os from "os"
  9. import { Global } from "../../global"
  10. import { Plugin } from "../../plugin"
  11. import { Instance } from "../../project/instance"
  12. export const AuthCommand = cmd({
  13. command: "auth",
  14. describe: "manage credentials",
  15. builder: (yargs) =>
  16. yargs.command(AuthLoginCommand).command(AuthLogoutCommand).command(AuthListCommand).demandCommand(),
  17. async handler() {},
  18. })
  19. export const AuthListCommand = cmd({
  20. command: "list",
  21. aliases: ["ls"],
  22. describe: "list providers",
  23. async handler() {
  24. UI.empty()
  25. const authPath = path.join(Global.Path.data, "auth.json")
  26. const homedir = os.homedir()
  27. const displayPath = authPath.startsWith(homedir) ? authPath.replace(homedir, "~") : authPath
  28. prompts.intro(`Credentials ${UI.Style.TEXT_DIM}${displayPath}`)
  29. const results = await Auth.all().then((x) => Object.entries(x))
  30. const database = await ModelsDev.get()
  31. for (const [providerID, result] of results) {
  32. const name = database[providerID]?.name || providerID
  33. prompts.log.info(`${name} ${UI.Style.TEXT_DIM}${result.type}`)
  34. }
  35. prompts.outro(`${results.length} credentials`)
  36. // Environment variables section
  37. const activeEnvVars: Array<{ provider: string; envVar: string }> = []
  38. for (const [providerID, provider] of Object.entries(database)) {
  39. for (const envVar of provider.env) {
  40. if (process.env[envVar]) {
  41. activeEnvVars.push({
  42. provider: provider.name || providerID,
  43. envVar,
  44. })
  45. }
  46. }
  47. }
  48. if (activeEnvVars.length > 0) {
  49. UI.empty()
  50. prompts.intro("Environment")
  51. for (const { provider, envVar } of activeEnvVars) {
  52. prompts.log.info(`${provider} ${UI.Style.TEXT_DIM}${envVar}`)
  53. }
  54. prompts.outro(`${activeEnvVars.length} environment variable` + (activeEnvVars.length === 1 ? "" : "s"))
  55. }
  56. },
  57. })
  58. export const AuthLoginCommand = cmd({
  59. command: "login [url]",
  60. describe: "log in to a provider",
  61. builder: (yargs) =>
  62. yargs.positional("url", {
  63. describe: "opencode auth provider",
  64. type: "string",
  65. }),
  66. async handler(args) {
  67. await Instance.provide({
  68. directory: process.cwd(),
  69. async fn() {
  70. UI.empty()
  71. prompts.intro("Add credential")
  72. if (args.url) {
  73. const wellknown = await fetch(`${args.url}/.well-known/opencode`).then((x) => x.json() as any)
  74. prompts.log.info(`Running \`${wellknown.auth.command.join(" ")}\``)
  75. const proc = Bun.spawn({
  76. cmd: wellknown.auth.command,
  77. stdout: "pipe",
  78. })
  79. const exit = await proc.exited
  80. if (exit !== 0) {
  81. prompts.log.error("Failed")
  82. prompts.outro("Done")
  83. return
  84. }
  85. const token = await new Response(proc.stdout).text()
  86. await Auth.set(args.url, {
  87. type: "wellknown",
  88. key: wellknown.auth.env,
  89. token: token.trim(),
  90. })
  91. prompts.log.success("Logged into " + args.url)
  92. prompts.outro("Done")
  93. return
  94. }
  95. await ModelsDev.refresh().catch(() => {})
  96. const providers = await ModelsDev.get()
  97. const priority: Record<string, number> = {
  98. opencode: 0,
  99. anthropic: 1,
  100. "github-copilot": 2,
  101. openai: 3,
  102. google: 4,
  103. openrouter: 5,
  104. vercel: 6,
  105. }
  106. let provider = await prompts.autocomplete({
  107. message: "Select provider",
  108. maxItems: 8,
  109. options: [
  110. ...pipe(
  111. providers,
  112. values(),
  113. sortBy(
  114. (x) => priority[x.id] ?? 99,
  115. (x) => x.name ?? x.id,
  116. ),
  117. map((x) => ({
  118. label: x.name,
  119. value: x.id,
  120. hint: priority[x.id] <= 1 ? "recommended" : undefined,
  121. })),
  122. ),
  123. {
  124. value: "other",
  125. label: "Other",
  126. },
  127. ],
  128. })
  129. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  130. const plugin = await Plugin.list().then((x) => x.find((x) => x.auth?.provider === provider))
  131. if (plugin && plugin.auth) {
  132. let index = 0
  133. if (plugin.auth.methods.length > 1) {
  134. const method = await prompts.select({
  135. message: "Login method",
  136. options: [
  137. ...plugin.auth.methods.map((x, index) => ({
  138. label: x.label,
  139. value: index.toString(),
  140. })),
  141. ],
  142. })
  143. if (prompts.isCancel(method)) throw new UI.CancelledError()
  144. index = parseInt(method)
  145. }
  146. const method = plugin.auth.methods[index]
  147. // Handle prompts for all auth types
  148. await new Promise((resolve) => setTimeout(resolve, 10))
  149. const inputs: Record<string, string> = {}
  150. if (method.prompts) {
  151. for (const prompt of method.prompts) {
  152. if (prompt.condition && !prompt.condition(inputs)) {
  153. continue
  154. }
  155. if (prompt.type === "select") {
  156. const value = await prompts.select({
  157. message: prompt.message,
  158. options: prompt.options,
  159. })
  160. if (prompts.isCancel(value)) throw new UI.CancelledError()
  161. inputs[prompt.key] = value
  162. } else {
  163. const value = await prompts.text({
  164. message: prompt.message,
  165. placeholder: prompt.placeholder,
  166. validate: prompt.validate ? (v) => prompt.validate!(v ?? "") : undefined,
  167. })
  168. if (prompts.isCancel(value)) throw new UI.CancelledError()
  169. inputs[prompt.key] = value
  170. }
  171. }
  172. }
  173. if (method.type === "oauth") {
  174. const authorize = await method.authorize(inputs)
  175. if (authorize.url) {
  176. prompts.log.info("Go to: " + authorize.url)
  177. }
  178. if (authorize.method === "auto") {
  179. if (authorize.instructions) {
  180. prompts.log.info(authorize.instructions)
  181. }
  182. const spinner = prompts.spinner()
  183. spinner.start("Waiting for authorization...")
  184. const result = await authorize.callback()
  185. if (result.type === "failed") {
  186. spinner.stop("Failed to authorize", 1)
  187. }
  188. if (result.type === "success") {
  189. const saveProvider = result.provider ?? provider
  190. if ("refresh" in result) {
  191. const { type: _, provider: __, refresh, access, expires, ...extraFields } = result
  192. await Auth.set(saveProvider, {
  193. type: "oauth",
  194. refresh,
  195. access,
  196. expires,
  197. ...extraFields,
  198. })
  199. }
  200. if ("key" in result) {
  201. await Auth.set(saveProvider, {
  202. type: "api",
  203. key: result.key,
  204. })
  205. }
  206. spinner.stop("Login successful")
  207. }
  208. }
  209. if (authorize.method === "code") {
  210. const code = await prompts.text({
  211. message: "Paste the authorization code here: ",
  212. validate: (x) => (x && x.length > 0 ? undefined : "Required"),
  213. })
  214. if (prompts.isCancel(code)) throw new UI.CancelledError()
  215. const result = await authorize.callback(code)
  216. if (result.type === "failed") {
  217. prompts.log.error("Failed to authorize")
  218. }
  219. if (result.type === "success") {
  220. const saveProvider = result.provider ?? provider
  221. if ("refresh" in result) {
  222. const { type: _, provider: __, refresh, access, expires, ...extraFields } = result
  223. await Auth.set(saveProvider, {
  224. type: "oauth",
  225. refresh,
  226. access,
  227. expires,
  228. ...extraFields,
  229. })
  230. }
  231. if ("key" in result) {
  232. await Auth.set(saveProvider, {
  233. type: "api",
  234. key: result.key,
  235. })
  236. }
  237. prompts.log.success("Login successful")
  238. }
  239. }
  240. prompts.outro("Done")
  241. return
  242. }
  243. if (method.type === "api") {
  244. if (method.authorize) {
  245. const result = await method.authorize(inputs)
  246. if (result.type === "failed") {
  247. prompts.log.error("Failed to authorize")
  248. }
  249. if (result.type === "success") {
  250. const saveProvider = result.provider ?? provider
  251. await Auth.set(saveProvider, {
  252. type: "api",
  253. key: result.key,
  254. })
  255. prompts.log.success("Login successful")
  256. }
  257. prompts.outro("Done")
  258. return
  259. }
  260. }
  261. }
  262. if (provider === "other") {
  263. provider = await prompts.text({
  264. message: "Enter provider id",
  265. validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
  266. })
  267. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  268. provider = provider.replace(/^@ai-sdk\//, "")
  269. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  270. prompts.log.warn(
  271. `This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
  272. )
  273. }
  274. if (provider === "amazon-bedrock") {
  275. prompts.log.info(
  276. "Amazon bedrock can be configured with standard AWS environment variables like AWS_BEARER_TOKEN_BEDROCK, AWS_PROFILE or AWS_ACCESS_KEY_ID",
  277. )
  278. prompts.outro("Done")
  279. return
  280. }
  281. if (provider === "opencode") {
  282. prompts.log.info("Create an api key at https://opencode.ai/auth")
  283. }
  284. if (provider === "vercel") {
  285. prompts.log.info("You can create an api key at https://vercel.link/ai-gateway-token")
  286. }
  287. const key = await prompts.password({
  288. message: "Enter your API key",
  289. validate: (x) => (x && x.length > 0 ? undefined : "Required"),
  290. })
  291. if (prompts.isCancel(key)) throw new UI.CancelledError()
  292. await Auth.set(provider, {
  293. type: "api",
  294. key,
  295. })
  296. prompts.outro("Done")
  297. },
  298. })
  299. },
  300. })
  301. export const AuthLogoutCommand = cmd({
  302. command: "logout",
  303. describe: "log out from a configured provider",
  304. async handler() {
  305. UI.empty()
  306. const credentials = await Auth.all().then((x) => Object.entries(x))
  307. prompts.intro("Remove credential")
  308. if (credentials.length === 0) {
  309. prompts.log.error("No credentials found")
  310. return
  311. }
  312. const database = await ModelsDev.get()
  313. const providerID = await prompts.select({
  314. message: "Select provider",
  315. options: credentials.map(([key, value]) => ({
  316. label: (database[key]?.name || key) + UI.Style.TEXT_DIM + " (" + value.type + ")",
  317. value: key,
  318. })),
  319. })
  320. if (prompts.isCancel(providerID)) throw new UI.CancelledError()
  321. await Auth.remove(providerID)
  322. prompts.outro("Logout successful")
  323. },
  324. })