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

ProviderAuthService.ts

256 lines10.1 KB

1import {
2 ProviderSetupError,
3 type ProviderInstanceId,
4 type ProviderSessionId,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Stream from "effect/Stream";
9import * as Semaphore from "effect/Semaphore";
10​
11import * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts";
12import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
13import * as ProviderAuthService from "../Services/ProviderAuthService.ts";
14import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
15​
16export const makeProviderAuthService = Effect.gen(function* () {
17 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
18 const projections = yield* ProjectionStore.ProjectionStoreV2;
19 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
20 const credentialChanges = yield* Semaphore.make(1);
21​
22 const getController = Effect.fn("ProviderAuthService.getController")(function* (
23 instanceId: ProviderInstanceId,
24 operation: string,
25 ) {
26 const instance = yield* registry.getInstance(instanceId);
27 if (!instance?.auth) {
28 return yield* new ProviderSetupError({
29 instanceId,
30 operation,
31 detail: instance
32 ? "This provider does not support sign-in in T3 Code."
33 : "This provider instance is no longer available.",
34 });
35 }
36 return instance.auth;
37 });
38​
39 // Native sessions may still belong to the previous provider after the
40 // selected model changes. Read session bindings, not the selected model,
41 // when invalidating credentials for sign-in or sign-out.
42 const stopSessions = Effect.fn("ProviderAuthService.stopSessions")(function* (
43 instanceId: ProviderInstanceId,
44 binding: ProviderAuthService.ProviderAuthController["credentialBinding"],
45 ) {
46 const failure = (detail: string) =>
47 new ProviderSetupError({ instanceId, operation: "stopSessions", detail });
48 const affectedIds = new Set([
49 instanceId,
50 ...(binding === undefined
51 ? []
52 : (yield* registry.listInstances)
53 .filter(
54 (instance) =>
55 instance.auth?.credentialBinding?.key === binding.key &&
56 instance.auth.credentialBinding.owner === binding.owner,
57 )
58 .map((instance) => instance.instanceId)),
59 ]);
60 const threadIds = yield* projections
61 .getRecoveryThreadIds("runtime")
62 .pipe(
63 Effect.mapError(() => failure("Could not read the provider's active sessions. Try again.")),
64 );
65 const released = new Set<ProviderSessionId>();
66 yield* Effect.forEach(
67 threadIds,
68 (threadId) =>
69 projections.getThreadRecords(threadId, ["providerSessions"]).pipe(
70 Effect.flatMap((projection) =>
71 Effect.forEach(
72 projection.providerSessions.filter(
73 (session) =>
74 affectedIds.has(session.providerInstanceId) &&
75 session.status !== "stopped" &&
76 session.status !== "error" &&
77 !released.has(session.id),
78 ),
79 (session) =>
80 Effect.gen(function* () {
81 if (session.providerInstanceId !== instanceId) {
82 const current = yield* registry.getInstance(session.providerInstanceId);
83 if (
84 !binding ||
85 current?.auth?.credentialBinding?.key !== binding.key ||
86 current.auth.credentialBinding.owner !== binding.owner
87 )
88 return;
89 }
90 yield* providerSessions
91 .release({
92 providerSessionId: session.id,
93 reason: "manual_shutdown",
94 detail: "Provider sign-in changed.",
95 })
96 .pipe(Effect.tap(() => Effect.sync(() => released.add(session.id))));
97 }),
98 { discard: true },
99 ),
100 ),
101 Effect.mapError(() =>
102 failure("Could not stop all sessions for this provider. Try again."),
103 ),
104 ),
105 { discard: true },
106 );
107 if (binding) {
108 yield* Effect.forEach(
109 (yield* registry.listInstances).filter(
110 (instance) =>
111 instance.instanceId !== instanceId &&
112 affectedIds.has(instance.instanceId) &&
113 instance.auth?.credentialBinding?.key === binding.key &&
114 instance.auth.credentialBinding.owner === binding.owner,
115 ),
116 (instance) => instance.auth?.invalidate ?? Effect.void,
117 { discard: true },
118 );
119 }
120 });
121​
122 const checkSharedBinding = Effect.fnUntraced(function* (
123 instanceId: ProviderInstanceId,
124 operation: "start" | "logout",
125 auth: ProviderAuthService.ProviderAuthController,
126 ) {
127 const binding = auth.credentialBinding;
128 if (!binding) return;
129 const instances = yield* registry.listInstances;
130 for (const instance of instances) {
131 if (
132 instance.instanceId !== instanceId &&
133 instance.auth?.credentialBinding?.key === binding.key &&
134 instance.auth.credentialBinding.owner === binding.owner &&
135 instance.auth.isChangingCredentials &&
136 (yield* instance.auth.isChangingCredentials)
137 ) {
138 return yield* new ProviderSetupError({
139 instanceId,
140 operation,
141 detail:
142 "Another provider instance is changing this shared sign-in. Finish or cancel it first.",
143 });
144 }
145 }
146 });
147​
148 return ProviderAuthService.ProviderAuthService.of({
149 reconnectProfile: Effect.fnUntraced(function* (input) {
150 const auth = yield* getController(input.instanceId, "export");
151 if (!auth.reconnectProfile)
152 return yield* new ProviderSetupError({
153 instanceId: input.instanceId,
154 operation: "export",
155 detail: "This provider does not support ChatGPT profile transfer.",
156 });
157 return yield* auth.reconnectProfile(input.methodId);
158 }),
159 importProfile: (input) =>
160 credentialChanges.withPermit(
161 Effect.gen(function* () {
162 const auth = yield* getController(input.instanceId, "import");
163 yield* checkSharedBinding(input.instanceId, "start", auth);
164 if (!auth.importProfile)
165 return yield* new ProviderSetupError({
166 instanceId: input.instanceId,
167 operation: "import",
168 detail: "This provider does not support ChatGPT profile transfer.",
169 });
170 return yield* auth.importProfile(
171 input.profile,
172 stopSessions(input.instanceId, auth.credentialBinding),
173 );
174 }),
175 ),
176 start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {
177 return yield* credentialChanges.withPermit(
178 Effect.gen(function* () {
179 const auth = yield* getController(input.instanceId, "start");
180 yield* checkSharedBinding(input.instanceId, "start", auth);
181 return yield* auth.start(
182 ownerSessionId,
183 stopSessions(input.instanceId, auth.credentialBinding),
184 input.methodId,
185 input.returnUrl,
186 input.callbackMode,
187 );
188 }),
189 );
190 }),
191 respond: Effect.fn("ProviderAuthService.respond")(function* (input, ownerSessionId) {
192 const auth = yield* getController(input.instanceId, "respond");
193 if (!auth.respond) {
194 return yield* new ProviderSetupError({
195 instanceId: input.instanceId,
196 operation: "respond",
197 detail: "This provider does not accept this sign-in interaction.",
198 });
199 }
200 return yield* auth.respond(ownerSessionId, input);
201 }),
202 complete: Effect.fn("ProviderAuthService.complete")(function* (input, ownerSessionId) {
203 const auth = yield* getController(input.instanceId, "complete");
204 return yield* auth.complete(ownerSessionId, input);
205 }),
206 cancel: Effect.fn("ProviderAuthService.cancel")(function* (input, ownerSessionId) {
207 const auth = yield* getController(input.instanceId, "cancel");
208 return yield* auth.cancel(ownerSessionId, input.flowId);
209 }),
210 logout: Effect.fn("ProviderAuthService.logout")(function* (input) {
211 return yield* credentialChanges.withPermit(
212 Effect.gen(function* () {
213 const auth = yield* getController(input.instanceId, "logout");
214 yield* checkSharedBinding(input.instanceId, "logout", auth);
215 return yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
216 }),
217 );
218 }),
219 subscribe: (input, ownerSessionId) =>
220 Effect.gen(function* () {
221 const changes = yield* registry.subscribeChanges;
222 const initial = yield* getController(input.instanceId, "subscribe");
223 return Stream.concat(
224 Stream.succeed(initial),
225 Stream.fromSubscription(changes).pipe(
226 Stream.mapEffect(() => getController(input.instanceId, "subscribe")),
227 ),
228 ).pipe(
229 Stream.changesWith((previous, next) => previous === next),
230 Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),
231 );
232 }).pipe(Stream.unwrap),
233 tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(
234 function* (input) {
235 const instance = yield* registry.getInstance(input.instanceId);
236 if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) {
237 return false;
238 }
239 return yield* credentialChanges.withPermit(
240 Effect.gen(function* () {
241 const auth = yield* getController(input.instanceId, "logout");
242 if (!auth.isLogoutPrompt?.(input.text, input.hasAttachments)) return false;
243 yield* checkSharedBinding(input.instanceId, "logout", auth);
244 yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
245 return true;
246 }),
247 );
248 },
249 ),
250 });
251});
252​
253export const ProviderAuthServiceLive = Layer.effect(
254 ProviderAuthService.ProviderAuthService,
255 makeProviderAuthService,
256);