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

ProviderAuthService.test.ts

608 lines22.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 ProviderDriverKind,
4 ProviderInstanceId,
5 ProviderSetupError,
6 ThreadId,
7 type ProviderAuthState,
8 type ProviderSession,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Deferred from "effect/Deferred";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as PubSub from "effect/PubSub";
15import * as Queue from "effect/Queue";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18​
19import {
20 ProviderSessionDirectoryPersistenceError,
21 ProviderValidationError,
22 type ProviderServiceError,
23} from "../Errors.ts";
24import type { ProviderInstance } from "../ProviderDriver.ts";
25import type { ProviderAuthController } from "../Services/ProviderAuthService.ts";
26import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
27import { ProviderService } from "../Services/ProviderService.ts";
28import {
29 ProviderSessionDirectory,
30 type ProviderRuntimeBindingWithMetadata,
31} from "../Services/ProviderSessionDirectory.ts";
32import { makeProviderAuthService } from "./ProviderAuthService.ts";
33​
34const instanceId = ProviderInstanceId.make("antigravity-personal");
35const otherInstanceId = ProviderInstanceId.make("antigravity-work");
36const unsupportedInstanceId = ProviderInstanceId.make("codex");
37const driverKind = ProviderDriverKind.make("antigravity");
38const owner = "paired-client-owner";
39const otherOwner = "paired-client-other";
40const flowId = "test-sign-in-flow";
41const callbackUrl = "http://127.0.0.1:48123/?state=test-state&code=test-code";
42const now = "2026-09-02T00:00:00.000Z";
43const idleAuthState: ProviderAuthState = {
44 instanceId,
45 phase: "idle",
46 flowId: null,
47 authorizationUrl: null,
48 expiresAt: null,
49 message: null,
50};
51const waitingAuthState: ProviderAuthState = {
52 ...idleAuthState,
53 phase: "waiting",
54 flowId,
55 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-state",
56 expiresAt: "2026-09-02T00:05:00.000Z",
57};
58​
59function makeInstance(input: {
60 instanceId: ProviderInstanceId;
61 enabled: boolean;
62 auth?: ProviderAuthController;
63}): ProviderInstance {
64 return {
65 ...input,
66 driverKind,
67 displayName: undefined,
68 continuationIdentity: { driverKind, continuationKey: input.instanceId },
69 get snapshot(): never {
70 throw new Error("Auth routing must not refresh the provider snapshot.");
71 },
72 get adapter(): never {
73 throw new Error("Auth routing must not start an adapter session.");
74 },
75 get textGeneration(): never {
76 throw new Error("Auth routing must not generate text.");
77 },
78 };
80​
81function makeBinding(
82 thread: string,
83 status: NonNullable<ProviderRuntimeBindingWithMetadata["status"]>,
84 providerInstanceId = instanceId,
85): ProviderRuntimeBindingWithMetadata {
86 return {
87 threadId: ThreadId.make(thread),
88 provider: driverKind,
89 providerInstanceId,
90 status,
91 lastSeenAt: now,
92 };
94​
95function makeSession(thread: string, providerInstanceId = instanceId): ProviderSession {
96 return {
97 threadId: ThreadId.make(thread),
98 provider: driverKind,
99 providerInstanceId,
100 status: "ready",
101 runtimeMode: "approval-required",
102 createdAt: now,
103 updatedAt: now,
104 };
106​
107const makeHarness = Effect.fn("ProviderAuthService.test.makeHarness")(function* (
108 input: {
109 enabled?: boolean;
110 bindings?: ReadonlyArray<ProviderRuntimeBindingWithMetadata>;
111 sessions?: ReadonlyArray<ProviderSession>;
112 directoryError?: ProviderSessionDirectoryPersistenceError;
113 stopError?: ProviderServiceError;
114 logoutError?: ProviderSetupError;
115 } = {},
116) {
117 const actions: string[] = [];
118 const registryChanges = yield* PubSub.unbounded<void>();
119 const sessions = new Map(input.sessions?.map((session) => [session.threadId, session]));
120 const bindings = new Map(input.bindings?.map((binding) => [binding.threadId, binding]));
121 const idle = idleAuthState;
122 let state = idle;
123 let flowOwner: string | undefined;
124 let gateClosed = false;
125​
126 const checkOwner = Effect.fn("ProviderAuthService.test.checkOwner")(function* (
127 ownerSessionId: string,
128 requestedFlowId: string,
129 operation: string,
130 ) {
131 if (ownerSessionId !== flowOwner || requestedFlowId !== state.flowId) {
132 return yield* new ProviderSetupError({
133 instanceId,
134 operation,
135 detail: "This sign-in belongs to another client or has expired.",
136 });
137 }
138 });
139​
140 const auth: ProviderAuthController = {
141 start: Effect.fn(function* (ownerSessionId, stopSessions) {
142 gateClosed = true;
143 actions.push("close-gate");
144 yield* stopSessions ?? Effect.void;
145 flowOwner = ownerSessionId;
146 state = waitingAuthState;
147 actions.push("start-sign-in");
148 return state;
149 }),
150 complete: Effect.fn(function* (ownerSessionId, request) {
151 yield* checkOwner(ownerSessionId, request.flowId, "complete");
152 if (request.callbackUrl !== callbackUrl) {
153 return yield* new ProviderSetupError({
154 instanceId,
155 operation: "complete",
156 detail: "The redirect URL does not match this sign-in.",
157 });
158 }
159 state = { ...idle, flowId, phase: "succeeded" };
160 return state;
161 }),
162 cancel: Effect.fn(function* (ownerSessionId, requestedFlowId) {
163 yield* checkOwner(ownerSessionId, requestedFlowId, "cancel");
164 state = { ...idle, flowId, phase: "cancelled" };
165 return state;
166 }),
167 logout: Effect.fn(function* (stopSessions) {
168 gateClosed = true;
169 actions.push("close-gate");
170 yield* stopSessions;
171 if (input.logoutError) return yield* input.logoutError;
172 actions.push("native-logout");
173 state = idle;
174 flowOwner = undefined;
175 return state;
176 }),
177 subscribe: (ownerSessionId) =>
178 Stream.fromEffect(Effect.sync(() => (ownerSessionId === flowOwner ? state : idle))),
179 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
180 };
181 const instances = [
182 makeInstance({ instanceId, enabled: input.enabled ?? true, auth }),
183 makeInstance({ instanceId: unsupportedInstanceId, enabled: true }),
184 ];
185 const service = yield* makeProviderAuthService.pipe(
186 Effect.provide(
187 Layer.mergeAll(
188 Layer.mock(ProviderInstanceRegistry)({
189 getInstance: (id) =>
190 Effect.succeed(instances.find((instance) => instance.instanceId === id)),
191 subscribeChanges: PubSub.subscribe(registryChanges),
192 }),
193 Layer.mock(ProviderSessionDirectory)({
194 listBindings: () =>
195 Effect.suspend(() => {
196 assert.isTrue(gateClosed);
197 actions.push("list-bindings");
198 return input.directoryError
199 ? Effect.fail(input.directoryError)
200 : Effect.succeed([...bindings.values()]);
201 }),
202 }),
203 Layer.mock(ProviderService)({
204 listSessions: () =>
205 Effect.sync(() => {
206 assert.isTrue(gateClosed);
207 actions.push("list-sessions");
208 return [...sessions.values()];
209 }),
210 stopSession: ({ threadId }) =>
211 Effect.suspend(() => {
212 assert.isTrue(gateClosed);
213 actions.push(`stop:${threadId}`);
214 if (input.stopError) return Effect.fail(input.stopError);
215 sessions.delete(threadId);
216 const binding = bindings.get(threadId);
217 if (binding) bindings.set(threadId, { ...binding, status: "stopped" });
218 return Effect.void;
219 }),
220 }),
221 ),
222 ),
223 );
224 return { service, actions, sessions, bindings };
225});
226​
227const makeStreamingController = Effect.fn("ProviderAuthService.test.makeStreamingController")(
228 function* (flowOwner: string) {
229 const state = yield* SubscriptionRef.make(idleAuthState);
230 const close = yield* Deferred.make<void>();
231 const closedSubscriptions = yield* Queue.unbounded<string>();
232 const unused = () => Effect.die("Unexpected auth operation in a subscription test.");
233 const auth: ProviderAuthController = {
234 start: unused,
235 complete: unused,
236 cancel: unused,
237 logout: unused,
238 subscribe: (ownerSessionId) =>
239 SubscriptionRef.changes(state).pipe(
240 Stream.map((current) => (ownerSessionId === flowOwner ? current : idleAuthState)),
241 Stream.interruptWhen(Deferred.await(close)),
242 Stream.ensuring(Queue.offer(closedSubscriptions, ownerSessionId)),
243 ),
244 };
245 return {
246 auth,
247 state,
248 closedSubscriptions,
249 close: Deferred.succeed(close, undefined),
250 };
251 },
252);
253​
254const makeSubscriptionHarness = Effect.fn("ProviderAuthService.test.makeSubscriptionHarness")(
255 function* (initial: ProviderInstance, replaceDuringFirstLookup?: ProviderInstance) {
256 const changes = yield* PubSub.unbounded<void>();
257 let current: ProviderInstance | undefined = initial;
258 let pendingReplacement = replaceDuringFirstLookup;
259 let subscribed = false;
260 const service = yield* makeProviderAuthService.pipe(
261 Effect.provide(
262 Layer.mergeAll(
263 Layer.mock(ProviderInstanceRegistry)({
264 subscribeChanges: Effect.gen(function* () {
265 const subscription = yield* PubSub.subscribe(changes);
266 subscribed = true;
267 return subscription;
268 }),
269 getInstance: () =>
270 Effect.gen(function* () {
271 const instance = current;
272 if (pendingReplacement) {
273 assert.isTrue(subscribed, "Registry changes must be subscribed before lookup.");
274 current = pendingReplacement;
275 pendingReplacement = undefined;
276 yield* PubSub.publish(changes, undefined);
277 }
278 return instance;
279 }),
280 }),
281 Layer.mock(ProviderService)({}),
282 Layer.mock(ProviderSessionDirectory)({}),
283 ),
284 ),
285 );
286 return {
287 service,
288 replace: Effect.fn(function* (replacement: ProviderInstance | undefined) {
289 current = replacement;
290 yield* PubSub.publish(changes, undefined);
291 }),
292 };
293 },
294);
295​
296const observeAuth = Effect.fn("ProviderAuthService.test.observeAuth")(function* (
297 stream: Stream.Stream<ProviderAuthState, ProviderSetupError>,
298) {
299 const states = yield* Queue.unbounded<ProviderAuthState>();
300 const fiber = yield* stream.pipe(
301 Stream.runForEach((state) => Queue.offer(states, state)),
302 Effect.forkScoped,
303 );
304 return { states, fiber };
305});
306​
307describe("ProviderAuthService", () => {
308 it.effect("stops routed sessions before sign-in, including for a disabled instance", () =>
309 Effect.gen(function* () {
310 const { service, actions, sessions } = yield* makeHarness({
311 enabled: false,
312 sessions: [makeSession("active")],
313 });
314 const state = yield* service.start({ instanceId }, owner);
315​
316 assert.strictEqual(state.instanceId, instanceId);
317 assert.strictEqual(state.phase, "waiting");
318 assert.strictEqual(sessions.size, 0);
319 assert.deepStrictEqual(actions, [
320 "close-gate",
321 "list-bindings",
322 "list-sessions",
323 "stop:active",
324 "start-sign-in",
325 ]);
326 }),
327 );
328​
329 it.effect("keeps sign-in state private and accepts the owner's redirect URL", () =>
330 Effect.gen(function* () {
331 const { service } = yield* makeHarness();
332 const waiting = yield* service.start({ instanceId }, owner);
333 const ownerStates = yield* service
334 .subscribe({ instanceId }, owner)
335 .pipe(Stream.take(1), Stream.runCollect);
336 const otherStates = yield* service
337 .subscribe({ instanceId }, otherOwner)
338 .pipe(Stream.take(1), Stream.runCollect);
339​
340 assert.deepStrictEqual(ownerStates, [waiting]);
341 assert.strictEqual(otherStates[0]?.authorizationUrl, null);
342 assert.strictEqual(otherStates[0]?.flowId, null);
343​
344 const otherError = yield* Effect.flip(
345 service.complete({ instanceId, flowId, callbackUrl }, otherOwner),
346 );
347 assert.strictEqual(otherError.operation, "complete");
348 const complete = yield* service.complete({ instanceId, flowId, callbackUrl }, owner);
349 assert.strictEqual(complete.phase, "succeeded");
350 assert.strictEqual(complete.authorizationUrl, null);
351 }),
352 );
353​
354 it.effect("lets only the flow owner cancel sign-in", () =>
355 Effect.gen(function* () {
356 const { service } = yield* makeHarness();
357 yield* service.start({ instanceId }, owner);
358 const error = yield* Effect.flip(service.cancel({ instanceId, flowId }, otherOwner));
359 assert.strictEqual(error.operation, "cancel");
360​
361 const cancelled = yield* service.cancel({ instanceId, flowId }, owner);
362 assert.strictEqual(cancelled.phase, "cancelled");
363 assert.strictEqual(cancelled.authorizationUrl, null);
364 }),
365 );
366​
367 it.effect.each([
368 { change: "enable", initialEnabled: false, closeBeforeReplacement: true },
369 { change: "config", initialEnabled: true, closeBeforeReplacement: false },
370 ])(
371 "keeps private auth subscriptions current after an instance $change change",
372 ({ initialEnabled, closeBeforeReplacement }) =>
373 Effect.gen(function* () {
374 const first = yield* makeStreamingController(owner);
375 const replacement = yield* makeStreamingController(otherOwner);
376 yield* SubscriptionRef.set(first.state, waitingAuthState);
377 const { service, replace } = yield* makeSubscriptionHarness(
378 makeInstance({ instanceId, enabled: initialEnabled, auth: first.auth }),
379 );
380 const firstClient = yield* observeAuth(service.subscribe({ instanceId }, owner));
381 const secondClient = yield* observeAuth(service.subscribe({ instanceId }, otherOwner));
382 assert.deepStrictEqual(yield* Queue.take(firstClient.states), waitingAuthState);
383 assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState);
384​
385 if (closeBeforeReplacement) {
386 yield* first.close;
387 const closed = yield* Queue.takeN(first.closedSubscriptions, 2);
388 assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner]));
389 }
390 yield* replace(makeInstance({ instanceId, enabled: true, auth: replacement.auth }));
391 assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState);
392 assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState);
393 if (!closeBeforeReplacement) {
394 const closed = yield* Queue.takeN(first.closedSubscriptions, 2);
395 assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner]));
396 }
397​
398 const staleState: ProviderAuthState = { ...idleAuthState, phase: "cancelled" };
399 yield* SubscriptionRef.set(first.state, staleState);
400 const newWaiting: ProviderAuthState = {
401 ...waitingAuthState,
402 flowId: "replacement-flow",
403 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=replacement-state",
404 };
405 yield* SubscriptionRef.set(replacement.state, newWaiting);
406 assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState);
407 assert.deepStrictEqual(yield* Queue.take(secondClient.states), newWaiting);
408 }),
409 );
410​
411 it.effect("does not miss a replacement during the first instance lookup", () =>
412 Effect.gen(function* () {
413 const first = yield* makeStreamingController(owner);
414 const replacement = yield* makeStreamingController(owner);
415 yield* SubscriptionRef.set(replacement.state, waitingAuthState);
416 const { service } = yield* makeSubscriptionHarness(
417 makeInstance({ instanceId, enabled: false, auth: first.auth }),
418 makeInstance({ instanceId, enabled: true, auth: replacement.auth }),
419 );
420​
421 const states = yield* service.subscribe({ instanceId }, owner).pipe(
422 Stream.filter((state) => state.phase === "waiting"),
423 Stream.take(1),
424 Stream.runCollect,
425 );
426​
427 assert.deepStrictEqual(states, [waitingAuthState]);
428 }),
429 );
430​
431 it.effect("ends the subscription with a setup error when the instance is removed", () =>
432 Effect.gen(function* () {
433 const controller = yield* makeStreamingController(owner);
434 const { service, replace } = yield* makeSubscriptionHarness(
435 makeInstance({ instanceId, enabled: true, auth: controller.auth }),
436 );
437 const { states, fiber } = yield* observeAuth(service.subscribe({ instanceId }, owner));
438 assert.deepStrictEqual(yield* Queue.take(states), idleAuthState);
439​
440 yield* replace(undefined);
441 const error = yield* Effect.flip(Fiber.join(fiber));
442​
443 assert.instanceOf(error, ProviderSetupError);
444 assert.strictEqual(error.instanceId, instanceId);
445 assert.strictEqual(error.operation, "subscribe");
446 assert.include(error.detail, "no longer available");
447 assert.strictEqual(yield* Queue.take(controller.closedSubscriptions), owner);
448 }),
449 );
450​
451 it.effect.each([
452 { id: ProviderInstanceId.make("missing"), detail: "no longer available" },
453 { id: unsupportedInstanceId, detail: "does not support sign-in" },
454 ])("rejects setup for unavailable or unsupported instance $id", ({ id, detail }) =>
455 Effect.gen(function* () {
456 const { service, actions } = yield* makeHarness();
457 const operations: Effect.Effect<
458 ProviderAuthState | ReadonlyArray<ProviderAuthState>,
459 ProviderSetupError
460 >[] = [
461 service.start({ instanceId: id }, owner),
462 service.complete({ instanceId: id, flowId, callbackUrl }, owner),
463 service.cancel({ instanceId: id, flowId }, owner),
464 service.logout({ instanceId: id }),
465 Stream.runCollect(service.subscribe({ instanceId: id }, owner)),
466 ];
467 for (const operation of operations) {
468 const error = yield* Effect.flip(operation);
469 assert.instanceOf(error, ProviderSetupError);
470 assert.strictEqual(error.instanceId, id);
471 assert.include(error.detail, detail);
472 }
473 assert.deepStrictEqual(actions, []);
474 }),
475 );
476​
477 it.effect("stops active and persisted sessions once before native logout", () =>
478 Effect.gen(function* () {
479 const { service, actions, sessions, bindings } = yield* makeHarness({
480 bindings: [
481 makeBinding("shared", "running"),
482 makeBinding("starting", "starting"),
483 makeBinding("persisted", "running"),
484 makeBinding("already-stopped", "stopped"),
485 makeBinding("other-instance", "running", otherInstanceId),
486 ],
487 sessions: [
488 makeSession("shared"),
489 makeSession("runtime-only"),
490 makeSession("other-instance", otherInstanceId),
491 ],
492 });
493 const state = yield* service.logout({ instanceId });
494​
495 assert.strictEqual(state.phase, "idle");
496 assert.deepStrictEqual(actions, [
497 "close-gate",
498 "list-bindings",
499 "list-sessions",
500 "stop:shared",
501 "stop:starting",
502 "stop:persisted",
503 "stop:runtime-only",
504 "native-logout",
505 ]);
506 assert.deepStrictEqual([...sessions.keys()], [ThreadId.make("other-instance")]);
507 assert.strictEqual(bindings.get(ThreadId.make("starting"))?.status, "stopped");
508 assert.strictEqual(bindings.get(ThreadId.make("persisted"))?.status, "stopped");
509 assert.strictEqual(bindings.get(ThreadId.make("other-instance"))?.status, "running");
510 }),
511 );
512​
513 it.effect.each([
514 { text: "/logout", hasAttachments: false, handled: true },
515 { text: " \n/logout\t", hasAttachments: false, handled: true },
516 { text: "/logout", hasAttachments: true, handled: false },
517 { text: "/logout please", hasAttachments: false, handled: false },
518 { text: "Explain /logout", hasAttachments: false, handled: false },
519 { text: "/Logout", hasAttachments: false, handled: false },
520 ])("handles only a standalone logout command %#", ({ text, hasAttachments, handled }) =>
521 Effect.gen(function* () {
522 const { service, actions } = yield* makeHarness();
523 const result = yield* service.tryHandlePromptCommand({ instanceId, text, hasAttachments });
524​
525 assert.strictEqual(result, handled);
526 assert.deepStrictEqual(
527 actions,
528 handled ? ["close-gate", "list-bindings", "list-sessions", "native-logout"] : [],
529 );
530 }),
531 );
532​
533 it.effect("does not intercept commands for providers without an auth controller", () =>
534 Effect.gen(function* () {
535 const { service, actions } = yield* makeHarness();
536 for (const id of [unsupportedInstanceId, ProviderInstanceId.make("missing")]) {
537 assert.isFalse(
538 yield* service.tryHandlePromptCommand({
539 instanceId: id,
540 text: "/logout",
541 hasAttachments: false,
542 }),
543 );
544 }
545 assert.deepStrictEqual(actions, []);
546 }),
547 );
548​
549 it.effect("does not log out when the session directory cannot be read", () =>
550 Effect.gen(function* () {
551 const { service, actions } = yield* makeHarness({
552 directoryError: new ProviderSessionDirectoryPersistenceError({
553 operation: "listBindings",
554 detail: "private database diagnostics",
555 }),
556 });
557 const error = yield* Effect.flip(service.logout({ instanceId }));
558​
559 assert.instanceOf(error, ProviderSetupError);
560 assert.strictEqual(error.instanceId, instanceId);
561 assert.strictEqual(error.operation, "stopSessions");
562 assert.notInclude(error.detail, "private database diagnostics");
563 assert.deepStrictEqual(actions, ["close-gate", "list-bindings"]);
564 }),
565 );
566​
567 it.effect("does not log out or consume the command when stopping a session fails", () =>
568 Effect.gen(function* () {
569 const { service, actions, sessions } = yield* makeHarness({
570 sessions: [makeSession("active")],
571 stopError: new ProviderValidationError({
572 operation: "stopSession",
573 issue: "private process diagnostics",
574 }),
575 });
576 const error = yield* Effect.flip(
577 service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }),
578 );
579​
580 assert.instanceOf(error, ProviderSetupError);
581 assert.strictEqual(error.operation, "stopSessions");
582 assert.notInclude(error.detail, "private process diagnostics");
583 assert.strictEqual(sessions.size, 1);
584 assert.deepStrictEqual(actions, [
585 "close-gate",
586 "list-bindings",
587 "list-sessions",
588 "stop:active",
589 ]);
590 }),
591 );
592​
593 it.effect("returns native logout failures to the command caller", () =>
594 Effect.gen(function* () {
595 const logoutError = new ProviderSetupError({
596 instanceId,
597 operation: "logout",
598 detail: "Native sign-out failed. Try again.",
599 });
600 const { service } = yield* makeHarness({ logoutError });
601 const error = yield* Effect.flip(
602 service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }),
603 );
604​
605 assert.strictEqual(error, logoutError);
606 }),
607 );
608});