oauth-client.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. import { createHash, randomBytes } from 'node:crypto';
  2. import { MCODE_OAUTH_AUDIENCE, MCODE_OAUTH_CLIENT_ID, MCODE_OAUTH_SCOPES } from './contracts.js';
  3. const DEVICE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
  4. export interface DeviceAuthorization {
  5. deviceCode: string;
  6. codeVerifier: string;
  7. tokenPollingParameter?: 'user_code';
  8. userCode: string;
  9. verificationUri: string;
  10. verificationUriComplete?: string;
  11. expiresInSec: number;
  12. intervalSec: number;
  13. }
  14. export interface OAuthTokenGrant {
  15. accessToken: string;
  16. refreshToken: string;
  17. tokenType: 'Bearer';
  18. scopes: string[];
  19. audience: string;
  20. expiresInSec: number;
  21. subject?: string;
  22. accountId?: string;
  23. }
  24. export interface OAuthClient {
  25. startDeviceAuthorization(options?: OAuthRequestOptions): Promise<DeviceAuthorization>;
  26. pollDeviceToken(
  27. authorization: DeviceAuthorization,
  28. options?: OAuthRequestOptions,
  29. ): Promise<OAuthTokenGrant>;
  30. refreshToken(refreshToken: string): Promise<OAuthTokenGrant>;
  31. revokeToken(refreshToken: string): Promise<void>;
  32. }
  33. export interface OAuthRequestOptions {
  34. signal?: AbortSignal;
  35. }
  36. export interface HttpOAuthClientOptions {
  37. deviceAuthorizationEndpoint: string;
  38. deviceAuthorizationHeaders?: Record<string, string>;
  39. tokenEndpoint: string;
  40. revocationEndpoint: string;
  41. fetchImpl?: typeof fetch;
  42. sleep?: (durationMs: number) => Promise<void>;
  43. now?: () => number;
  44. }
  45. export class OAuthProtocolError extends Error {
  46. constructor(
  47. readonly code: string,
  48. message?: string,
  49. readonly httpStatus?: number,
  50. ) {
  51. super(
  52. message ??
  53. `The OAuth server rejected the request (${code}${httpStatus ? `, HTTP ${httpStatus}` : ''}).`,
  54. );
  55. this.name = 'OAuthProtocolError';
  56. }
  57. }
  58. export class HttpOAuthClient implements OAuthClient {
  59. private readonly fetchImpl: typeof fetch;
  60. private readonly sleep: (durationMs: number) => Promise<void>;
  61. private readonly now: () => number;
  62. constructor(private readonly options: HttpOAuthClientOptions) {
  63. this.fetchImpl = options.fetchImpl ?? fetch;
  64. this.sleep =
  65. options.sleep ?? ((durationMs) => new Promise((resolve) => setTimeout(resolve, durationMs)));
  66. this.now = options.now ?? Date.now;
  67. }
  68. async startDeviceAuthorization(options: OAuthRequestOptions = {}): Promise<DeviceAuthorization> {
  69. const codeVerifier = randomBytes(32).toString('base64url');
  70. const codeChallenge = createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
  71. const body = await this.postForm(
  72. this.options.deviceAuthorizationEndpoint,
  73. {
  74. client_id: MCODE_OAUTH_CLIENT_ID,
  75. scope: MCODE_OAUTH_SCOPES.join(' '),
  76. audience: MCODE_OAUTH_AUDIENCE,
  77. code_challenge: codeChallenge,
  78. code_challenge_method: 'S256',
  79. },
  80. {
  81. headers: this.options.deviceAuthorizationHeaders,
  82. signal: options.signal,
  83. },
  84. );
  85. const userCode = readString(body, 'user_code');
  86. const standardDeviceCode = readString(body, 'device_code');
  87. const accountExpiredAtMs = readPositiveNumber(body, 'expired_in');
  88. const usesAccountUserCodePolling =
  89. !standardDeviceCode && Boolean(userCode) && accountExpiredAtMs !== undefined;
  90. const deviceCode = standardDeviceCode ?? (usesAccountUserCodePolling ? userCode : undefined);
  91. const verificationUri =
  92. readString(body, 'verification_uri') ?? readString(body, 'verification_url');
  93. const expiresInSec =
  94. readPositiveNumber(body, 'expires_in') ??
  95. normalizeAccountExpirySeconds(accountExpiredAtMs, this.now());
  96. const rawInterval = readPositiveNumber(body, 'interval');
  97. const intervalSec =
  98. usesAccountUserCodePolling && rawInterval !== undefined
  99. ? rawInterval / 1_000
  100. : (rawInterval ?? 5);
  101. if (!deviceCode || !userCode || !verificationUri || !expiresInSec) {
  102. throw new OAuthProtocolError('invalid_device_authorization_response');
  103. }
  104. return {
  105. deviceCode,
  106. codeVerifier,
  107. ...(usesAccountUserCodePolling ? { tokenPollingParameter: 'user_code' as const } : {}),
  108. userCode,
  109. verificationUri,
  110. ...(readString(body, 'verification_uri_complete') || usesAccountUserCodePolling
  111. ? {
  112. verificationUriComplete:
  113. readString(body, 'verification_uri_complete') ?? verificationUri,
  114. }
  115. : {}),
  116. expiresInSec,
  117. intervalSec,
  118. };
  119. }
  120. async pollDeviceToken(
  121. authorization: DeviceAuthorization,
  122. options: OAuthRequestOptions = {},
  123. ): Promise<OAuthTokenGrant> {
  124. const deadline = this.now() + authorization.expiresInSec * 1_000;
  125. let intervalMs = authorization.intervalSec * 1_000;
  126. while (this.now() < deadline) {
  127. options.signal?.throwIfAborted();
  128. const pollingCode: Record<string, string> =
  129. authorization.tokenPollingParameter === 'user_code'
  130. ? { user_code: authorization.userCode }
  131. : { device_code: authorization.deviceCode };
  132. const response = await this.postFormAllowOAuthError(
  133. this.options.tokenEndpoint,
  134. {
  135. grant_type: DEVICE_GRANT_TYPE,
  136. ...pollingCode,
  137. client_id: MCODE_OAUTH_CLIENT_ID,
  138. code_verifier: authorization.codeVerifier,
  139. },
  140. { signal: options.signal },
  141. );
  142. const pollingStatus = readString(response.body, 'status');
  143. if (response.ok && pollingStatus === 'pending') {
  144. await sleepWithSignal(this.sleep, intervalMs, options.signal);
  145. continue;
  146. }
  147. if (response.ok && pollingStatus === 'slow_down') {
  148. intervalMs += 5_000;
  149. await sleepWithSignal(this.sleep, intervalMs, options.signal);
  150. continue;
  151. }
  152. if (response.ok && (pollingStatus === 'denied' || pollingStatus === 'access_denied')) {
  153. throw new OAuthProtocolError('access_denied');
  154. }
  155. if (response.ok && (pollingStatus === 'expired' || pollingStatus === 'expired_token')) {
  156. throw new OAuthProtocolError('expired_token');
  157. }
  158. if (response.ok) return parseTokenGrant(response.body);
  159. if (response.error === 'authorization_pending') {
  160. await sleepWithSignal(this.sleep, intervalMs, options.signal);
  161. continue;
  162. }
  163. if (response.error === 'slow_down') {
  164. intervalMs += 5_000;
  165. await sleepWithSignal(this.sleep, intervalMs, options.signal);
  166. continue;
  167. }
  168. throw new OAuthProtocolError(
  169. response.error ?? 'device_authorization_failed',
  170. undefined,
  171. response.status,
  172. );
  173. }
  174. throw new OAuthProtocolError('expired_token', 'The OAuth device authorization expired.');
  175. }
  176. async refreshToken(refreshToken: string): Promise<OAuthTokenGrant> {
  177. const body = await this.postForm(this.options.tokenEndpoint, {
  178. grant_type: 'refresh_token',
  179. refresh_token: refreshToken,
  180. client_id: MCODE_OAUTH_CLIENT_ID,
  181. scope: MCODE_OAUTH_SCOPES.join(' '),
  182. audience: MCODE_OAUTH_AUDIENCE,
  183. });
  184. return parseTokenGrant(body, refreshToken);
  185. }
  186. async revokeToken(refreshToken: string): Promise<void> {
  187. const response = await this.postFormAllowOAuthError(
  188. this.options.revocationEndpoint,
  189. {
  190. token: refreshToken,
  191. token_type_hint: 'refresh_token',
  192. client_id: MCODE_OAUTH_CLIENT_ID,
  193. },
  194. { allowEmptySuccess: true },
  195. );
  196. if (!response.ok)
  197. throw new OAuthProtocolError(
  198. response.error ?? 'oauth_request_failed',
  199. undefined,
  200. response.status,
  201. );
  202. }
  203. private async postForm(
  204. endpoint: string,
  205. values: Record<string, string>,
  206. options: OAuthHttpRequestOptions = {},
  207. ): Promise<Record<string, unknown>> {
  208. const response = await this.postFormAllowOAuthError(endpoint, values, options);
  209. if (!response.ok)
  210. throw new OAuthProtocolError(
  211. response.error ?? 'oauth_request_failed',
  212. undefined,
  213. response.status,
  214. );
  215. return response.body;
  216. }
  217. private async postFormAllowOAuthError(
  218. endpoint: string,
  219. values: Record<string, string>,
  220. options: OAuthHttpRequestOptions = {},
  221. ): Promise<{ ok: boolean; status: number; body: Record<string, unknown>; error?: string }> {
  222. const response = await this.fetchImpl(endpoint, {
  223. method: 'POST',
  224. headers: {
  225. Accept: 'application/json',
  226. 'Content-Type': 'application/x-www-form-urlencoded',
  227. ...options.headers,
  228. },
  229. body: new URLSearchParams(values),
  230. signal: options.signal,
  231. });
  232. const body = asRecord(await response.json().catch(() => undefined));
  233. if (!body && response.ok && options.allowEmptySuccess)
  234. return { ok: true, status: response.status, body: {} };
  235. if (!body) throw new OAuthProtocolError('invalid_json_response', undefined, response.status);
  236. const error = readString(body, 'error');
  237. return {
  238. ok: response.ok && !error,
  239. status: response.status,
  240. body,
  241. ...(error ? { error } : {}),
  242. };
  243. }
  244. }
  245. interface OAuthHttpRequestOptions extends OAuthRequestOptions {
  246. headers?: Record<string, string>;
  247. allowEmptySuccess?: boolean;
  248. }
  249. async function sleepWithSignal(
  250. sleep: (durationMs: number) => Promise<void>,
  251. durationMs: number,
  252. signal: AbortSignal | undefined,
  253. ): Promise<void> {
  254. if (!signal) {
  255. await sleep(durationMs);
  256. return;
  257. }
  258. signal.throwIfAborted();
  259. let rejectAbort!: (reason?: unknown) => void;
  260. const onAbort = () => rejectAbort(signal.reason);
  261. const aborted = new Promise<never>((_resolve, reject) => {
  262. rejectAbort = reject;
  263. });
  264. signal.addEventListener('abort', onAbort, { once: true });
  265. try {
  266. await Promise.race([sleep(durationMs), aborted]);
  267. } finally {
  268. signal.removeEventListener('abort', onAbort);
  269. }
  270. }
  271. function parseTokenGrant(
  272. body: Record<string, unknown>,
  273. previousRefreshToken?: string,
  274. ): OAuthTokenGrant {
  275. const accessToken = readString(body, 'access_token');
  276. const refreshToken = readString(body, 'refresh_token') ?? previousRefreshToken;
  277. const tokenType = readString(body, 'token_type');
  278. const expiresInSec = readPositiveNumber(body, 'expires_in');
  279. const claims = accessToken ? decodeJwtPayload(accessToken) : undefined;
  280. const scopes = parseScopes(body.scope ?? claims?.scope ?? claims?.scp);
  281. if (
  282. !accessToken ||
  283. !refreshToken ||
  284. tokenType?.toLowerCase() !== 'bearer' ||
  285. !expiresInSec ||
  286. !scopes.includes(MCODE_OAUTH_SCOPES[0])
  287. ) {
  288. throw new OAuthProtocolError('invalid_token_response');
  289. }
  290. return {
  291. accessToken,
  292. refreshToken,
  293. tokenType: 'Bearer',
  294. scopes,
  295. audience: MCODE_OAUTH_AUDIENCE,
  296. expiresInSec,
  297. ...(readString(claims, 'sub') ? { subject: readString(claims, 'sub') } : {}),
  298. ...(readString(claims, 'account_id') ? { accountId: readString(claims, 'account_id') } : {}),
  299. };
  300. }
  301. function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
  302. const segments = token.split('.');
  303. if (segments.length !== 3 || !segments[1]) return undefined;
  304. try {
  305. return asRecord(JSON.parse(Buffer.from(segments[1], 'base64url').toString('utf8')));
  306. } catch {
  307. return undefined;
  308. }
  309. }
  310. function parseScopes(value: unknown): string[] {
  311. if (typeof value === 'string') return value.split(/\s+/u).filter(Boolean);
  312. if (Array.isArray(value) && value.every((scope) => typeof scope === 'string')) return value;
  313. return [];
  314. }
  315. function asRecord(value: unknown): Record<string, unknown> | undefined {
  316. return typeof value === 'object' && value !== null && !Array.isArray(value)
  317. ? (value as Record<string, unknown>)
  318. : undefined;
  319. }
  320. function readString(value: unknown, key: string): string | undefined {
  321. const record = asRecord(value);
  322. const candidate = record?.[key];
  323. return typeof candidate === 'string' && candidate.trim() ? candidate.trim() : undefined;
  324. }
  325. function readPositiveNumber(value: unknown, key: string): number | undefined {
  326. const record = asRecord(value);
  327. const candidate = record?.[key];
  328. return typeof candidate === 'number' && Number.isFinite(candidate) && candidate > 0
  329. ? candidate
  330. : undefined;
  331. }
  332. function normalizeAccountExpirySeconds(
  333. expiredIn: number | undefined,
  334. nowMs: number,
  335. ): number | undefined {
  336. if (expiredIn === undefined) return undefined;
  337. if (expiredIn < 1_000_000_000_000) return expiredIn;
  338. const remainingMs = expiredIn - nowMs;
  339. return remainingMs > 0 ? Math.ceil(remainingMs / 1_000) : undefined;
  340. }