identity-storage.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { createHash } from 'node:crypto';
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import { retryWindowsFileSystemOperation } from '@mavis/shared';
  5. import {
  6. normalizeLocalRuntimeAuthContext,
  7. type LocalRuntimeAuthContextSnapshot,
  8. } from '@mavis/config';
  9. import type { CliAuthScope } from './types.js';
  10. const CLI_ACCOUNT_IDENTITY_FILE = 'account-identity.json';
  11. interface CliAccountIdentityRecord {
  12. readonly version: 1;
  13. readonly region: CliAuthScope['region'];
  14. readonly buildEnv: CliAuthScope['buildEnv'];
  15. readonly status: 'verified' | 'rejected';
  16. readonly tokenFingerprint: string;
  17. readonly realUserID?: string;
  18. readonly userEmail?: string;
  19. readonly userName?: string;
  20. readonly subUserName?: string;
  21. readonly updatedAtMs: number;
  22. }
  23. export interface VerifiedCliAccountIdentity {
  24. readonly realUserID: string;
  25. readonly userEmail?: string;
  26. readonly userName?: string;
  27. readonly subUserName?: string;
  28. readonly verifiedAtMs: number;
  29. }
  30. export function resolveCliAccountIdentityPath(dataDir: string, scope: CliAuthScope): string {
  31. return path.join(dataDir, 'cli-auth', scope.buildEnv, scope.region, CLI_ACCOUNT_IDENTITY_FILE);
  32. }
  33. export function readVerifiedCliAccountIdentity(
  34. dataDir: string,
  35. scope: CliAuthScope,
  36. accessToken: string,
  37. ): VerifiedCliAccountIdentity | undefined {
  38. const record = readCliAccountIdentity(dataDir, scope, accessToken);
  39. const identity = normalizeLocalRuntimeAuthContext(record);
  40. const realUserID = identity.realUserID;
  41. if (record?.status !== 'verified' || !realUserID) return undefined;
  42. return {
  43. realUserID,
  44. ...(identity.userEmail ? { userEmail: identity.userEmail } : {}),
  45. ...(identity.userName ? { userName: identity.userName } : {}),
  46. ...(identity.subUserName ? { subUserName: identity.subUserName } : {}),
  47. verifiedAtMs: record.updatedAtMs,
  48. };
  49. }
  50. export function isCliAccessTokenRejected(
  51. dataDir: string,
  52. scope: CliAuthScope,
  53. accessToken: string,
  54. ): boolean {
  55. return readCliAccountIdentity(dataDir, scope, accessToken)?.status === 'rejected';
  56. }
  57. export function writeVerifiedCliAccountIdentity(
  58. dataDir: string,
  59. scope: CliAuthScope,
  60. accessToken: string,
  61. identityInput: string | LocalRuntimeAuthContextSnapshot,
  62. updatedAtMs = Date.now(),
  63. ): void {
  64. const identity = normalizeLocalRuntimeAuthContext(
  65. typeof identityInput === 'string' ? { realUserID: identityInput } : identityInput,
  66. );
  67. if (!identity.realUserID) throw new Error('MiniMax account identity is missing a user ID.');
  68. writeCliAccountIdentity(dataDir, scope, {
  69. version: 1,
  70. ...scope,
  71. status: 'verified',
  72. tokenFingerprint: fingerprintAccessToken(accessToken),
  73. realUserID: identity.realUserID,
  74. ...(identity.userEmail ? { userEmail: identity.userEmail } : {}),
  75. ...(identity.userName ? { userName: identity.userName } : {}),
  76. ...(identity.subUserName ? { subUserName: identity.subUserName } : {}),
  77. updatedAtMs,
  78. });
  79. }
  80. export function writeRejectedCliAccountIdentity(
  81. dataDir: string,
  82. scope: CliAuthScope,
  83. accessToken: string,
  84. updatedAtMs = Date.now(),
  85. ): void {
  86. writeCliAccountIdentity(dataDir, scope, {
  87. version: 1,
  88. ...scope,
  89. status: 'rejected',
  90. tokenFingerprint: fingerprintAccessToken(accessToken),
  91. updatedAtMs,
  92. });
  93. }
  94. export function clearCliAccountIdentity(dataDir: string, scope: CliAuthScope): void {
  95. fs.rmSync(resolveCliAccountIdentityPath(dataDir, scope), { force: true });
  96. }
  97. function readCliAccountIdentity(
  98. dataDir: string,
  99. scope: CliAuthScope,
  100. accessToken: string,
  101. ): CliAccountIdentityRecord | undefined {
  102. const normalizedToken = accessToken.trim();
  103. if (!normalizedToken) return undefined;
  104. try {
  105. const parsed = JSON.parse(
  106. fs.readFileSync(resolveCliAccountIdentityPath(dataDir, scope), 'utf8'),
  107. ) as Partial<CliAccountIdentityRecord>;
  108. if (
  109. parsed.version !== 1 ||
  110. parsed.region !== scope.region ||
  111. parsed.buildEnv !== scope.buildEnv ||
  112. (parsed.status !== 'verified' && parsed.status !== 'rejected') ||
  113. parsed.tokenFingerprint !== fingerprintAccessToken(normalizedToken) ||
  114. typeof parsed.updatedAtMs !== 'number'
  115. ) {
  116. return undefined;
  117. }
  118. return parsed as CliAccountIdentityRecord;
  119. } catch {
  120. return undefined;
  121. }
  122. }
  123. function writeCliAccountIdentity(
  124. dataDir: string,
  125. scope: CliAuthScope,
  126. record: CliAccountIdentityRecord,
  127. ): void {
  128. const filePath = resolveCliAccountIdentityPath(dataDir, scope);
  129. const directory = path.dirname(filePath);
  130. fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
  131. const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
  132. fs.writeFileSync(temporaryPath, `${JSON.stringify(record, null, 2)}\n`, {
  133. encoding: 'utf8',
  134. mode: 0o600,
  135. });
  136. retryWindowsFileSystemOperation(() => fs.renameSync(temporaryPath, filePath));
  137. retryWindowsFileSystemOperation(() => fs.chmodSync(filePath, 0o600));
  138. }
  139. function fingerprintAccessToken(accessToken: string): string {
  140. return `sha256:${createHash('sha256').update(accessToken.trim()).digest('hex')}`;
  141. }