Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexAuthCallback.ts

59 lines2.3 KB

1import { ProviderSetupError, type CodexAuthCallbackInput } from "@t3tools/contracts";
2import { receiveCodexAuthCallback } from "@t3tools/shared/codexAuthCallback";
3import { codexAuthorizationRequest } from "@t3tools/shared/codexAuthHandoff";
4import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
5import { isLoopbackHost } from "@t3tools/shared/preview";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Stream from "effect/Stream";
10​
11export function subscribeCodexAuthCallback(input: CodexAuthCallbackInput) {
12 const failure = (error: unknown) =>
13 new ProviderSetupError({
14 instanceId: input.instanceId,
15 operation: "callback",
16 detail:
17 error instanceof Error ? error.message : "Could not receive sign-in on this computer.",
18 });
19 return Stream.unwrap(
20 Effect.gen(function* () {
21 const destination = yield* Effect.try({
22 try: () => {
23 codexAuthorizationRequest(input.authorizationUrl);
24 const destination = providerAuthReturnUrl(input.returnUrl);
25 if (!destination || !isLoopbackHost(new URL(destination).hostname))
26 throw new Error("The local sign-in receiver needs a local T3 Code return address.");
27 return destination;
28 },
29 catch: failure,
30 });
31 const ready = yield* Deferred.make<void, ProviderSetupError>();
32 const runSync = Effect.runSyncWith(yield* Effect.context<never>());
33 const callback = yield* Effect.tryPromise({
34 try: (signal) =>
35 receiveCodexAuthCallback(
36 input.authorizationUrl,
37 async () => {
38 runSync(Deferred.succeed(ready, undefined));
39 return true;
40 },
41 () => destination,
42 signal,
43 ),
44 catch: failure,
45 }).pipe(
46 Effect.tapError((error) => Deferred.fail(ready, error)),
47 Effect.forkScoped,
48 );
49 return Stream.fromEffect(Deferred.await(ready)).pipe(
50 Stream.map(() => ({ phase: "ready" as const })),
51 Stream.concat(
52 Stream.fromEffect(Fiber.join(callback)).pipe(
53 Stream.map((callbackUrl) => ({ phase: "finished" as const, callbackUrl })),
54 ),
55 ),
56 );
57 }),
58 );