server.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
  2. import type { ServerConnection } from "@/context/server"
  3. import { decode64 } from "@/utils/base64"
  4. export function authTokenFromCredentials(input: { username?: string; password: string }) {
  5. return btoa(`${input.username ?? "opencode"}:${input.password}`)
  6. }
  7. export function authFromToken(token: string | null) {
  8. const decoded = decode64(token ?? undefined)
  9. if (!decoded) return
  10. const separator = decoded.indexOf(":")
  11. if (separator === -1) return
  12. return {
  13. username: decoded.slice(0, separator) || "opencode",
  14. password: decoded.slice(separator + 1),
  15. }
  16. }
  17. export function createSdkForServer({
  18. server,
  19. ...config
  20. }: Omit<NonNullable<Parameters<typeof createOpencodeClient>[0]>, "baseUrl"> & {
  21. server: ServerConnection.HttpBase
  22. }) {
  23. const auth = (() => {
  24. if (!server.password) return
  25. return {
  26. Authorization: `Basic ${authTokenFromCredentials({ username: server.username, password: server.password })}`,
  27. }
  28. })()
  29. return createOpencodeClient({
  30. ...config,
  31. headers: {
  32. ...(config.headers instanceof Headers ? Object.fromEntries(config.headers.entries()) : config.headers),
  33. ...auth,
  34. },
  35. baseUrl: server.url,
  36. })
  37. }