auth-core.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. import { randomUUID } from 'node:crypto';
  2. import { watchFile, unwatchFile } from 'node:fs';
  3. import {
  4. MCODE_OAUTH_AUDIENCE,
  5. MCODE_OAUTH_CLIENT_ID,
  6. MCODE_OAUTH_SCOPES,
  7. type AccessTokenLease,
  8. type UnauthorizedContext,
  9. } from './contracts.js';
  10. import { CrossProcessAuthLock } from './cross-process-lock.js';
  11. import type { CredentialStore, StoredCredential } from './credential-store/types.js';
  12. import type { AuthNamespace } from './namespace.js';
  13. import {
  14. OAuthProtocolError,
  15. type DeviceAuthorization,
  16. type OAuthClient,
  17. type OAuthTokenGrant,
  18. } from './oauth-client.js';
  19. import {
  20. AUTH_STATE_SCHEMA_VERSION,
  21. AuthStateStore,
  22. type AuthState,
  23. type AuthStatus,
  24. } from './state-store.js';
  25. const DEFAULT_AUTHORIZATION_LEASE_MS = 10 * 60 * 1_000;
  26. const DEFAULT_STATE_POLL_INTERVAL_MS = 250;
  27. export class AuthRequiredError extends Error {
  28. readonly code = 'AUTH_REQUIRED';
  29. constructor(options?: ErrorOptions) {
  30. super('MCode authentication is required.', options);
  31. this.name = 'AuthRequiredError';
  32. }
  33. }
  34. export class AuthLoginCancelledError extends Error {
  35. readonly code = 'AUTH_LOGIN_CANCELLED';
  36. constructor() {
  37. super('MCode OAuth device authorization was cancelled.');
  38. this.name = 'AuthLoginCancelledError';
  39. }
  40. }
  41. /** Rejects only the stale request; the current shared account remains signed in. */
  42. export class AuthSessionChangedError extends Error {
  43. readonly code = 'AUTH_SESSION_CHANGED';
  44. constructor() {
  45. super('The login changed while this request was in progress.');
  46. this.name = 'AuthSessionChangedError';
  47. }
  48. }
  49. export function assertSameLoginEpoch(
  50. expected: string | undefined,
  51. current: string | undefined,
  52. ): void {
  53. if (!expected || expected !== current) throw new AuthSessionChangedError();
  54. }
  55. export class AuthScopeUpgradeRequiredError extends Error {
  56. readonly code = 'AUTH_SCOPE_UPGRADE_REQUIRED';
  57. constructor(readonly missingScopes: string[]) {
  58. super('The current MCode authorization does not include the required scope.');
  59. this.name = 'AuthScopeUpgradeRequiredError';
  60. }
  61. }
  62. export class AuthResourceContractMismatchError extends Error {
  63. readonly code = 'AUTH_RESOURCE_CONTRACT_MISMATCH';
  64. constructor() {
  65. super('The stored credential does not match the MCode resource contract.');
  66. this.name = 'AuthResourceContractMismatchError';
  67. }
  68. }
  69. export function requiresInteractiveLogin(error: unknown): boolean {
  70. return (
  71. error instanceof AuthRequiredError ||
  72. error instanceof AuthScopeUpgradeRequiredError ||
  73. error instanceof AuthResourceContractMismatchError
  74. );
  75. }
  76. export class AuthDomainConflictError extends Error {
  77. readonly code = 'AUTH_DOMAIN_CONFLICT';
  78. constructor(
  79. readonly active: Pick<AuthNamespace, 'buildEnv' | 'region'>,
  80. readonly requested: Pick<AuthNamespace, 'buildEnv' | 'region'>,
  81. ) {
  82. super(
  83. `MCode is signed in to ${active.buildEnv}/${active.region}; sign out before using ${requested.buildEnv}/${requested.region}.`,
  84. );
  85. this.name = 'AuthDomainConflictError';
  86. }
  87. }
  88. export interface MCodeOAuthCoreOptions {
  89. namespace: AuthNamespace;
  90. credentialStore: CredentialStore;
  91. oauthClient: OAuthClient;
  92. initialize?: () => Promise<void>;
  93. now?: () => number;
  94. sleep?: (durationMs: number) => Promise<void>;
  95. authorizationLeaseMs?: number;
  96. statePollIntervalMs?: number;
  97. createLeaseId?: () => string;
  98. }
  99. export interface LoginOptions {
  100. onDeviceAuthorization?: (authorization: DeviceAuthorizationPrompt) => void;
  101. }
  102. export interface DeviceAuthorizationPrompt {
  103. userCode: string;
  104. verificationUri: string;
  105. verificationUriComplete?: string;
  106. expiresInSec: number;
  107. }
  108. export interface LoginResult {
  109. status: 'authenticated';
  110. generation: number;
  111. }
  112. export interface LogoutResult {
  113. status: 'anonymous' | 'logout_pending';
  114. generation: number;
  115. }
  116. export interface AccessTokenOptions {
  117. requiredScopes: string[];
  118. minValidityMs: number;
  119. }
  120. export interface AuthStatusSnapshot {
  121. status: AuthStatus;
  122. generation: number;
  123. scopes: string[];
  124. buildEnv?: AuthNamespace['buildEnv'];
  125. region?: AuthNamespace['region'];
  126. expiresAtMs?: number;
  127. }
  128. export class MCodeOAuthCore {
  129. private readonly stateStore: AuthStateStore;
  130. private readonly lock: CrossProcessAuthLock;
  131. private readonly now: () => number;
  132. private readonly sleep: (durationMs: number) => Promise<void>;
  133. private readonly authorizationLeaseMs: number;
  134. private readonly statePollIntervalMs: number;
  135. private readonly createLeaseId: () => string;
  136. private loginPromise: Promise<LoginResult> | undefined;
  137. private loginAbortController: AbortController | undefined;
  138. private initializePromise: Promise<void> | undefined;
  139. constructor(private readonly options: MCodeOAuthCoreOptions) {
  140. this.stateStore = new AuthStateStore(options.namespace.statePath);
  141. this.lock = new CrossProcessAuthLock(options.namespace.lockPath);
  142. this.now = options.now ?? Date.now;
  143. this.sleep =
  144. options.sleep ?? ((durationMs) => new Promise((resolve) => setTimeout(resolve, durationMs)));
  145. this.authorizationLeaseMs = options.authorizationLeaseMs ?? DEFAULT_AUTHORIZATION_LEASE_MS;
  146. this.statePollIntervalMs = options.statePollIntervalMs ?? DEFAULT_STATE_POLL_INTERVAL_MS;
  147. this.createLeaseId = options.createLeaseId ?? randomUUID;
  148. }
  149. async getStatus(): Promise<AuthStatusSnapshot> {
  150. await this.initialize();
  151. const state = await this.stateStore.read();
  152. if (!state) return { status: 'anonymous', generation: 0, scopes: [] };
  153. if (state.status === 'authorizing' || state.status === 'refreshing') {
  154. const recovered = await this.recoverInterruptedCredentialCommit(state);
  155. return toStatusSnapshot(recovered);
  156. }
  157. if (state.status === 'authenticated' || state.status === 'expired') {
  158. const credential = await this.options.credentialStore.get(
  159. this.options.namespace.credentialKey,
  160. );
  161. if (!credential || credential.generation !== state.generation) {
  162. return toStatusSnapshot({ ...state, status: 'error' });
  163. }
  164. try {
  165. assertCredentialContract(credential, [...MCODE_OAUTH_SCOPES]);
  166. } catch (error) {
  167. if (error instanceof AuthScopeUpgradeRequiredError) {
  168. return toStatusSnapshot({
  169. ...authenticatedState(
  170. credential,
  171. this.options.credentialStore.kind,
  172. this.options.namespace,
  173. ),
  174. status: 'scope_upgrade_required',
  175. });
  176. }
  177. if (error instanceof AuthResourceContractMismatchError) {
  178. return toStatusSnapshot({ ...state, status: 'error' });
  179. }
  180. throw error;
  181. }
  182. const current = authenticatedState(
  183. credential,
  184. this.options.credentialStore.kind,
  185. this.options.namespace,
  186. );
  187. if (state.status === 'expired' || credential.expiresAtMs <= this.now()) {
  188. return toStatusSnapshot({ ...current, status: 'expired' });
  189. }
  190. return toStatusSnapshot(current);
  191. }
  192. return toStatusSnapshot(state);
  193. }
  194. login(options: LoginOptions = {}): Promise<LoginResult> {
  195. if (!this.loginPromise) {
  196. const controller = new AbortController();
  197. const promise = this.initialize()
  198. .then(() => this.runLogin(options, controller.signal))
  199. .finally(() => {
  200. if (this.loginPromise !== promise) return;
  201. this.loginPromise = undefined;
  202. this.loginAbortController = undefined;
  203. });
  204. this.loginAbortController = controller;
  205. this.loginPromise = promise;
  206. }
  207. return this.loginPromise;
  208. }
  209. async cancelLogin(): Promise<void> {
  210. const controller = this.loginAbortController;
  211. const promise = this.loginPromise;
  212. if (!controller || !promise) return;
  213. controller.abort();
  214. try {
  215. await promise;
  216. } catch (error) {
  217. if (!(error instanceof AuthLoginCancelledError)) throw error;
  218. }
  219. }
  220. async getAccessToken(options: AccessTokenOptions): Promise<AccessTokenLease> {
  221. await this.initialize();
  222. validateRequestedScopes(options.requiredScopes);
  223. try {
  224. const initial = await this.readUsableCredential(options.requiredScopes);
  225. if (this.satisfiesMinValidity(initial, options.minValidityMs)) {
  226. return toAccessTokenLease(initial.credential);
  227. }
  228. } catch (error) {
  229. if (!(error instanceof AuthRequiredError)) throw error;
  230. // A concurrent writer may have committed credentials before their state.
  231. // Recheck under the domain lock before reporting authentication as missing.
  232. }
  233. return this.lock.withLock(async () => {
  234. const current = await this.readUsableCredential(options.requiredScopes);
  235. if (this.satisfiesMinValidity(current, options.minValidityMs)) {
  236. return toAccessTokenLease(current.credential);
  237. }
  238. return this.refreshCredential(current);
  239. });
  240. }
  241. /**
  242. * Only committed authenticated leases can be reused. A refresh in progress
  243. * must finish under the shared lock; an expired lease must refresh successfully.
  244. */
  245. private satisfiesMinValidity(
  246. current: { state: AuthState; credential: StoredCredential },
  247. minValidityMs: number,
  248. ): boolean {
  249. if (current.state.status !== 'authenticated') return false;
  250. const remainingMs = current.credential.expiresAtMs - this.now();
  251. return remainingMs > 0 && remainingMs >= minValidityMs;
  252. }
  253. async handleUnauthorized(context: UnauthorizedContext): Promise<'retry' | 'logout'> {
  254. await this.initialize();
  255. try {
  256. return await this.lock.withLock(async () => {
  257. const current = await this.readUsableCredential([...MCODE_OAUTH_SCOPES]);
  258. if (context.loginEpoch !== undefined) {
  259. assertSameLoginEpoch(context.loginEpoch, current.credential.loginEpoch);
  260. } else if (current.credential.generation > context.generation) {
  261. // Older callers cannot prove that a newer generation belongs to their login.
  262. throw new AuthSessionChangedError();
  263. }
  264. if (current.credential.generation > context.generation) return 'retry';
  265. if (current.credential.generation < context.generation) return 'logout';
  266. await this.refreshCredential(current, { rejected: true });
  267. return 'retry';
  268. });
  269. } catch (error) {
  270. if (requiresInteractiveLogin(error)) return 'logout';
  271. throw error;
  272. }
  273. }
  274. async logout(options: { revoke: boolean }): Promise<LogoutResult> {
  275. await this.initialize();
  276. return this.lock.withLock(async () => {
  277. const state = await this.stateStore.read();
  278. const credential = await this.options.credentialStore.get(
  279. this.options.namespace.credentialKey,
  280. );
  281. const currentGeneration = Math.max(state?.generation ?? 0, credential?.generation ?? 0);
  282. if (!credential && (!state || state.status === 'anonymous')) {
  283. return { status: 'anonymous', generation: currentGeneration };
  284. }
  285. const logoutGeneration = currentGeneration + 1;
  286. await this.stateStore.write(
  287. baseState(
  288. {
  289. status: 'logging_out',
  290. generation: logoutGeneration,
  291. storeKind: this.options.credentialStore.kind,
  292. },
  293. this.options.namespace,
  294. ),
  295. );
  296. if (options.revoke && credential) {
  297. try {
  298. await this.options.oauthClient.revokeToken(credential.refreshToken);
  299. } catch {
  300. await this.stateStore.write(
  301. baseState(
  302. {
  303. status: 'logout_pending',
  304. generation: logoutGeneration,
  305. storeKind: this.options.credentialStore.kind,
  306. },
  307. this.options.namespace,
  308. ),
  309. );
  310. return { status: 'logout_pending', generation: logoutGeneration };
  311. }
  312. }
  313. await this.options.credentialStore.delete(this.options.namespace.credentialKey);
  314. await this.stateStore.write(
  315. baseState(
  316. {
  317. status: 'anonymous',
  318. generation: logoutGeneration,
  319. storeKind: this.options.credentialStore.kind,
  320. },
  321. this.options.namespace,
  322. ),
  323. );
  324. return { status: 'anonymous', generation: logoutGeneration };
  325. });
  326. }
  327. watch(listener: (status: AuthStatusSnapshot) => void): () => void {
  328. const onChange = () => {
  329. void this.getStatus()
  330. .then(listener)
  331. .catch(() => undefined);
  332. };
  333. watchFile(this.options.namespace.statePath, { interval: this.statePollIntervalMs }, onChange);
  334. return () => unwatchFile(this.options.namespace.statePath, onChange);
  335. }
  336. private initialize(): Promise<void> {
  337. this.initializePromise ??= (async () => {
  338. await this.options.initialize?.();
  339. await this.options.credentialStore.healthCheck();
  340. })().catch((error) => {
  341. this.initializePromise = undefined;
  342. throw error;
  343. });
  344. return this.initializePromise;
  345. }
  346. private async runLogin(options: LoginOptions, signal: AbortSignal): Promise<LoginResult> {
  347. while (true) {
  348. assertLoginNotCancelled(signal);
  349. const leaseId = this.createLeaseId();
  350. const decision = await this.lock.withLock(async () => {
  351. const state = await this.stateStore.read();
  352. assertLoginStateDomain(state, this.options.namespace);
  353. const credential = await this.options.credentialStore.get(
  354. this.options.namespace.credentialKey,
  355. );
  356. if (
  357. state &&
  358. credential &&
  359. state.generation === credential.generation &&
  360. (state.status === 'authenticated' ||
  361. state.status === 'expired' ||
  362. state.status === 'refreshing')
  363. ) {
  364. try {
  365. assertCredentialContract(credential, [...MCODE_OAUTH_SCOPES]);
  366. if (state.status === 'authenticated' && credential.expiresAtMs > this.now()) {
  367. return { kind: 'authenticated' as const, generation: credential.generation };
  368. }
  369. return { kind: 'refresh' as const, generation: credential.generation };
  370. } catch (error) {
  371. if (
  372. !(error instanceof AuthScopeUpgradeRequiredError) &&
  373. !(error instanceof AuthResourceContractMismatchError)
  374. ) {
  375. throw error;
  376. }
  377. }
  378. }
  379. if (
  380. state?.status === 'authorizing' &&
  381. state.authorization &&
  382. state.authorization.leaseExpiresAtMs > this.now()
  383. ) {
  384. return { kind: 'wait' as const, leaseExpiresAtMs: state.authorization.leaseExpiresAtMs };
  385. }
  386. const generation = Math.max(state?.generation ?? 0, credential?.generation ?? 0);
  387. await this.stateStore.write({
  388. ...baseState(
  389. {
  390. status: 'authorizing',
  391. generation,
  392. storeKind: this.options.credentialStore.kind,
  393. },
  394. this.options.namespace,
  395. ),
  396. authorization: {
  397. leaseId,
  398. leaseExpiresAtMs: this.now() + this.authorizationLeaseMs,
  399. },
  400. });
  401. return { kind: 'owner' as const };
  402. });
  403. if (decision.kind === 'authenticated') {
  404. return { status: 'authenticated', generation: decision.generation };
  405. }
  406. if (decision.kind === 'refresh') {
  407. try {
  408. await this.lock.withLock(async () => {
  409. const current = await this.readUsableCredential([...MCODE_OAUTH_SCOPES]);
  410. if (
  411. current.credential.generation > decision.generation &&
  412. this.satisfiesMinValidity(current, 1)
  413. )
  414. return;
  415. await this.refreshCredential(current);
  416. });
  417. } catch (error) {
  418. // The credential changed or vanished concurrently; re-evaluate.
  419. if (requiresInteractiveLogin(error)) continue;
  420. throw error;
  421. }
  422. const state = await this.stateStore.read();
  423. if (state?.status === 'authenticated') {
  424. return { status: 'authenticated', generation: state.generation };
  425. }
  426. continue;
  427. }
  428. if (decision.kind === 'wait') {
  429. const result = await this.waitForAuthorization(
  430. decision.leaseExpiresAtMs,
  431. options.onDeviceAuthorization,
  432. signal,
  433. );
  434. if (result) return result;
  435. continue;
  436. }
  437. try {
  438. const authorization = await this.options.oauthClient.startDeviceAuthorization({ signal });
  439. await this.publishAuthorizationProgress(leaseId, authorization);
  440. options.onDeviceAuthorization?.(toAuthorizationPrompt(authorization));
  441. const grant = await this.options.oauthClient.pollDeviceToken(authorization, { signal });
  442. return await this.commitLogin(leaseId, grant, signal);
  443. } catch (error) {
  444. const cancelled = signal.aborted;
  445. await this.releaseAuthorizationLease(leaseId, cancelled ? 'anonymous' : 'error');
  446. if (cancelled) throw new AuthLoginCancelledError();
  447. throw error;
  448. }
  449. }
  450. }
  451. private async commitLogin(
  452. leaseId: string,
  453. grant: OAuthTokenGrant,
  454. signal: AbortSignal,
  455. ): Promise<LoginResult> {
  456. return this.lock.withLock(async () => {
  457. assertLoginNotCancelled(signal);
  458. const state = await this.stateStore.read();
  459. if (state?.status !== 'authorizing' || state.authorization?.leaseId !== leaseId) {
  460. throw new AuthRequiredError();
  461. }
  462. const credential = await this.options.credentialStore.get(
  463. this.options.namespace.credentialKey,
  464. );
  465. assertLoginNotCancelled(signal);
  466. const generation = Math.max(state.generation, credential?.generation ?? 0) + 1;
  467. const stored = credentialFromGrant(grant, generation, this.now(), randomUUID());
  468. await this.options.credentialStore.put(this.options.namespace.credentialKey, stored);
  469. try {
  470. assertLoginNotCancelled(signal);
  471. await this.stateStore.write(
  472. authenticatedState(stored, this.options.credentialStore.kind, this.options.namespace),
  473. );
  474. assertLoginNotCancelled(signal);
  475. } catch (error) {
  476. if (error instanceof AuthLoginCancelledError) {
  477. // Roll back under the same lock; another client's login cannot be erased.
  478. await this.stateStore.write(state);
  479. if (credential) {
  480. await this.options.credentialStore.put(
  481. this.options.namespace.credentialKey,
  482. credential,
  483. );
  484. } else {
  485. await this.options.credentialStore.delete(this.options.namespace.credentialKey);
  486. }
  487. }
  488. throw error;
  489. }
  490. return { status: 'authenticated', generation };
  491. });
  492. }
  493. private async waitForAuthorization(
  494. leaseExpiresAtMs: number,
  495. onDeviceAuthorization?: (authorization: DeviceAuthorizationPrompt) => void,
  496. signal?: AbortSignal,
  497. ): Promise<LoginResult | undefined> {
  498. let progressPublished = false;
  499. while (this.now() < leaseExpiresAtMs) {
  500. assertLoginNotCancelled(signal);
  501. const state = await this.stateStore.read();
  502. if (
  503. !progressPublished &&
  504. state?.status === 'authorizing' &&
  505. state.authorization?.userCode &&
  506. state.authorization.verificationUri
  507. ) {
  508. onDeviceAuthorization?.({
  509. userCode: state.authorization.userCode,
  510. verificationUri: state.authorization.verificationUri,
  511. ...(state.authorization.verificationUriComplete
  512. ? { verificationUriComplete: state.authorization.verificationUriComplete }
  513. : {}),
  514. expiresInSec: Math.max(
  515. 1,
  516. Math.ceil((state.authorization.leaseExpiresAtMs - this.now()) / 1_000),
  517. ),
  518. });
  519. progressPublished = true;
  520. }
  521. if (state?.status === 'authenticated') {
  522. const credential = await this.options.credentialStore.get(
  523. this.options.namespace.credentialKey,
  524. );
  525. if (credential && credential.generation === state.generation) {
  526. assertCredentialContract(credential, [...MCODE_OAUTH_SCOPES]);
  527. return { status: 'authenticated', generation: state.generation };
  528. }
  529. }
  530. if (state?.status !== 'authorizing') return undefined;
  531. await sleepWithSignal(this.sleep, this.statePollIntervalMs, signal);
  532. }
  533. return undefined;
  534. }
  535. private async publishAuthorizationProgress(
  536. leaseId: string,
  537. authorization: DeviceAuthorization,
  538. ): Promise<void> {
  539. await this.lock.withLock(async () => {
  540. const state = await this.stateStore.read();
  541. if (state?.status !== 'authorizing' || state.authorization?.leaseId !== leaseId) {
  542. throw new AuthRequiredError();
  543. }
  544. await this.stateStore.write({
  545. ...state,
  546. authorization: {
  547. ...state.authorization,
  548. userCode: authorization.userCode,
  549. verificationUri: authorization.verificationUri,
  550. ...(authorization.verificationUriComplete
  551. ? { verificationUriComplete: authorization.verificationUriComplete }
  552. : {}),
  553. },
  554. });
  555. });
  556. }
  557. private async releaseAuthorizationLease(
  558. leaseId: string,
  559. status: Extract<AuthStatus, 'anonymous' | 'error'>,
  560. ): Promise<void> {
  561. await this.lock.withLock(async () => {
  562. const state = await this.stateStore.read();
  563. if (state?.status !== 'authorizing' || state.authorization?.leaseId !== leaseId) return;
  564. await this.stateStore.write(
  565. baseState(
  566. {
  567. status,
  568. generation: state.generation,
  569. storeKind: this.options.credentialStore.kind,
  570. },
  571. this.options.namespace,
  572. ),
  573. );
  574. });
  575. }
  576. private async recoverInterruptedCredentialCommit(observedState: AuthState): Promise<AuthState> {
  577. const observedCredential = await this.options.credentialStore.get(
  578. this.options.namespace.credentialKey,
  579. );
  580. if (!observedCredential || observedCredential.generation <= observedState.generation) {
  581. return observedState;
  582. }
  583. assertCredentialContract(observedCredential, [...MCODE_OAUTH_SCOPES]);
  584. return this.lock.withLock(async () => {
  585. const state = await this.stateStore.read();
  586. const credential = await this.options.credentialStore.get(
  587. this.options.namespace.credentialKey,
  588. );
  589. if (
  590. !state ||
  591. !credential ||
  592. (state.status !== 'authorizing' && state.status !== 'refreshing') ||
  593. credential.generation <= state.generation
  594. ) {
  595. return state ?? observedState;
  596. }
  597. assertCredentialContract(credential, [...MCODE_OAUTH_SCOPES]);
  598. const recovered = authenticatedState(
  599. credential,
  600. this.options.credentialStore.kind,
  601. this.options.namespace,
  602. );
  603. await this.stateStore.write(recovered);
  604. return recovered;
  605. });
  606. }
  607. private async readUsableCredential(requiredScopes: string[]): Promise<{
  608. state: AuthState;
  609. credential: StoredCredential;
  610. }> {
  611. const state = await this.stateStore.read();
  612. if (
  613. !state ||
  614. (state.status !== 'authenticated' &&
  615. state.status !== 'expired' &&
  616. state.status !== 'refreshing')
  617. ) {
  618. throw new AuthRequiredError();
  619. }
  620. const credential = await this.options.credentialStore.get(this.options.namespace.credentialKey);
  621. if (!credential || state.generation !== credential.generation) throw new AuthRequiredError();
  622. assertCredentialContract(credential, requiredScopes);
  623. return { state, credential };
  624. }
  625. private async refreshCredential(
  626. current: { state: AuthState; credential: StoredCredential },
  627. options: { rejected?: boolean } = {},
  628. ): Promise<AccessTokenLease> {
  629. await this.stateStore.write({ ...current.state, status: 'refreshing' });
  630. let grant: OAuthTokenGrant;
  631. try {
  632. grant = await this.options.oauthClient.refreshToken(current.credential.refreshToken);
  633. } catch (error) {
  634. if (isInvalidRefreshGrant(error)) {
  635. // Publish the invalidation before deleting the secret. Both mutations
  636. // use the caller's lock, so another owner cannot commit a login between them.
  637. await this.stateStore.write(
  638. baseState(
  639. {
  640. status: 'anonymous',
  641. generation: current.credential.generation + 1,
  642. storeKind: this.options.credentialStore.kind,
  643. },
  644. this.options.namespace,
  645. ),
  646. );
  647. await this.options.credentialStore.delete(this.options.namespace.credentialKey);
  648. throw new AuthRequiredError({ cause: error });
  649. } else {
  650. const preserveSession =
  651. !options.rejected &&
  652. current.state.status === 'authenticated' &&
  653. current.credential.expiresAtMs > this.now();
  654. await this.stateStore.write({
  655. ...current.state,
  656. status: preserveSession ? 'authenticated' : 'expired',
  657. });
  658. }
  659. throw error;
  660. }
  661. const stored = credentialFromGrant(
  662. grant,
  663. Math.max(current.state.generation, current.credential.generation) + 1,
  664. this.now(),
  665. current.credential.loginEpoch,
  666. );
  667. await this.options.credentialStore.put(this.options.namespace.credentialKey, stored);
  668. await this.stateStore.write(
  669. authenticatedState(stored, this.options.credentialStore.kind, this.options.namespace),
  670. );
  671. return toAccessTokenLease(stored);
  672. }
  673. }
  674. function assertLoginNotCancelled(signal: AbortSignal | undefined): void {
  675. if (signal?.aborted) throw new AuthLoginCancelledError();
  676. }
  677. function isInvalidRefreshGrant(error: unknown): boolean {
  678. return (
  679. error instanceof OAuthProtocolError &&
  680. error.code === 'invalid_grant' &&
  681. error.httpStatus === 400
  682. );
  683. }
  684. async function sleepWithSignal(
  685. sleep: (durationMs: number) => Promise<void>,
  686. durationMs: number,
  687. signal: AbortSignal | undefined,
  688. ): Promise<void> {
  689. if (!signal) {
  690. await sleep(durationMs);
  691. return;
  692. }
  693. assertLoginNotCancelled(signal);
  694. let rejectCancellation!: (error: AuthLoginCancelledError) => void;
  695. const onAbort = () => rejectCancellation(new AuthLoginCancelledError());
  696. const cancelled = new Promise<never>((_resolve, reject) => {
  697. rejectCancellation = reject;
  698. });
  699. signal.addEventListener('abort', onAbort, { once: true });
  700. try {
  701. await Promise.race([sleep(durationMs), cancelled]);
  702. } finally {
  703. signal.removeEventListener('abort', onAbort);
  704. }
  705. }
  706. function toAuthorizationPrompt(authorization: DeviceAuthorization): DeviceAuthorizationPrompt {
  707. return {
  708. userCode: authorization.userCode,
  709. verificationUri: authorization.verificationUri,
  710. ...(authorization.verificationUriComplete
  711. ? { verificationUriComplete: authorization.verificationUriComplete }
  712. : {}),
  713. expiresInSec: authorization.expiresInSec,
  714. };
  715. }
  716. function baseState(
  717. input: {
  718. status: AuthStatus;
  719. generation: number;
  720. storeKind: CredentialStore['kind'];
  721. },
  722. namespace: AuthNamespace,
  723. ): AuthState {
  724. return {
  725. schemaVersion: AUTH_STATE_SCHEMA_VERSION,
  726. status: input.status,
  727. storeKind: input.storeKind,
  728. clientId: MCODE_OAUTH_CLIENT_ID,
  729. scopes: [...MCODE_OAUTH_SCOPES],
  730. audience: MCODE_OAUTH_AUDIENCE,
  731. buildEnv: namespace.buildEnv,
  732. region: namespace.region,
  733. generation: input.generation,
  734. };
  735. }
  736. function authenticatedState(
  737. credential: StoredCredential,
  738. storeKind: CredentialStore['kind'],
  739. namespace: AuthNamespace,
  740. ): AuthState {
  741. return {
  742. ...baseState(
  743. { status: 'authenticated', generation: credential.generation, storeKind },
  744. namespace,
  745. ),
  746. scopes: credential.scopes,
  747. expiresAtMs: credential.expiresAtMs,
  748. };
  749. }
  750. function credentialFromGrant(
  751. grant: OAuthTokenGrant,
  752. generation: number,
  753. now: number,
  754. loginEpoch: string = randomUUID(),
  755. ): StoredCredential {
  756. const credential: StoredCredential = {
  757. schemaVersion: 1,
  758. accessToken: grant.accessToken,
  759. refreshToken: grant.refreshToken,
  760. tokenType: grant.tokenType,
  761. clientId: MCODE_OAUTH_CLIENT_ID,
  762. scopes: grant.scopes,
  763. audience: MCODE_OAUTH_AUDIENCE,
  764. expiresAtMs: now + grant.expiresInSec * 1_000,
  765. generation,
  766. loginEpoch,
  767. ...(grant.subject ? { subject: grant.subject } : {}),
  768. ...(grant.accountId ? { accountId: grant.accountId } : {}),
  769. };
  770. assertCredentialContract(credential, [...MCODE_OAUTH_SCOPES]);
  771. if (grant.audience !== MCODE_OAUTH_AUDIENCE) throw new AuthResourceContractMismatchError();
  772. return credential;
  773. }
  774. function validateRequestedScopes(requiredScopes: string[]): void {
  775. const unsupported = requiredScopes.filter(
  776. (scope) => !MCODE_OAUTH_SCOPES.includes(scope as 'agent.default'),
  777. );
  778. if (unsupported.length > 0) throw new AuthScopeUpgradeRequiredError(unsupported);
  779. }
  780. function assertCredentialContract(credential: StoredCredential, requiredScopes: string[]): void {
  781. if (
  782. credential.clientId !== MCODE_OAUTH_CLIENT_ID ||
  783. credential.audience !== MCODE_OAUTH_AUDIENCE ||
  784. credential.tokenType !== 'Bearer'
  785. ) {
  786. throw new AuthResourceContractMismatchError();
  787. }
  788. const missing = requiredScopes.filter((scope) => !credential.scopes.includes(scope));
  789. if (missing.length > 0) throw new AuthScopeUpgradeRequiredError(missing);
  790. }
  791. function toStatusSnapshot(state: AuthState): AuthStatusSnapshot {
  792. return {
  793. status: state.status,
  794. generation: state.generation,
  795. scopes: state.scopes,
  796. ...(state.buildEnv === undefined ? {} : { buildEnv: state.buildEnv }),
  797. ...(state.region === undefined ? {} : { region: state.region }),
  798. ...(state.expiresAtMs === undefined ? {} : { expiresAtMs: state.expiresAtMs }),
  799. };
  800. }
  801. function assertLoginStateDomain(state: AuthState | null, namespace: AuthNamespace): void {
  802. if (
  803. !state ||
  804. state.status === 'anonymous' ||
  805. state.buildEnv === undefined ||
  806. state.region === undefined ||
  807. (state.buildEnv === namespace.buildEnv && state.region === namespace.region)
  808. ) {
  809. return;
  810. }
  811. throw new AuthDomainConflictError(
  812. { buildEnv: state.buildEnv, region: state.region },
  813. { buildEnv: namespace.buildEnv, region: namespace.region },
  814. );
  815. }
  816. function toAccessTokenLease(credential: StoredCredential): AccessTokenLease {
  817. return {
  818. accessToken: credential.accessToken,
  819. ...(credential.loginEpoch ? { loginEpoch: credential.loginEpoch } : {}),
  820. expiresAtMs: credential.expiresAtMs,
  821. generation: credential.generation,
  822. scopes: MCODE_OAUTH_SCOPES,
  823. audience: MCODE_OAUTH_AUDIENCE,
  824. };
  825. }