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

ProviderAuthService.ts

348 lines13.8 KB

1import {
2 ProviderSetupError,
3 type ChatGptReconnectProfile,
4 type ChatGptTransferredProfile,
5 type ProviderAuthRespondInput,
6 type ProviderAuthStartInput,
7 type ProviderAuthState,
8 type ProviderInstanceId,
9 type ProviderSessionId,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import type * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as Semaphore from "effect/Semaphore";
17​
18import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
19import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
20import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
21​
22export interface ProviderAuthController {
23 /** Equal keys mean these instances share credentials on this environment. */
24 readonly credentialBinding?: { readonly owner: "provider" | "t3"; readonly key: string };
25 readonly reconnectProfile?: (
26 methodId: string,
27 ) => Effect.Effect<ChatGptReconnectProfile | null, ProviderSetupError>;
28 readonly importProfile?: (
29 profile: ChatGptTransferredProfile,
30 stopSessions: Effect.Effect<void, ProviderSetupError>,
31 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
32 readonly adoptCredentials?: (
33 update: Effect.Effect<void, ProviderSetupError>,
34 stopSessions: Effect.Effect<void, ProviderSetupError>,
35 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
36 readonly isChangingCredentials?: Effect.Effect<boolean>;
37 readonly invalidate?: Effect.Effect<void>;
38 readonly refreshMethods?: Effect.Effect<void>;
39 readonly withAccess?: <A, E, R>(
40 task: Effect.Effect<A, E, R>,
41 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
42 readonly start: (
43 ownerSessionId: string,
44 stopSessions?: Effect.Effect<void, ProviderSetupError>,
45 methodId?: string,
46 returnUrl?: string,
47 callbackMode?: "server" | "client",
48 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
49 readonly complete: (
50 ownerSessionId: string,
51 input: { readonly flowId: string; readonly callbackUrl: string },
52 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
53 readonly cancel: (
54 ownerSessionId: string,
55 flowId: string,
56 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
57 readonly respond?: (
58 ownerSessionId: string,
59 input: ProviderAuthRespondInput,
60 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
61 /** The controller closes process admission before it stops routed sessions. */
62 readonly logout: (
63 stopSessions: Effect.Effect<void, ProviderSetupError>,
64 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
65 readonly subscribe: (ownerSessionId: string) => Stream.Stream<ProviderAuthState>;
66 readonly isLogoutPrompt?: (text: string, hasAttachments: boolean) => boolean;
68​
69interface ProviderAuthTarget {
70 readonly instanceId: ProviderInstanceId;
72​
73export class ProviderAuthService extends Context.Service<
74 ProviderAuthService,
75 {
76 readonly reconnectProfile: (
77 input: ProviderAuthTarget & { methodId: string },
78 ) => Effect.Effect<ChatGptReconnectProfile | null, ProviderSetupError>;
79 readonly importProfile: (
80 input: ProviderAuthTarget & { profile: ChatGptTransferredProfile },
81 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
82 readonly start: (
83 input: ProviderAuthStartInput,
84 ownerSessionId: string,
85 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
86 readonly complete: (
87 input: ProviderAuthTarget & { readonly flowId: string; readonly callbackUrl: string },
88 ownerSessionId: string,
89 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
90 readonly respond: (
91 input: ProviderAuthRespondInput,
92 ownerSessionId: string,
93 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
94 readonly cancel: (
95 input: ProviderAuthTarget & { readonly flowId: string },
96 ownerSessionId: string,
97 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
98 readonly logout: (
99 input: ProviderAuthTarget,
100 ) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
101 readonly subscribe: (
102 input: ProviderAuthTarget,
103 ownerSessionId: string,
104 ) => Stream.Stream<ProviderAuthState, ProviderSetupError>;
105 readonly tryHandlePromptCommand: (
106 input: ProviderAuthTarget & { readonly text: string; readonly hasAttachments: boolean },
107 ) => Effect.Effect<boolean, ProviderSetupError>;
108 }
109>()("t3/provider/ProviderAuthService") {}
110​
111export const makeProviderAuthService = Effect.gen(function* () {
112 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
113 const projections = yield* ProjectionStore.ProjectionStoreV2;
114 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
115 const credentialChanges = yield* Semaphore.make(1);
116​
117 const getController = Effect.fn("ProviderAuthService.getController")(function* (
118 instanceId: ProviderInstanceId,
119 operation: string,
120 ) {
121 const instance = yield* registry.getInstance(instanceId);
122 if (!instance?.auth) {
123 return yield* new ProviderSetupError({
124 instanceId,
125 operation,
126 detail: instance
127 ? "This provider does not support sign-in in T3 Code."
128 : "This provider instance is no longer available.",
129 });
130 }
131 return instance.auth;
132 });
133​
134 // Native sessions may still belong to the previous provider after the
135 // selected model changes. Read session bindings, not the selected model,
136 // when invalidating credentials for sign-in or sign-out.
137 const stopSessions = Effect.fn("ProviderAuthService.stopSessions")(function* (
138 instanceId: ProviderInstanceId,
139 binding: ProviderAuthController["credentialBinding"],
140 ) {
141 const failure = (detail: string) =>
142 new ProviderSetupError({ instanceId, operation: "stopSessions", detail });
143 const affectedIds = new Set([
144 instanceId,
145 ...(binding === undefined
146 ? []
147 : (yield* registry.listInstances)
148 .filter(
149 (instance) =>
150 instance.auth?.credentialBinding?.key === binding.key &&
151 instance.auth.credentialBinding.owner === binding.owner,
152 )
153 .map((instance) => instance.instanceId)),
154 ]);
155 const threadIds = yield* projections
156 .getRecoveryThreadIds("runtime")
157 .pipe(
158 Effect.mapError(() => failure("Could not read the provider's active sessions. Try again.")),
159 );
160 const released = new Set<ProviderSessionId>();
161 yield* Effect.forEach(
162 threadIds,
163 (threadId) =>
164 projections.getThreadRecords(threadId, ["providerSessions"]).pipe(
165 Effect.flatMap((projection) =>
166 Effect.forEach(
167 projection.providerSessions.filter(
168 (session) =>
169 affectedIds.has(session.providerInstanceId) &&
170 session.status !== "stopped" &&
171 session.status !== "error" &&
172 !released.has(session.id),
173 ),
174 (session) =>
175 Effect.gen(function* () {
176 if (session.providerInstanceId !== instanceId) {
177 const current = yield* registry.getInstance(session.providerInstanceId);
178 if (
179 !binding ||
180 current?.auth?.credentialBinding?.key !== binding.key ||
181 current.auth.credentialBinding.owner !== binding.owner
182 )
183 return;
184 }
185 yield* providerSessions
186 .release({
187 providerSessionId: session.id,
188 reason: "manual_shutdown",
189 detail: "Provider sign-in changed.",
190 })
191 .pipe(Effect.tap(() => Effect.sync(() => released.add(session.id))));
192 }),
193 { discard: true },
194 ),
195 ),
196 Effect.mapError(() =>
197 failure("Could not stop all sessions for this provider. Try again."),
198 ),
199 ),
200 { discard: true },
201 );
202 if (binding) {
203 yield* Effect.forEach(
204 (yield* registry.listInstances).filter(
205 (instance) =>
206 instance.instanceId !== instanceId &&
207 affectedIds.has(instance.instanceId) &&
208 instance.auth?.credentialBinding?.key === binding.key &&
209 instance.auth.credentialBinding.owner === binding.owner,
210 ),
211 (instance) => instance.auth?.invalidate ?? Effect.void,
212 { discard: true },
213 );
214 }
215 });
216​
217 const checkSharedBinding = Effect.fnUntraced(function* (
218 instanceId: ProviderInstanceId,
219 operation: "start" | "logout",
220 auth: ProviderAuthController,
221 ) {
222 const binding = auth.credentialBinding;
223 if (!binding) return;
224 const instances = yield* registry.listInstances;
225 for (const instance of instances) {
226 if (
227 instance.instanceId !== instanceId &&
228 instance.auth?.credentialBinding?.key === binding.key &&
229 instance.auth.credentialBinding.owner === binding.owner &&
230 instance.auth.isChangingCredentials &&
231 (yield* instance.auth.isChangingCredentials)
232 ) {
233 return yield* new ProviderSetupError({
234 instanceId,
235 operation,
236 detail:
237 "Another provider instance is changing this shared sign-in. Finish or cancel it first.",
238 });
239 }
240 }
241 });
242​
243 return ProviderAuthService.of({
244 reconnectProfile: Effect.fnUntraced(function* (input) {
245 const auth = yield* getController(input.instanceId, "export");
246 if (!auth.reconnectProfile)
247 return yield* new ProviderSetupError({
248 instanceId: input.instanceId,
249 operation: "export",
250 detail: "This provider does not support ChatGPT profile transfer.",
251 });
252 return yield* auth.reconnectProfile(input.methodId);
253 }),
254 importProfile: (input) =>
255 credentialChanges.withPermit(
256 Effect.gen(function* () {
257 const auth = yield* getController(input.instanceId, "import");
258 yield* checkSharedBinding(input.instanceId, "start", auth);
259 if (!auth.importProfile)
260 return yield* new ProviderSetupError({
261 instanceId: input.instanceId,
262 operation: "import",
263 detail: "This provider does not support ChatGPT profile transfer.",
264 });
265 return yield* auth.importProfile(
266 input.profile,
267 stopSessions(input.instanceId, auth.credentialBinding),
268 );
269 }),
270 ),
271 start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {
272 return yield* credentialChanges.withPermit(
273 Effect.gen(function* () {
274 const auth = yield* getController(input.instanceId, "start");
275 yield* checkSharedBinding(input.instanceId, "start", auth);
276 return yield* auth.start(
277 ownerSessionId,
278 stopSessions(input.instanceId, auth.credentialBinding),
279 input.methodId,
280 input.returnUrl,
281 input.callbackMode,
282 );
283 }),
284 );
285 }),
286 respond: Effect.fn("ProviderAuthService.respond")(function* (input, ownerSessionId) {
287 const auth = yield* getController(input.instanceId, "respond");
288 if (!auth.respond) {
289 return yield* new ProviderSetupError({
290 instanceId: input.instanceId,
291 operation: "respond",
292 detail: "This provider does not accept this sign-in interaction.",
293 });
294 }
295 return yield* auth.respond(ownerSessionId, input);
296 }),
297 complete: Effect.fn("ProviderAuthService.complete")(function* (input, ownerSessionId) {
298 const auth = yield* getController(input.instanceId, "complete");
299 return yield* auth.complete(ownerSessionId, input);
300 }),
301 cancel: Effect.fn("ProviderAuthService.cancel")(function* (input, ownerSessionId) {
302 const auth = yield* getController(input.instanceId, "cancel");
303 return yield* auth.cancel(ownerSessionId, input.flowId);
304 }),
305 logout: Effect.fn("ProviderAuthService.logout")(function* (input) {
306 return yield* credentialChanges.withPermit(
307 Effect.gen(function* () {
308 const auth = yield* getController(input.instanceId, "logout");
309 yield* checkSharedBinding(input.instanceId, "logout", auth);
310 return yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
311 }),
312 );
313 }),
314 subscribe: (input, ownerSessionId) =>
315 Effect.gen(function* () {
316 const changes = yield* registry.subscribeChanges;
317 const initial = yield* getController(input.instanceId, "subscribe");
318 return Stream.concat(
319 Stream.succeed(initial),
320 Stream.fromSubscription(changes).pipe(
321 Stream.mapEffect(() => getController(input.instanceId, "subscribe")),
322 ),
323 ).pipe(
324 Stream.changesWith((previous, next) => previous === next),
325 Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),
326 );
327 }).pipe(Stream.unwrap),
328 tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(
329 function* (input) {
330 const instance = yield* registry.getInstance(input.instanceId);
331 if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) {
332 return false;
333 }
334 return yield* credentialChanges.withPermit(
335 Effect.gen(function* () {
336 const auth = yield* getController(input.instanceId, "logout");
337 if (!auth.isLogoutPrompt?.(input.text, input.hasAttachments)) return false;
338 yield* checkSharedBinding(input.instanceId, "logout", auth);
339 yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
340 return true;
341 }),
342 );
343 },
344 ),
345 });
346});
347​
348export const layer = Layer.effect(ProviderAuthService, makeProviderAuthService);