The best way to control Claude Code, Codex and more from any computer or phone

main
ts 736 lines 26.3 KB
Raw
1 import http from "node:http";
2 import * as Clock from "effect/Clock";
3 import * as Digest from "effect/crypto/Digest";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
5 import * as Data from "effect/Data";
6 import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import { Base64Url } from "effect/encoding";
9 import * as FetchHttpClient from "effect/http/FetchHttpClient";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as HttpClientResponse from "effect/http/HttpClientResponse";
13 import * as Url from "effect/http/Url";
14 import * as Match from "effect/Match";
15 import * as Redacted from "effect/Redacted";
16 import * as Result from "effect/Result";
17 import * as Schedule from "effect/Schedule";
18 import * as Schema from "effect/Schema";
19 import { AUTH_ERROR_URL, AUTH_SUCCESS_URL } from "./AuthProvider.ts";
20
21 /**
22 * The authorization server rejected a request with an OAuth error code
23 * (RFC 6749 §5.2, RFC 8628 §3.5). `error` is the server's code verbatim.
24 */
25 export class OAuthError extends Data.TaggedError("OAuthError")<{
26 error: string;
27 errorDescription: string;
28 }> {
29 override get message(): string {
30 return `${this.error}: ${this.errorDescription}`;
31 }
32 }
33
34 /** A request to the authorization server could not be sent or answered. */
35 export class OAuthNetworkError extends Data.TaggedError("OAuthNetworkError")<{
36 endpoint: string;
37 cause: unknown;
38 }> {
39 override get message(): string {
40 return `Request to ${this.endpoint} failed: ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
41 }
42 }
43
44 /**
45 * The authorization server answered 429/5xx without an OAuth error body
46 * (typically an edge error page). Transient.
47 */
48 export class OAuthServerUnavailable extends Data.TaggedError("OAuthServerUnavailable")<{
49 endpoint: string;
50 status: number;
51 }> {
52 override get message(): string {
53 return `${this.endpoint} is temporarily unavailable (HTTP ${this.status}).`;
54 }
55 }
56
57 /** The authorization server's response could not be interpreted. */
58 export class OAuthInvalidResponse extends Data.TaggedError("OAuthInvalidResponse")<{
59 endpoint: string;
60 status: number;
61 reason: string;
62 }> {
63 override get message(): string {
64 return `Unexpected response from ${this.endpoint} (HTTP ${this.status}): ${this.reason}`;
65 }
66 }
67
68 /** Every way a request to the authorization server can fail. */
69 export type OAuthRequestError =
70 | OAuthError
71 | OAuthNetworkError
72 | OAuthServerUnavailable
73 | OAuthInvalidResponse;
74
75 /** The client spec lacks the endpoints/URIs a flow needs. */
76 export class UnsupportedOAuthFlowError extends Data.TaggedError("UnsupportedOAuthFlowError")<{
77 flow: "browser" | "device";
78 }> {
79 override get message(): string {
80 return `This OAuth client is not configured for the ${this.flow} flow.`;
81 }
82 }
83
84 /** A callback redirect or pasted code lacks a code or carries the wrong state. */
85 export class OAuthCallbackError extends Data.TaggedError("OAuthCallbackError")<{
86 reason: "missing_code" | "state_mismatch";
87 }> {
88 override get message(): string {
89 return this.reason === "missing_code"
90 ? "The authorization code is missing."
91 : "The authorization state does not match.";
92 }
93 }
94
95 /** No browser callback arrived within 5 minutes. */
96 export class OAuthCallbackTimeout extends Data.TaggedError("OAuthCallbackTimeout") {
97 override get message(): string {
98 return "The authorization process timed out.";
99 }
100 }
101
102 /**
103 * The device authorization endpoint pointed the user at a URL outside the
104 * authorization server's host (RFC 8628 §5.4, remote phishing).
105 */
106 export class UntrustedVerificationUriError extends Data.TaggedError(
107 "UntrustedVerificationUriError",
108 )<{
109 url: string;
110 expectedHost: string;
111 }> {
112 override get message(): string {
113 return `Refusing verification URL outside ${this.expectedHost}: ${this.url}`;
114 }
115 }
116
117 /** The user denied the device authorization. */
118 export class DeviceAuthorizationDenied extends Data.TaggedError("DeviceAuthorizationDenied") {
119 override get message(): string {
120 return "The device authorization was denied.";
121 }
122 }
123
124 /** The device code expired (or the 5 minute cap passed) before approval. */
125 export class DeviceAuthorizationExpired extends Data.TaggedError("DeviceAuthorizationExpired") {
126 override get message(): string {
127 return "The device authorization expired before it was approved.";
128 }
129 }
130
131 /**
132 * The local loopback callback server could not start (typically the port is
133 * already taken). Distinct from {@link CallbackServerError} so callers can
134 * fall back to manual code entry instead of failing the whole flow.
135 */
136 export class CallbackServerStartError extends Data.TaggedError("CallbackServerStartError")<{
137 message: string;
138 }> {}
139
140 /** The loopback callback server failed after it started listening. */
141 export class CallbackServerError extends Data.TaggedError("CallbackServerError")<{
142 message: string;
143 }> {}
144
145 /**
146 * On-disk shape of OAuth credentials persisted under
147 * `~/.alchemy/credentials/{profile}/<provider>-oauth.json`.
148 *
149 * `clientId` is optional because files written before the client id was
150 * recorded must still parse — {@link OAuthClient.usesCurrentClient} treats a
151 * missing id as "issued to a previous client", which triggers a clean
152 * re-login.
153 */
154 export const OAuthCredentials = Schema.Struct({
155 type: Schema.Literal("oauth"),
156 clientId: Schema.optional(Schema.String),
157 access: Schema.RedactedFromValue(Schema.String),
158 refresh: Schema.RedactedFromValue(Schema.String),
159 expires: Schema.Number,
160 scopes: Schema.String.pipe(Schema.Array, Schema.mutable),
161 });
162 export type OAuthCredentials = typeof OAuthCredentials.Type;
163
164 /**
165 * A pending OAuth 2.0 Device Authorization Grant (RFC 8628): the user
166 * approves `userCode` at `verificationUri` while the CLI polls for tokens.
167 */
168 export interface DeviceAuthorization {
169 deviceCode: string;
170 userCode: string;
171 verificationUri: string;
172 /** Verification URL with the user code pre-filled. */
173 verificationUriComplete: string;
174 /** Seconds until the device code expires. */
175 expiresIn: number;
176 /** Seconds between token polls. */
177 interval: number;
178 }
179
180 export interface Authorization {
181 url: string;
182 state: string;
183 /** PKCE verifier; present only for `auth: { kind: "pkce" }` clients. */
184 verifier?: string;
185 }
186
187 /**
188 * The provider-specific facts an OAuth flow needs. Everything else —
189 * state/PKCE generation, the loopback callback server, hosted-relay code
190 * extraction, device-code polling, token exchange, refresh, revoke — is
191 * shared.
192 *
193 * The browser (authorization-code) flow needs `endpoints.authorize`,
194 * `redirectUri` and `localCallbackUri`; the device flow needs
195 * `endpoints.deviceAuthorization`. A client that only refreshes and revokes
196 * existing grants needs neither.
197 */
198 export interface OAuthClientSpec {
199 readonly clientId: string;
200 readonly endpoints: {
201 readonly authorize?: string;
202 /** RFC 8628 device authorization endpoint. */
203 readonly deviceAuthorization?: string;
204 readonly token: string;
205 /** Providers without a revocation endpoint omit it; `revoke` then no-ops. */
206 readonly revoke?: string;
207 };
208 /** Hosted relay redirect URI registered with the OAuth application. */
209 readonly redirectUri?: string;
210 /** Loopback URI the local callback server listens on. */
211 readonly localCallbackUri?: string;
212 /**
213 * Client authentication. `pkce` for public clients; `clientSecret` for
214 * providers whose token endpoint requires client authentication for every
215 * grant (the secret ships in the CLI — same exposure posture as a public
216 * client id, rotated by cutting a release).
217 */
218 readonly auth:
219 | { readonly kind: "pkce" }
220 | { readonly kind: "clientSecret"; readonly clientSecret: Redacted.Redacted<string> };
221 /**
222 * How token-request parameters travel: URL-encoded POST body (the OAuth 2
223 * standard, default) or the query string (PlanetScale's documented form).
224 */
225 readonly tokenTransport?: "body" | "query";
226 }
227
228 export interface OAuthClient {
229 readonly clientId: string;
230 /** Whether persisted credentials were issued to this client. */
231 readonly usesCurrentClient: (credentials: { readonly clientId?: unknown }) => boolean;
232 /**
233 * Generate an authorization URL. Pass `scopes` only for providers that
234 * take them per-authorization; omit for providers whose scopes are
235 * configured on the application.
236 */
237 readonly authorize: (
238 scopes?: ReadonlyArray<string>,
239 ) => Effect.Effect<
240 Authorization,
241 UnsupportedOAuthFlowError,
242 SecureRandom.SecureRandom | Digest.Digest
243 >;
244 /**
245 * Exchange an authorization code directly. `authorization` supplies the
246 * PKCE verifier; omit for non-PKCE clients (tests, relay-less flows).
247 */
248 readonly exchange: (
249 code: string,
250 authorization?: Authorization,
251 ) => Effect.Effect<OAuthCredentials, OAuthRequestError | UnsupportedOAuthFlowError, never>;
252 /**
253 * Exchange a code copied from the hosted relay page, or extract the code
254 * from either the hosted or loopback callback URL.
255 */
256 readonly exchangeCallbackInput: (
257 input: string,
258 authorization: Authorization,
259 ) => Effect.Effect<
260 OAuthCredentials,
261 OAuthRequestError | OAuthCallbackError | UnsupportedOAuthFlowError,
262 never
263 >;
264 /**
265 * Start a local HTTP server to listen for the OAuth callback, exchange
266 * the authorization code, and return the credentials. Times out after 5
267 * minutes.
268 */
269 readonly callback: (
270 authorization: Authorization,
271 ) => Effect.Effect<
272 OAuthCredentials,
273 | OAuthRequestError
274 | OAuthCallbackError
275 | OAuthCallbackTimeout
276 | CallbackServerStartError
277 | CallbackServerError
278 | UnsupportedOAuthFlowError,
279 never
280 >;
281 /** Start an RFC 8628 device authorization for `scopes`. */
282 readonly deviceAuthorize: (
283 scopes?: ReadonlyArray<string>,
284 ) => Effect.Effect<
285 DeviceAuthorization,
286 OAuthRequestError | UnsupportedOAuthFlowError | UntrustedVerificationUriError,
287 never
288 >;
289 /**
290 * Poll the token endpoint until the user approves (or denies) the device
291 * authorization. Times out when the device code expires, capped at 5
292 * minutes.
293 */
294 readonly deviceToken: (
295 authorization: DeviceAuthorization,
296 ) => Effect.Effect<
297 OAuthCredentials,
298 OAuthRequestError | DeviceAuthorizationDenied | DeviceAuthorizationExpired,
299 never
300 >;
301 /** Refresh expired OAuth credentials with the stored refresh token. */
302 readonly refresh: (
303 credentials: OAuthCredentials,
304 ) => Effect.Effect<OAuthCredentials, OAuthRequestError, never>;
305 /** Revoke the refresh token; no-op when the spec has no revoke endpoint. */
306 readonly revoke: (credentials: OAuthCredentials) => Effect.Effect<void, OAuthNetworkError>;
307 }
308
309 const randomText = Effect.fn(function* (length: number) {
310 const random = yield* SecureRandom.SecureRandom;
311 return Base64Url.encode(yield* random.randomBytes(length));
312 });
313
314 const generatePKCE = Effect.fn(function* (length = 96) {
315 const digest = yield* Digest.Digest;
316 const verifier = yield* randomText(length);
317 const challenge = yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier));
318 return { verifier, challenge: Base64Url.encode(challenge) };
319 });
320
321 const TokenResponse = Schema.Struct({
322 access_token: Schema.String,
323 refresh_token: Schema.optional(Schema.String),
324 expires_in: Schema.Number,
325 scope: Schema.optional(Schema.String),
326 });
327
328 const DeviceAuthorizationResponse = Schema.Struct({
329 device_code: Schema.String,
330 user_code: Schema.String,
331 verification_uri: Schema.String,
332 verification_uri_complete: Schema.optional(Schema.String),
333 expires_in: Schema.Number,
334 interval: Schema.optional(Schema.Number),
335 });
336
337 const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
338
339 const TokenErrorResponse = Schema.Struct({
340 error: Schema.String,
341 error_description: Schema.optional(Schema.String),
342 });
343
344 export const makeOAuthClient = (spec: OAuthClientSpec): OAuthClient => {
345 const provideHttp = <A, E>(effect: Effect.Effect<A, E, HttpClient.HttpClient>) =>
346 effect.pipe(Effect.provide(FetchHttpClient.layer));
347 const clientAuthParams = (): Record<string, string> =>
348 spec.auth.kind === "clientSecret"
349 ? { client_secret: Redacted.value(spec.auth.clientSecret) }
350 : {};
351
352 /**
353 * POST form params to an authorization-server endpoint and decode the 2xx
354 * body with `success`. Non-2xx responses surface the server's OAuth error
355 * code as {@link OAuthError}.
356 */
357 const postForm = Effect.fn(function* <A>(
358 endpoint: string,
359 params: Record<string, string>,
360 success: Schema.ConstraintDecoder<A, never>,
361 transport: "body" | "query" = "body",
362 ) {
363 const client = yield* HttpClient.HttpClient;
364 const request = HttpClientRequest.post(endpoint).pipe(
365 HttpClientRequest.setHeader("Accept", "application/json"),
366 transport === "query"
367 ? HttpClientRequest.setUrlParams(params)
368 : HttpClientRequest.bodyUrlParams(params),
369 );
370 const response = yield* client
371 .execute(request)
372 .pipe(Effect.mapError((cause) => new OAuthNetworkError({ endpoint, cause })));
373 const { status } = response;
374 if (status < 200 || status >= 300) {
375 const json = yield* HttpClientResponse.schemaBodyJson(TokenErrorResponse)(response).pipe(
376 Effect.mapError(() =>
377 status === 429 || status >= 500
378 ? new OAuthServerUnavailable({ endpoint, status })
379 : new OAuthInvalidResponse({ endpoint, status, reason: "no OAuth error body" }),
380 ),
381 );
382 return yield* new OAuthError({
383 error: json.error,
384 errorDescription: json.error_description ?? `HTTP ${status}`,
385 });
386 }
387 return yield* HttpClientResponse.schemaBodyJson(success)(response).pipe(
388 Effect.mapError(
389 () => new OAuthInvalidResponse({ endpoint, status, reason: "unexpected response body" }),
390 ),
391 );
392 });
393
394 const tokenRequest = Effect.fn(function* (
395 params: Record<string, string>,
396 previous?: OAuthCredentials,
397 ) {
398 const endpoint = spec.endpoints.token;
399 const json = yield* postForm(endpoint, params, TokenResponse, spec.tokenTransport);
400 const refresh =
401 json.refresh_token === undefined ? previous?.refresh : Redacted.make(json.refresh_token);
402 if (!refresh) {
403 return yield* new OAuthInvalidResponse({
404 endpoint,
405 status: 200,
406 reason: "no refresh token was returned for this authorization",
407 });
408 }
409 const now = yield* Clock.currentTimeMillis;
410 return {
411 type: "oauth" as const,
412 clientId: spec.clientId,
413 access: Redacted.make(json.access_token),
414 refresh,
415 expires: now + json.expires_in * 1000,
416 scopes: json.scope?.split(" ") ?? previous?.scopes ?? [],
417 } satisfies OAuthCredentials;
418 });
419
420 const browserSpec = Effect.suspend(() => {
421 const { redirectUri, localCallbackUri } = spec;
422 const authorizeEndpoint = spec.endpoints.authorize;
423 return redirectUri === undefined ||
424 localCallbackUri === undefined ||
425 authorizeEndpoint === undefined
426 ? Effect.fail(new UnsupportedOAuthFlowError({ flow: "browser" }))
427 : Effect.succeed({ redirectUri, localCallbackUri, authorizeEndpoint });
428 });
429
430 const authorize = Effect.fn(function* (scopes?: ReadonlyArray<string>) {
431 const { authorizeEndpoint, redirectUri } = yield* browserSpec;
432 const state = yield* randomText(32);
433 const url = new URL(authorizeEndpoint);
434 url.searchParams.set("client_id", spec.clientId);
435 url.searchParams.set("redirect_uri", redirectUri);
436 url.searchParams.set("response_type", "code");
437 if (scopes !== undefined) {
438 url.searchParams.set("scope", scopes.join(" "));
439 }
440 url.searchParams.set("state", state);
441 if (spec.auth.kind === "pkce") {
442 const pkce = yield* generatePKCE();
443 url.searchParams.set("code_challenge", pkce.challenge);
444 url.searchParams.set("code_challenge_method", "S256");
445 return { url: url.toString(), state, verifier: pkce.verifier };
446 }
447 return { url: url.toString(), state };
448 });
449
450 const exchange = Effect.fn(function* (code: string, authorization?: Authorization) {
451 const { redirectUri } = yield* browserSpec;
452 return yield* tokenRequest({
453 grant_type: "authorization_code",
454 code,
455 client_id: spec.clientId,
456 redirect_uri: redirectUri,
457 ...clientAuthParams(),
458 ...(authorization?.verifier === undefined ? {} : { code_verifier: authorization.verifier }),
459 });
460 });
461
462 const deviceAuthorize = Effect.fn(function* (scopes?: ReadonlyArray<string>) {
463 const endpoint = spec.endpoints.deviceAuthorization;
464 if (endpoint === undefined) return yield* new UnsupportedOAuthFlowError({ flow: "device" });
465 const json = yield* postForm(
466 endpoint,
467 {
468 client_id: spec.clientId,
469 ...(scopes === undefined ? {} : { scope: scopes.join(" ") }),
470 ...clientAuthParams(),
471 },
472 DeviceAuthorizationResponse,
473 );
474 // The server picks where the user is sent to type their code; only
475 // trust https URLs on the authorization server's own host (RFC 8628
476 // §5.4, remote phishing).
477 const expectedHost = new URL(endpoint).host;
478 const trustedUrl = (value: string) => {
479 const untrusted = () => new UntrustedVerificationUriError({ url: value, expectedHost });
480 return Url.fromString(value).pipe(
481 Result.mapError(untrusted),
482 Result.filterOrFail(
483 (url) =>
484 url.protocol === "https:" &&
485 url.username === "" &&
486 url.password === "" &&
487 url.host === expectedHost,
488 untrusted,
489 ),
490 Effect.fromResult,
491 );
492 };
493 const verificationUri = yield* trustedUrl(json.verification_uri);
494 const complete =
495 json.verification_uri_complete === undefined
496 ? Url.mutate(verificationUri, (url) => url.searchParams.set("user_code", json.user_code))
497 : yield* trustedUrl(json.verification_uri_complete);
498 return {
499 deviceCode: json.device_code,
500 userCode: json.user_code,
501 verificationUri: json.verification_uri,
502 verificationUriComplete: complete.toString(),
503 expiresIn: json.expires_in,
504 interval: json.interval ?? 5,
505 } satisfies DeviceAuthorization;
506 });
507
508 const deviceToken = Effect.fn(function* (authorization: DeviceAuthorization) {
509 let interval = Math.max(authorization.interval, 1);
510 // The delay is read on every recurrence, so slow_down's bump applies to
511 // all later polls.
512 const schedule = Schedule.forever.pipe(
513 Schedule.modifyDelay(() => Effect.sync(() => Duration.seconds(interval))),
514 );
515 return yield* tokenRequest({
516 grant_type: DEVICE_CODE_GRANT,
517 device_code: authorization.deviceCode,
518 client_id: spec.clientId,
519 ...clientAuthParams(),
520 }).pipe(
521 Effect.tapError((e) =>
522 Effect.sync(() => {
523 // RFC 8628 §3.5: slow_down adds 5 seconds to every later poll.
524 if (e._tag === "OAuthError" && e.error === "slow_down") interval += 5;
525 }),
526 ),
527 Effect.retry({
528 schedule,
529 // Transient failures, or RFC 8628 §3.5 codes meaning the user has
530 // not decided yet.
531 while: (e) =>
532 ["OAuthNetworkError", "OAuthServerUnavailable"].includes(e._tag) ||
533 (e._tag === "OAuthError" &&
534 ["authorization_pending", "slow_down", "temporarily_unavailable"].includes(e.error)),
535 }),
536 Effect.catchTag("OAuthError", (e) =>
537 Effect.fail(
538 Match.value(e.error).pipe(
539 Match.when("access_denied", () => new DeviceAuthorizationDenied()),
540 Match.when("expired_token", () => new DeviceAuthorizationExpired()),
541 Match.orElse(() => e),
542 ),
543 ),
544 ),
545 Effect.timeoutOrElse({
546 duration: Duration.seconds(Math.min(authorization.expiresIn, 300)),
547 orElse: () => Effect.fail(new DeviceAuthorizationExpired()),
548 }),
549 );
550 });
551
552 const refresh = Effect.fn(function (credentials: OAuthCredentials) {
553 return tokenRequest(
554 {
555 grant_type: "refresh_token",
556 refresh_token: Redacted.value(credentials.refresh),
557 client_id: spec.clientId,
558 ...clientAuthParams(),
559 },
560 credentials,
561 );
562 });
563
564 const revoke = Effect.fn(function* (credentials: OAuthCredentials) {
565 const endpoint = spec.endpoints.revoke;
566 if (endpoint === undefined) return;
567 const client = yield* HttpClient.HttpClient;
568 const request = HttpClientRequest.post(endpoint).pipe(
569 HttpClientRequest.setHeader("Accept", "application/json"),
570 HttpClientRequest.bodyUrlParams({
571 token: Redacted.value(credentials.refresh),
572 token_type_hint: "refresh_token",
573 client_id: spec.clientId,
574 ...clientAuthParams(),
575 }),
576 );
577 yield* client.execute(request).pipe(
578 Effect.mapError((cause) => new OAuthNetworkError({ endpoint, cause })),
579 Effect.asVoid,
580 );
581 });
582
583 const exchangeCallbackInput = Effect.fn(function* (input: string, authorization: Authorization) {
584 const value = input.trim();
585 // A full callback URL carries code + state; a code copied from the hosted
586 // relay page is `code#state`.
587 const { code, state } = Url.fromString(value).pipe(
588 Result.map((url) => ({
589 code: url.searchParams.get("code") ?? "",
590 state: url.searchParams.get("state"),
591 })),
592 Result.getOrElse(() => {
593 const separator = value.lastIndexOf("#");
594 return separator >= 0
595 ? { code: value.slice(0, separator), state: value.slice(separator + 1) }
596 : { code: value, state: null };
597 }),
598 );
599
600 if (!code) {
601 return yield* new OAuthCallbackError({ reason: "missing_code" });
602 }
603 if (state !== null && state !== authorization.state) {
604 return yield* new OAuthCallbackError({ reason: "state_mismatch" });
605 }
606 return yield* exchange(code, authorization);
607 });
608
609 type CallbackFailure =
610 | OAuthRequestError
611 | OAuthCallbackError
612 | CallbackServerStartError
613 | CallbackServerError
614 | UnsupportedOAuthFlowError;
615
616 const callback = Effect.fn(function* (authorization: Authorization) {
617 const { localCallbackUri, redirectUri } = yield* browserSpec;
618 const { pathname, port, protocol } = new URL(localCallbackUri);
619 const listenPort = port === "" ? (protocol === "https:" ? 443 : 80) : Number(port);
620 const listen = Effect.callback<OAuthCredentials, CallbackFailure, HttpClient.HttpClient>(
621 (resume) => {
622 // The handler can run more than once (browser retries, extra tabs);
623 // resume exactly once and ignore everything after.
624 let settled = false;
625 const resolveOnce = (
626 effect: Effect.Effect<OAuthCredentials, CallbackFailure, HttpClient.HttpClient>,
627 ) => {
628 if (settled) return;
629 settled = true;
630 resume(effect);
631 };
632 const server = http.createServer((req, res) => {
633 const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
634
635 if (url.pathname === "/auth/ping") {
636 res.writeHead(req.method === "OPTIONS" ? 204 : 200, {
637 "Access-Control-Allow-Origin": new URL(redirectUri).origin,
638 "Access-Control-Allow-Methods": "GET, OPTIONS",
639 "Access-Control-Allow-Private-Network": "true",
640 "Cache-Control": "no-store",
641 });
642 res.end();
643 return;
644 }
645
646 if (url.pathname !== pathname) {
647 res.statusCode = 404;
648 res.end("Not Found");
649 return;
650 }
651
652 const error = url.searchParams.get("error");
653 const errorDescription = url.searchParams.get("error_description");
654 if (error) {
655 res.writeHead(302, { Location: AUTH_ERROR_URL });
656 res.end();
657 new OAuthError({
658 error,
659 errorDescription: errorDescription ?? "An unknown error occurred.",
660 }).pipe(Effect.fail, resolveOnce);
661 return;
662 }
663
664 const code = url.searchParams.get("code");
665 const state = url.searchParams.get("state");
666 if (!code || !state) {
667 res.writeHead(302, { Location: AUTH_ERROR_URL });
668 res.end();
669 new OAuthCallbackError({ reason: "missing_code" }).pipe(Effect.fail, resolveOnce);
670 return;
671 }
672
673 if (state !== authorization.state) {
674 res.writeHead(302, { Location: AUTH_ERROR_URL });
675 res.end();
676 new OAuthCallbackError({ reason: "state_mismatch" }).pipe(Effect.fail, resolveOnce);
677 return;
678 }
679 resolveOnce(
680 exchange(code, authorization).pipe(
681 Effect.tap(() =>
682 Effect.sync(() => {
683 res.writeHead(302, { Location: AUTH_SUCCESS_URL });
684 res.end();
685 }),
686 ),
687 Effect.tapError(() =>
688 Effect.sync(() => {
689 res.writeHead(302, { Location: AUTH_ERROR_URL });
690 res.end();
691 }),
692 ),
693 ),
694 );
695 });
696
697 server.on("error", (err) => {
698 (server.listening
699 ? new CallbackServerError({ message: `Callback server failed: ${err.message}` })
700 : new CallbackServerStartError({
701 message: `Failed to start callback server: ${err.message}`,
702 })
703 ).pipe(Effect.fail, resolveOnce);
704 });
705
706 server.listen(listenPort, "127.0.0.1");
707 return Effect.sync(() => {
708 server.close();
709 // `close` only stops new connections — a keep-alive browser
710 // connection would otherwise hold the process open until its
711 // socket timeout after login completes.
712 server.closeAllConnections();
713 });
714 },
715 );
716 return yield* listen.pipe(
717 Effect.timeoutOrElse({
718 duration: "5 minutes",
719 orElse: () => Effect.fail(new OAuthCallbackTimeout()),
720 }),
721 );
722 });
723
724 return {
725 clientId: spec.clientId,
726 usesCurrentClient: (credentials) => credentials.clientId === spec.clientId,
727 authorize,
728 exchange: (...args) => provideHttp(exchange(...args)),
729 exchangeCallbackInput: (...args) => provideHttp(exchangeCallbackInput(...args)),
730 callback: (authorization) => provideHttp(callback(authorization)),
731 deviceAuthorize: (scopes) => provideHttp(deviceAuthorize(scopes)),
732 deviceToken: (authorization) => provideHttp(deviceToken(authorization)),
733 refresh: (credentials) => provideHttp(refresh(credentials)),
734 revoke: (credentials) => provideHttp(revoke(credentials)),
735 };
736 };