index.ts 1.8 KB

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