auth.ts 9.3 KB

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