auth.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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(process.cwd(), async () => {
  68. UI.empty()
  69. prompts.intro("Add credential")
  70. if (args.url) {
  71. const wellknown = await fetch(`${args.url}/.well-known/opencode`).then((x) => x.json())
  72. prompts.log.info(`Running \`${wellknown.auth.command.join(" ")}\``)
  73. const proc = Bun.spawn({
  74. cmd: wellknown.auth.command,
  75. stdout: "pipe",
  76. })
  77. const exit = await proc.exited
  78. if (exit !== 0) {
  79. prompts.log.error("Failed")
  80. prompts.outro("Done")
  81. return
  82. }
  83. const token = await new Response(proc.stdout).text()
  84. await Auth.set(args.url, {
  85. type: "wellknown",
  86. key: wellknown.auth.env,
  87. token: token.trim(),
  88. })
  89. prompts.log.success("Logged into " + args.url)
  90. prompts.outro("Done")
  91. return
  92. }
  93. await ModelsDev.refresh().catch(() => {})
  94. const providers = await ModelsDev.get()
  95. const priority: Record<string, number> = {
  96. opencode: 0,
  97. anthropic: 1,
  98. "github-copilot": 2,
  99. openai: 3,
  100. google: 4,
  101. openrouter: 5,
  102. vercel: 6,
  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] <= 1 ? "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. prompts.log.info("Go to: " + authorize.url)
  150. }
  151. if (authorize.method === "auto") {
  152. if (authorize.instructions) {
  153. prompts.log.info(authorize.instructions)
  154. }
  155. const spinner = prompts.spinner()
  156. spinner.start("Waiting for authorization...")
  157. const result = await authorize.callback()
  158. if (result.type === "failed") {
  159. spinner.stop("Failed to authorize", 1)
  160. }
  161. if (result.type === "success") {
  162. if ("refresh" in result) {
  163. await Auth.set(provider, {
  164. type: "oauth",
  165. refresh: result.refresh,
  166. access: result.access,
  167. expires: result.expires,
  168. })
  169. }
  170. if ("key" in result) {
  171. await Auth.set(provider, {
  172. type: "api",
  173. key: result.key,
  174. })
  175. }
  176. spinner.stop("Login successful")
  177. }
  178. }
  179. if (authorize.method === "code") {
  180. const code = await prompts.text({
  181. message: "Paste the authorization code here: ",
  182. validate: (x) => (x && x.length > 0 ? undefined : "Required"),
  183. })
  184. if (prompts.isCancel(code)) throw new UI.CancelledError()
  185. const result = await authorize.callback(code)
  186. if (result.type === "failed") {
  187. prompts.log.error("Failed to authorize")
  188. }
  189. if (result.type === "success") {
  190. if ("refresh" in result) {
  191. await Auth.set(provider, {
  192. type: "oauth",
  193. refresh: result.refresh,
  194. access: result.access,
  195. expires: result.expires,
  196. })
  197. }
  198. if ("key" in result) {
  199. await Auth.set(provider, {
  200. type: "api",
  201. key: result.key,
  202. })
  203. }
  204. prompts.log.success("Login successful")
  205. }
  206. }
  207. prompts.outro("Done")
  208. return
  209. }
  210. }
  211. if (provider === "other") {
  212. provider = await prompts.text({
  213. message: "Enter provider id",
  214. validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
  215. })
  216. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  217. provider = provider.replace(/^@ai-sdk\//, "")
  218. if (prompts.isCancel(provider)) throw new UI.CancelledError()
  219. prompts.log.warn(
  220. `This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
  221. )
  222. }
  223. if (provider === "amazon-bedrock") {
  224. prompts.log.info(
  225. "Amazon bedrock can be configured with standard AWS environment variables like AWS_BEARER_TOKEN_BEDROCK, AWS_PROFILE or AWS_ACCESS_KEY_ID",
  226. )
  227. prompts.outro("Done")
  228. return
  229. }
  230. if (provider === "opencode") {
  231. prompts.log.info("Create an api key at https://opencode.ai/auth")
  232. }
  233. if (provider === "vercel") {
  234. prompts.log.info("You can create an api key at https://vercel.link/ai-gateway-token")
  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. })