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

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