state-store.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import { readFile } from 'node:fs/promises';
  2. import { atomicWritePrivateFile } from './fs/atomic-write.js';
  3. import type { AuthBuildEnv, AuthRegion } from './contracts.js';
  4. import type { PersistedCredentialStoreKind } from './credential-store/types.js';
  5. export const AUTH_STATE_SCHEMA_VERSION = 2 as const;
  6. export const AUTH_STATE_MIN_SUPPORTED_SCHEMA_VERSION = 1 as const;
  7. export type AuthStatus =
  8. | 'anonymous'
  9. | 'authorizing'
  10. | 'authenticated'
  11. | 'refreshing'
  12. | 'scope_upgrade_required'
  13. | 'logging_out'
  14. | 'logout_pending'
  15. | 'expired'
  16. | 'error';
  17. export interface AuthState {
  18. schemaVersion: typeof AUTH_STATE_SCHEMA_VERSION | typeof AUTH_STATE_MIN_SUPPORTED_SCHEMA_VERSION;
  19. status: AuthStatus;
  20. storeKind: PersistedCredentialStoreKind;
  21. clientId: 'mcode-public';
  22. scopes: string[];
  23. audience: 'agent-backend';
  24. buildEnv?: AuthBuildEnv;
  25. region?: AuthRegion;
  26. expiresAtMs?: number;
  27. generation: number;
  28. authorization?: {
  29. leaseId: string;
  30. leaseExpiresAtMs: number;
  31. userCode?: string;
  32. verificationUri?: string;
  33. verificationUriComplete?: string;
  34. };
  35. }
  36. const SENSITIVE_KEY_PATTERN =
  37. /access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;
  38. function assertNoSensitiveKeys(value: unknown): void {
  39. if (typeof value !== 'object' || value === null) return;
  40. for (const [key, child] of Object.entries(value)) {
  41. if (SENSITIVE_KEY_PATTERN.test(key)) {
  42. throw new TypeError('Sensitive OAuth fields cannot be persisted in auth-state.json.');
  43. }
  44. assertNoSensitiveKeys(child);
  45. }
  46. }
  47. function parseState(value: unknown): AuthState {
  48. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  49. throw new TypeError('Invalid OAuth state.');
  50. }
  51. const state = value as Record<string, unknown>;
  52. const valid =
  53. typeof state.schemaVersion === 'number' &&
  54. Number.isInteger(state.schemaVersion) &&
  55. state.schemaVersion >= AUTH_STATE_MIN_SUPPORTED_SCHEMA_VERSION &&
  56. state.schemaVersion <= AUTH_STATE_SCHEMA_VERSION &&
  57. [
  58. 'anonymous',
  59. 'authorizing',
  60. 'authenticated',
  61. 'refreshing',
  62. 'scope_upgrade_required',
  63. 'logging_out',
  64. 'logout_pending',
  65. 'expired',
  66. 'error',
  67. ].includes(state.status as string) &&
  68. ((state.schemaVersion === 1 &&
  69. (state.storeKind === 'os-keyring' || state.storeKind === 'file')) ||
  70. (state.schemaVersion === AUTH_STATE_SCHEMA_VERSION && state.storeKind === 'file')) &&
  71. state.clientId === 'mcode-public' &&
  72. Array.isArray(state.scopes) &&
  73. state.scopes.every((scope) => typeof scope === 'string') &&
  74. state.audience === 'agent-backend' &&
  75. isOptionalAuthScope(state.buildEnv, state.region) &&
  76. (state.expiresAtMs === undefined ||
  77. (typeof state.expiresAtMs === 'number' && Number.isFinite(state.expiresAtMs))) &&
  78. Number.isSafeInteger(state.generation) &&
  79. (state.generation as number) >= 0 &&
  80. (state.authorization === undefined || isAuthorizationLease(state.authorization));
  81. if (!valid) throw new TypeError('Invalid OAuth state.');
  82. assertNoSensitiveKeys(state);
  83. return state as unknown as AuthState;
  84. }
  85. function isOptionalAuthScope(buildEnv: unknown, region: unknown): boolean {
  86. if (buildEnv === undefined && region === undefined) return true;
  87. return (
  88. (buildEnv === 'dev' || buildEnv === 'test' || buildEnv === 'staging' || buildEnv === 'prod') &&
  89. (region === 'cn' || region === 'en')
  90. );
  91. }
  92. function isAuthorizationLease(value: unknown): boolean {
  93. if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
  94. const lease = value as Record<string, unknown>;
  95. return (
  96. typeof lease.leaseId === 'string' &&
  97. lease.leaseId.length > 0 &&
  98. typeof lease.leaseExpiresAtMs === 'number' &&
  99. Number.isFinite(lease.leaseExpiresAtMs) &&
  100. isOptionalString(lease.userCode) &&
  101. isOptionalString(lease.verificationUri) &&
  102. isOptionalString(lease.verificationUriComplete)
  103. );
  104. }
  105. function isOptionalString(value: unknown): boolean {
  106. return value === undefined || typeof value === 'string';
  107. }
  108. export class AuthStateStore {
  109. constructor(private readonly path: string) {}
  110. async read(): Promise<AuthState | null> {
  111. let raw: string;
  112. try {
  113. raw = await readFile(this.path, 'utf8');
  114. } catch (error) {
  115. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
  116. throw error;
  117. }
  118. try {
  119. return parseState(JSON.parse(raw));
  120. } catch (error) {
  121. if (error instanceof TypeError) throw error;
  122. throw new TypeError('Invalid OAuth state.');
  123. }
  124. }
  125. async write(state: AuthState): Promise<void> {
  126. const validated = parseState(state);
  127. await atomicWritePrivateFile(this.path, `${JSON.stringify(validated, null, 2)}\n`);
  128. }
  129. }