local-runtime-auth-context.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import fs from 'node:fs';
  2. import path from 'node:path';
  3. import { retryWindowsFileSystemOperation } from '@mavis/shared';
  4. export const LOCAL_RUNTIME_AUTH_CONTEXT_FILE = 'local-runtime.auth.json';
  5. export interface LocalRuntimeAuthContextSnapshot {
  6. accessToken?: string;
  7. realUserID?: string;
  8. userEmail?: string;
  9. userName?: string;
  10. subUserName?: string;
  11. }
  12. interface PersistedLocalRuntimeAuthContext {
  13. version: 1;
  14. updatedAtMs: number;
  15. auth: LocalRuntimeAuthContextSnapshot;
  16. }
  17. function readOptionalString(value: unknown): string | undefined {
  18. return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
  19. }
  20. export function normalizeLocalRuntimeAuthContext(
  21. data: Record<string, unknown> | LocalRuntimeAuthContextSnapshot | undefined,
  22. ): LocalRuntimeAuthContextSnapshot {
  23. if (!data) return {};
  24. return {
  25. ...(readOptionalString(data.accessToken)
  26. ? { accessToken: readOptionalString(data.accessToken) }
  27. : {}),
  28. ...(readOptionalString(data.realUserID)
  29. ? { realUserID: readOptionalString(data.realUserID) }
  30. : {}),
  31. ...(readOptionalString(data.userEmail)
  32. ? { userEmail: readOptionalString(data.userEmail) }
  33. : {}),
  34. ...(readOptionalString(data.userName) ? { userName: readOptionalString(data.userName) } : {}),
  35. ...(readOptionalString(data.subUserName)
  36. ? { subUserName: readOptionalString(data.subUserName) }
  37. : {}),
  38. };
  39. }
  40. export function resolveLocalRuntimeAuthContextPath(dataDir: string): string {
  41. return path.join(dataDir, LOCAL_RUNTIME_AUTH_CONTEXT_FILE);
  42. }
  43. export function readLocalRuntimeAuthContext(
  44. dataDir: string,
  45. ): LocalRuntimeAuthContextSnapshot | undefined {
  46. try {
  47. const raw = fs.readFileSync(resolveLocalRuntimeAuthContextPath(dataDir), 'utf-8');
  48. const parsed = JSON.parse(raw) as Partial<PersistedLocalRuntimeAuthContext>;
  49. if (parsed.version !== 1 || !parsed.auth || typeof parsed.auth !== 'object') return undefined;
  50. const auth = normalizeLocalRuntimeAuthContext(parsed.auth);
  51. return auth.accessToken ? auth : undefined;
  52. } catch {
  53. return undefined;
  54. }
  55. }
  56. export function writeLocalRuntimeAuthContext(
  57. dataDir: string,
  58. data: Record<string, unknown> | LocalRuntimeAuthContextSnapshot,
  59. options: { retryWindowsFileSystem?: boolean } = {},
  60. ): { path: string; written: boolean } {
  61. const filePath = resolveLocalRuntimeAuthContextPath(dataDir);
  62. const auth = normalizeLocalRuntimeAuthContext(data);
  63. if (!auth.accessToken) {
  64. clearLocalRuntimeAuthContextFile(dataDir);
  65. return { path: filePath, written: false };
  66. }
  67. fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
  68. const payload: PersistedLocalRuntimeAuthContext = {
  69. version: 1,
  70. updatedAtMs: Date.now(),
  71. auth,
  72. };
  73. const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
  74. fs.writeFileSync(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, {
  75. encoding: 'utf-8',
  76. mode: 0o600,
  77. });
  78. if (options.retryWindowsFileSystem) {
  79. retryWindowsFileSystemOperation(() => fs.renameSync(tmpPath, filePath));
  80. retryWindowsFileSystemOperation(() => fs.chmodSync(filePath, 0o600));
  81. } else {
  82. fs.renameSync(tmpPath, filePath);
  83. fs.chmodSync(filePath, 0o600);
  84. }
  85. return { path: filePath, written: true };
  86. }
  87. export function clearLocalRuntimeAuthContextFile(dataDir: string): void {
  88. try {
  89. fs.rmSync(resolveLocalRuntimeAuthContextPath(dataDir), { force: true });
  90. } catch {
  91. // Best-effort cleanup. Callers should not fail logout/runtime shutdown just
  92. // because an auth context file was already gone or temporarily locked.
  93. }
  94. }