2
0

index.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import path from "path"
  2. import { Global } from "../global"
  3. import z from "zod"
  4. import { Filesystem } from "../util/filesystem"
  5. export const OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"
  6. export namespace Auth {
  7. export const Oauth = z
  8. .object({
  9. type: z.literal("oauth"),
  10. refresh: z.string(),
  11. access: z.string(),
  12. expires: z.number(),
  13. accountId: z.string().optional(),
  14. enterpriseUrl: z.string().optional(),
  15. })
  16. .meta({ ref: "OAuth" })
  17. export const Api = z
  18. .object({
  19. type: z.literal("api"),
  20. key: z.string(),
  21. })
  22. .meta({ ref: "ApiAuth" })
  23. export const WellKnown = z
  24. .object({
  25. type: z.literal("wellknown"),
  26. key: z.string(),
  27. token: z.string(),
  28. })
  29. .meta({ ref: "WellKnownAuth" })
  30. export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown]).meta({ ref: "Auth" })
  31. export type Info = z.infer<typeof Info>
  32. const filepath = path.join(Global.Path.data, "auth.json")
  33. export async function get(providerID: string) {
  34. const auth = await all()
  35. return auth[providerID]
  36. }
  37. export async function all(): Promise<Record<string, Info>> {
  38. const data = await Filesystem.readJson<Record<string, unknown>>(filepath).catch(() => ({}))
  39. return Object.entries(data).reduce(
  40. (acc, [key, value]) => {
  41. const parsed = Info.safeParse(value)
  42. if (!parsed.success) return acc
  43. acc[key] = parsed.data
  44. return acc
  45. },
  46. {} as Record<string, Info>,
  47. )
  48. }
  49. export async function set(key: string, info: Info) {
  50. const data = await all()
  51. await Filesystem.writeJson(filepath, { ...data, [key]: info }, 0o600)
  52. }
  53. export async function remove(key: string) {
  54. const data = await all()
  55. delete data[key]
  56. await Filesystem.writeJson(filepath, data, 0o600)
  57. }
  58. }