index.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. })
  13. .openapi({ ref: "OAuth" })
  14. export const Api = z
  15. .object({
  16. type: z.literal("api"),
  17. key: z.string(),
  18. })
  19. .openapi({ ref: "ApiAuth" })
  20. export const WellKnown = z
  21. .object({
  22. type: z.literal("wellknown"),
  23. key: z.string(),
  24. token: z.string(),
  25. })
  26. .openapi({ ref: "WellKnownAuth" })
  27. export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown]).openapi({ ref: "Auth" })
  28. export type Info = z.infer<typeof Info>
  29. const filepath = path.join(Global.Path.data, "auth.json")
  30. export async function get(providerID: string) {
  31. const file = Bun.file(filepath)
  32. return file
  33. .json()
  34. .catch(() => ({}))
  35. .then((x) => x[providerID] as Info | undefined)
  36. }
  37. export async function all(): Promise<Record<string, Info>> {
  38. const file = Bun.file(filepath)
  39. return file.json().catch(() => ({}))
  40. }
  41. export async function set(key: string, info: Info) {
  42. const file = Bun.file(filepath)
  43. const data = await all()
  44. await Bun.write(file, JSON.stringify({ ...data, [key]: info }, null, 2))
  45. await fs.chmod(file.name!, 0o600)
  46. }
  47. export async function remove(key: string) {
  48. const file = Bun.file(filepath)
  49. const data = await all()
  50. delete data[key]
  51. await Bun.write(file, JSON.stringify(data, null, 2))
  52. await fs.chmod(file.name!, 0o600)
  53. }
  54. }