index.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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.object({
  7. type: z.literal("oauth"),
  8. refresh: z.string(),
  9. expires: z.number(),
  10. })
  11. export const Api = z.object({
  12. type: z.literal("api"),
  13. key: z.string(),
  14. })
  15. export const Info = z.discriminatedUnion("type", [Oauth, Api])
  16. export type Info = z.infer<typeof Info>
  17. const filepath = path.join(Global.Path.data, "auth.json")
  18. export async function get(providerID: string) {
  19. const file = Bun.file(filepath)
  20. return file
  21. .json()
  22. .catch(() => ({}))
  23. .then((x) => x[providerID] as Info | undefined)
  24. }
  25. export async function all(): Promise<Record<string, Info>> {
  26. const file = Bun.file(filepath)
  27. return file.json().catch(() => ({}))
  28. }
  29. export async function set(key: string, info: Info) {
  30. const file = Bun.file(filepath)
  31. const data = await all()
  32. await Bun.write(file, JSON.stringify({ ...data, [key]: info }, null, 2))
  33. await fs.chmod(file.name!, 0o600)
  34. }
  35. export async function remove(key: string) {
  36. const file = Bun.file(filepath)
  37. const data = await all()
  38. delete data[key]
  39. await Bun.write(file, JSON.stringify(data, null, 2))
  40. await fs.chmod(file.name!, 0o600)
  41. }
  42. }