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

ProviderAuthService.ts

225 lines8.6 KB

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