lease-broker.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { randomBytes } from 'node:crypto';
  2. import { chmod, mkdir, open, rename, rm } from 'node:fs/promises';
  3. import path from 'node:path';
  4. import {
  5. AUTH_LEASE_AUDIENCE,
  6. AUTH_LEASE_PROTOCOL_VERSION,
  7. AUTH_LEASE_SCOPES,
  8. AuthLeaseProtocolError,
  9. resolveAuthLeaseEndpoint,
  10. startNodeAuthLeaseServer,
  11. type AuthLeaseRequest,
  12. type AuthLeaseSuccessResult,
  13. type NodeAuthLeaseServer,
  14. } from '@mavis/oauth-lease-protocol';
  15. import type {
  16. McodeToolsAccessTokenLease,
  17. McodeToolsAuthStatusSnapshot,
  18. McodeToolsHostAuthSession,
  19. McodeToolsHostLogger,
  20. } from './contracts.js';
  21. const NOOP_LOGGER: McodeToolsHostLogger = {
  22. info: () => undefined,
  23. warn: () => undefined,
  24. };
  25. export interface McodeToolsAuthLeaseBroker {
  26. endpoint: string;
  27. capabilityFile: string;
  28. dispose(): Promise<void>;
  29. }
  30. export interface StartMcodeToolsAuthLeaseBrokerOptions {
  31. dataDir: string;
  32. session: McodeToolsHostAuthSession;
  33. now?: () => number;
  34. logger?: McodeToolsHostLogger;
  35. }
  36. export async function startMcodeToolsAuthLeaseBroker(
  37. options: StartMcodeToolsAuthLeaseBrokerOptions,
  38. ): Promise<McodeToolsAuthLeaseBroker> {
  39. const endpoint = resolveAuthLeaseEndpoint(options.dataDir);
  40. const capability = randomBytes(32).toString('base64url');
  41. const now = options.now ?? Date.now;
  42. const brokerLogger = options.logger ?? NOOP_LOGGER;
  43. let cachedLease: McodeToolsAccessTokenLease | undefined;
  44. let inFlight:
  45. | {
  46. epoch: number;
  47. promise: Promise<McodeToolsAccessTokenLease>;
  48. }
  49. | undefined;
  50. let epoch = 0;
  51. let minimumGeneration = 0;
  52. let admissionOpen = true;
  53. let disposed = false;
  54. let server: NodeAuthLeaseServer | undefined;
  55. let stopWatching: (() => void) | undefined;
  56. function invalidate(): void {
  57. epoch += 1;
  58. cachedLease = undefined;
  59. }
  60. async function loadValidatedLease(
  61. minValidityMs: number,
  62. requestEpoch: number,
  63. ): Promise<McodeToolsAccessTokenLease> {
  64. const lease = await loadLease(options.session, minValidityMs);
  65. assertFixedLease(lease);
  66. if (disposed) throw new AuthLeaseProtocolError('BROKER_UNAVAILABLE');
  67. if (requestEpoch !== epoch || !admissionOpen || lease.generation < minimumGeneration) {
  68. throw new AuthLeaseProtocolError('AUTH_REQUIRED');
  69. }
  70. cachedLease = lease;
  71. return lease;
  72. }
  73. async function acquireLease(minValidityMs: number): Promise<McodeToolsAccessTokenLease> {
  74. if (disposed) throw new AuthLeaseProtocolError('BROKER_UNAVAILABLE');
  75. if (!admissionOpen) throw new AuthLeaseProtocolError('AUTH_REQUIRED');
  76. if (
  77. cachedLease &&
  78. admissionOpen &&
  79. cachedLease.generation >= minimumGeneration &&
  80. isUsableLease(cachedLease, minValidityMs, now())
  81. ) {
  82. return cachedLease;
  83. }
  84. for (;;) {
  85. if (inFlight) {
  86. const lease = await inFlight.promise;
  87. if (
  88. admissionOpen &&
  89. lease.generation >= minimumGeneration &&
  90. isUsableLease(lease, minValidityMs, now())
  91. ) {
  92. return lease;
  93. }
  94. continue;
  95. }
  96. const requestEpoch = epoch;
  97. const request = loadValidatedLease(minValidityMs, requestEpoch);
  98. const current = { epoch: requestEpoch, promise: request };
  99. inFlight = current;
  100. try {
  101. const lease = await request;
  102. if (
  103. admissionOpen &&
  104. lease.generation >= minimumGeneration &&
  105. isUsableLease(lease, minValidityMs, now())
  106. ) {
  107. return lease;
  108. }
  109. } finally {
  110. if (inFlight === current) inFlight = undefined;
  111. }
  112. }
  113. }
  114. async function handleRequest(request: AuthLeaseRequest): Promise<AuthLeaseSuccessResult> {
  115. if (disposed) throw new AuthLeaseProtocolError('BROKER_UNAVAILABLE');
  116. if (request.method === 'status') return await getCredentialFreeStatus(options.session);
  117. if (request.method === 'lease') {
  118. const lease = await acquireLease(request.minValidityMs);
  119. return {
  120. method: 'lease',
  121. accessToken: lease.accessToken,
  122. expiresAtMs: lease.expiresAtMs,
  123. generation: lease.generation,
  124. audience: AUTH_LEASE_AUDIENCE,
  125. scopes: AUTH_LEASE_SCOPES,
  126. };
  127. }
  128. invalidate();
  129. const action = await options.session.handleUnauthorized(request.generation);
  130. return { method: 'unauthorized', action };
  131. }
  132. await atomicWriteCapability(endpoint.capabilityFile, capability);
  133. try {
  134. server = await startNodeAuthLeaseServer({
  135. endpoint: endpoint.endpoint,
  136. capability,
  137. handler: handleRequest,
  138. });
  139. stopWatching = options.session.watch((status) => {
  140. minimumGeneration = Math.max(minimumGeneration, status.generation);
  141. const generationChanged =
  142. cachedLease !== undefined && cachedLease.generation < minimumGeneration;
  143. const admissionClosed = status.status !== 'authenticated' && status.status !== 'refreshing';
  144. admissionOpen = !admissionClosed;
  145. if (admissionClosed) invalidate();
  146. else if (generationChanged) cachedLease = undefined;
  147. });
  148. } catch (error) {
  149. await server?.close().catch(() => undefined);
  150. await rm(endpoint.capabilityFile, { force: true });
  151. throw error;
  152. }
  153. brokerLogger.info(`[auth-lease-broker] ready protocol=${AUTH_LEASE_PROTOCOL_VERSION}`);
  154. return {
  155. endpoint: endpoint.endpoint,
  156. capabilityFile: endpoint.capabilityFile,
  157. async dispose(): Promise<void> {
  158. if (disposed) return;
  159. disposed = true;
  160. invalidate();
  161. stopWatching?.();
  162. stopWatching = undefined;
  163. try {
  164. await server?.close();
  165. } catch {
  166. brokerLogger.warn('[auth-lease-broker] dispose transport_error');
  167. } finally {
  168. server = undefined;
  169. await rm(endpoint.capabilityFile, { force: true });
  170. }
  171. brokerLogger.info(`[auth-lease-broker] disposed protocol=${AUTH_LEASE_PROTOCOL_VERSION}`);
  172. },
  173. };
  174. }
  175. async function getCredentialFreeStatus(
  176. session: McodeToolsHostAuthSession,
  177. ): Promise<AuthLeaseSuccessResult> {
  178. const status = await session.getStatus();
  179. return {
  180. method: 'status',
  181. status: status.status,
  182. generation: status.generation,
  183. ...(status.expiresAtMs === undefined ? {} : { expiresAtMs: status.expiresAtMs }),
  184. };
  185. }
  186. async function loadLease(
  187. session: McodeToolsHostAuthSession,
  188. minValidityMs: number,
  189. ): Promise<McodeToolsAccessTokenLease> {
  190. try {
  191. return await session.getAccessToken(minValidityMs);
  192. } catch (error) {
  193. const status = await readStatusAfterLeaseFailure(session);
  194. if (!status || status.status !== 'authenticated') {
  195. throw new AuthLeaseProtocolError('AUTH_REQUIRED');
  196. }
  197. throw error;
  198. }
  199. }
  200. async function readStatusAfterLeaseFailure(
  201. session: McodeToolsHostAuthSession,
  202. ): Promise<McodeToolsAuthStatusSnapshot | undefined> {
  203. try {
  204. return await session.getStatus();
  205. } catch {
  206. return undefined;
  207. }
  208. }
  209. function isUsableLease(
  210. lease: McodeToolsAccessTokenLease,
  211. minValidityMs: number,
  212. nowMs: number,
  213. ): boolean {
  214. return lease.expiresAtMs - nowMs >= minValidityMs;
  215. }
  216. function assertFixedLease(lease: McodeToolsAccessTokenLease): void {
  217. if (
  218. lease.audience !== AUTH_LEASE_AUDIENCE ||
  219. lease.scopes.length !== 1 ||
  220. lease.scopes[0] !== AUTH_LEASE_SCOPES[0]
  221. ) {
  222. throw new AuthLeaseProtocolError('INTERNAL_ERROR');
  223. }
  224. }
  225. async function atomicWriteCapability(capabilityFile: string, capability: string): Promise<void> {
  226. const directory = path.dirname(capabilityFile);
  227. await mkdir(directory, { recursive: true, mode: 0o700 });
  228. if (process.platform !== 'win32') await chmod(directory, 0o700);
  229. const temporaryFile = `${capabilityFile}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
  230. let handle;
  231. try {
  232. handle = await open(temporaryFile, 'wx', 0o600);
  233. await handle.writeFile(`${capability}\n`, 'utf8');
  234. await handle.sync();
  235. if (process.platform !== 'win32') await handle.chmod(0o600);
  236. await handle.close();
  237. handle = undefined;
  238. await rename(temporaryFile, capabilityFile);
  239. if (process.platform !== 'win32') await chmod(capabilityFile, 0o600);
  240. } catch (error) {
  241. await handle?.close().catch(() => undefined);
  242. await rm(temporaryFile, { force: true });
  243. throw error;
  244. }
  245. }