index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 file = Bun.file(filepath)
  33. return file
  34. .json()
  35. .catch(() => ({}))
  36. .then((x) => x[providerID] as Info | undefined)
  37. }
  38. export async function all(): Promise<Record<string, Info>> {
  39. const file = Bun.file(filepath)
  40. return file.json().catch(() => ({}))
  41. }
  42. export async function set(key: string, info: Info) {
  43. const file = Bun.file(filepath)
  44. const data = await all()
  45. await Bun.write(file, JSON.stringify({ ...data, [key]: info }, null, 2))
  46. await fs.chmod(file.name!, 0o600)
  47. }
  48. export async function remove(key: string) {
  49. const file = Bun.file(filepath)
  50. const data = await all()
  51. delete data[key]
  52. await Bun.write(file, JSON.stringify(data, null, 2))
  53. await fs.chmod(file.name!, 0o600)
  54. }
  55. }