Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 ProviderInstanceId,
5 ProviderSetupError,
6 type ProviderAuthInteraction,
7 type ProviderAuthResponse,
8 type ProviderAuthState,
9} from "@t3tools/contracts";
10import * as Fiber from "effect/Fiber";
11import * as Exit from "effect/Exit";
12import * as Scope from "effect/Scope";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Stream from "effect/Stream";
17
18import * as ProviderAuthFlow from "./providerAuthFlow.ts";
19
20const instanceId = ProviderInstanceId.make("auth-flow-test");
21const method = { id: "browser", name: "Browser", description: null, type: "agent" as const };
22
23it.effect("distinguishes pending method discovery from an agent with no sign-in methods", () =>
24 Effect.gen(function* () {
25 const discovered = yield* Deferred.make<ReadonlyArray<typeof method>>();
26 const controller = yield* ProviderAuthFlow.make({
27 instanceId,
28 credentialBinding: { owner: "provider", key: "shared-agent" },
29 methods: Deferred.await(discovered),
30 authenticate: () => Effect.void,
31 logout: Effect.void,
32 });
33 const pending = yield* controller
34 .subscribe("owner")
35 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
36 assert.isUndefined(pending.methods);
37 yield* Deferred.succeed(discovered, []);
38 const ready = yield* controller.subscribe("owner").pipe(
39 Stream.filter((state) => state.methods !== undefined),
40 Stream.runHead,
41 Effect.map(Option.getOrThrow),
42 );
43 assert.deepEqual(ready.methods, []);
44 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
45);
46
47const makeHarness = Effect.gen(function* () {
48 const approved = yield* Deferred.make<void>();
49 const verified = yield* Deferred.make<void>();
50 const started = yield* Deferred.make<void>();
51 let attempts = 0;
52 const controller = yield* ProviderAuthFlow.make({
53 instanceId,
54 credentialBinding: { owner: "provider", key: "shared-agent" },
55 methods: Effect.succeed([method]),
56 authenticate: (_, context) =>
57 Effect.gen(function* () {
58 attempts++;
59 yield* context.setInteraction(
60 {
61 type: "browser",
62 id: "consent",
63 url: "https://example.com/login",
64 requiresConsent: true,
65 },
66 (response) =>
67 response.type === "browser" && response.action === "accept"
68 ? Deferred.succeed(approved, undefined).pipe(Effect.asVoid)
69 : Effect.void,
70 );
71 yield* Deferred.succeed(started, undefined);
72 yield* Deferred.await(approved);
73 yield* context.verifying;
74 yield* Deferred.await(verified);
75 }),
76 logout: Effect.void,
77 });
78 const phase = (phase: ProviderAuthState["phase"], owner = "owner") =>
79 controller.subscribe(owner).pipe(
80 Stream.filter((state) => state.phase === phase),
81 Stream.runHead,
82 Effect.map(Option.getOrThrow),
83 );
84 return { controller, phase, started, verified, attempts: () => attempts };
85});
86
87it.effect("requires owner consent and provider verification before success", () =>
88 Effect.gen(function* () {
89 const { controller, phase, started, verified, attempts } = yield* makeHarness;
90 const state = yield* controller.start("owner");
91 yield* Deferred.await(started);
92 const response = {
93 instanceId,
94 flowId: state.flowId!,
95 interactionId: "consent",
96 response: { type: "browser" as const, action: "accept" as const },
97 };
98 const other = yield* phase("waiting", "other");
99 assert.isNull(other.interaction);
100 assert.isNull(other.flowId);
101 assert.isTrue(
102 (yield* controller.respond!("other", response).pipe(Effect.result))._tag === "Failure",
103 );
104 assert.isTrue(
105 (yield* controller.respond!("owner", { ...response, interactionId: "stale" }).pipe(
106 Effect.result,
107 ))._tag === "Failure",
108 );
109 yield* controller.start("owner");
110 assert.strictEqual(attempts(), 1);
111 yield* controller.respond!("owner", response);
112 yield* phase("verifying");
113 yield* Deferred.succeed(verified, undefined);
114 assert.strictEqual((yield* phase("succeeded")).phase, "succeeded");
115 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
116);
117
118it.effect("cancellation rejects late consent and permits another login", () =>
119 Effect.gen(function* () {
120 const { controller, started, phase } = yield* makeHarness;
121 const state = yield* controller.start("owner");
122 yield* Deferred.await(started);
123 yield* controller.cancel("owner", state.flowId!);
124 assert.strictEqual((yield* phase("cancelled")).phase, "cancelled");
125 assert.isTrue(
126 (yield* controller.respond!("owner", {
127 instanceId,
128 flowId: state.flowId!,
129 interactionId: "consent",
130 response: { type: "browser", action: "accept" },
131 }).pipe(Effect.result))._tag === "Failure",
132 );
133 const next = yield* controller.start("other");
134 assert.notStrictEqual(next.flowId, state.flowId);
135 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
136);
137
138it.effect("closes admitted provider processes and blocks new ones while login is pending", () =>
139 Effect.gen(function* () {
140 const { controller, started } = yield* makeHarness;
141 let closed = false;
142 yield* controller.withAccess!(
143 Effect.addFinalizer(() =>
144 Effect.sync(() => {
145 closed = true;
146 }),
147 ),
148 );
149 yield* controller.start("owner");
150 yield* Deferred.await(started);
151 assert.isTrue(closed);
152 assert.isTrue(
153 (yield* controller.withAccess!(Effect.void).pipe(Effect.result))._tag === "Failure",
154 );
155 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
156);
157
158it.effect("shared credential invalidation closes admitted processes before permitting reuse", () =>
159 Effect.gen(function* () {
160 const { controller } = yield* makeHarness;
161 let closed = false;
162 yield* controller.withAccess!(
163 Effect.addFinalizer(() =>
164 Effect.sync(() => {
165 closed = true;
166 }),
167 ),
168 );
169 yield* controller.invalidate!;
170 assert.isTrue(closed);
171 assert.strictEqual(yield* controller.withAccess!(Effect.succeed("new process")), "new process");
172 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
173);
174
175it.effect.each([
176 {
177 interaction: { type: "terminal", id: "terminal", output: "Log in" },
178 response: { type: "terminal", data: "input", size: { cols: 80, rows: 24 } },
179 },
180 {
181 interaction: {
182 type: "credentials",
183 id: "credentials",
184 fields: [{ name: "token", label: "Token", secret: true }],
185 },
186 response: { type: "credentials", values: { token: "private-token" } },
187 },
188] satisfies ReadonlyArray<{
189 interaction: ProviderAuthInteraction;
190 response: ProviderAuthResponse;
191}>)(
192 "keeps $interaction.type responses private and waits for adapter verification",
193 ({ interaction, response }) =>
194 Effect.gen(function* () {
195 const received = yield* Deferred.make<ProviderAuthResponse>();
196 const controller = yield* ProviderAuthFlow.make({
197 instanceId,
198 credentialBinding: { owner: "t3", key: "binding" },
199 methods: Effect.succeed([method]),
200 authenticate: (_, context) =>
201 Effect.gen(function* () {
202 yield* context.setInteraction(interaction, (response) =>
203 Deferred.succeed(received, response).pipe(Effect.asVoid),
204 );
205 yield* Deferred.await(received);
206 yield* context.verifying;
207 return yield* Effect.never;
208 }),
209 logout: Effect.void,
210 });
211 const state = yield* controller.start("owner");
212 const pending = yield* controller.subscribe("owner").pipe(
213 Stream.filter((state) => state.phase === "waiting"),
214 Stream.runHead,
215 Effect.map(Option.getOrThrow),
216 );
217 assert.deepStrictEqual(pending.interaction, interaction);
218 const hidden = yield* controller
219 .subscribe("other")
220 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
221 assert.isNull(hidden.interaction);
222 yield* controller.respond!("owner", {
223 instanceId,
224 flowId: state.flowId!,
225 interactionId: interaction.id,
226 response,
227 });
228 assert.deepStrictEqual(yield* Deferred.await(received), response);
229 const verifying = yield* controller.subscribe("owner").pipe(
230 Stream.filter((state) => state.phase === "verifying"),
231 Stream.runHead,
232 Effect.map(Option.getOrThrow),
233 );
234 assert.isNull(verifying.interaction);
235 assert.notInclude(verifying.message ?? "", "private-token");
236 yield* controller.cancel("owner", state.flowId!);
237 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
238);
239
240it.effect("shows a device code only to its owner without treating it as authenticated", () =>
241 Effect.gen(function* () {
242 const controller = yield* ProviderAuthFlow.make({
243 instanceId,
244 credentialBinding: { owner: "provider", key: "device" },
245 methods: Effect.succeed([method]),
246 authenticate: (_, context) =>
247 context
248 .setInteraction({
249 type: "deviceCode",
250 id: "code",
251 url: "https://example.com/device",
252 userCode: "ABCD-EFGH",
253 })
254 .pipe(Effect.andThen(Effect.never)),
255 logout: Effect.void,
256 });
257 const start = yield* controller.start("owner");
258 const waiting = yield* controller.subscribe("owner").pipe(
259 Stream.filter((state) => state.phase === "waiting"),
260 Stream.runHead,
261 Effect.map(Option.getOrThrow),
262 );
263 assert.strictEqual(waiting.interaction?.type, "deviceCode");
264 assert.strictEqual(waiting.authorizationUrl, "https://example.com/device");
265 const other = yield* controller
266 .subscribe("other")
267 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
268 assert.isNull(other.interaction);
269 assert.isNull(other.authorizationUrl);
270 yield* controller.cancel("owner", start.flowId!);
271 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
272);
273
274it.effect.each([
275 {
276 failure: Effect.fail(
277 new ProviderSetupError({
278 instanceId,
279 operation: "authenticate",
280 detail: "This account cannot sign in. Choose another account.",
281 }),
282 ),
283 message: "This account cannot sign in. Choose another account.",
284 },
285 {
286 failure: Effect.die(new Error("private-token in native diagnostics")),
287 message: "Sign-in failed. Start again.",
288 },
289])("publishes only safe authentication failure text %#", ({ failure, message }) =>
290 Effect.gen(function* () {
291 const controller = yield* ProviderAuthFlow.make({
292 instanceId,
293 credentialBinding: { owner: "t3", key: "failure" },
294 methods: Effect.succeed([method]),
295 authenticate: () => failure,
296 logout: Effect.void,
297 });
298 yield* controller.start("owner");
299 const failed = yield* controller.subscribe("owner").pipe(
300 Stream.filter((state) => state.phase === "failed"),
301 Stream.runHead,
302 Effect.map(Option.getOrThrow),
303 );
304 assert.strictEqual(failed.message, message);
305 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
306);
307
308const makeBlockingResponseHarness = Effect.gen(function* () {
309 const entered = yield* Deferred.make<void>();
310 const cleanupStarted = yield* Deferred.make<void>();
311 const cleanupReleased = yield* Deferred.make<void>();
312 const cleanupFinished = yield* Deferred.make<void>();
313 const authenticationFinished = yield* Deferred.make<void>();
314 let responses = 0;
315 const controller = yield* ProviderAuthFlow.make({
316 instanceId,
317 credentialBinding: { owner: "t3", key: "blocked-response" },
318 methods: Effect.succeed([method]),
319 authenticate: (_, context) =>
320 Effect.gen(function* () {
321 yield* context.setInteraction(
322 {
323 type: "browser",
324 id: "blocked",
325 url: "https://example.com/login",
326 requiresConsent: true,
327 },
328 () =>
329 Effect.gen(function* () {
330 responses++;
331 yield* Deferred.succeed(entered, undefined);
332 return yield* Effect.never;
333 }).pipe(
334 Effect.ensuring(
335 Effect.gen(function* () {
336 yield* Deferred.succeed(cleanupStarted, undefined);
337 yield* Deferred.await(cleanupReleased);
338 yield* Deferred.succeed(cleanupFinished, undefined);
339 }),
340 ),
341 ),
342 );
343 yield* Deferred.await(authenticationFinished);
344 }),
345 logout: Effect.void,
346 });
347 const start = yield* controller.start("owner");
348 yield* controller.subscribe("owner").pipe(
349 Stream.filter((state) => state.phase === "waiting"),
350 Stream.runHead,
351 );
352 const input = {
353 instanceId,
354 flowId: start.flowId!,
355 interactionId: "blocked",
356 response: { type: "browser" as const, action: "accept" as const },
357 };
358 const response = yield* controller.respond!("owner", input).pipe(Effect.exit, Effect.forkChild);
359 yield* Deferred.await(entered);
360 return {
361 controller,
362 input,
363 response,
364 cleanupStarted,
365 cleanupReleased,
366 cleanupFinished,
367 authenticationFinished,
368 responses: () => responses,
369 };
370});
371
372it.effect.each(["cancel", "logout"] as const)(
373 "%s interrupts and awaits a blocked adapter response before admitting another sign-in",
374 (action) =>
375 Effect.gen(function* () {
376 const harness = yield* makeBlockingResponseHarness;
377 const duplicate = yield* Effect.flip(harness.controller.respond!("owner", harness.input));
378 assert.include(duplicate.detail, "already in progress");
379 assert.equal(harness.responses(), 1);
380 const stopping = yield* (
381 action === "cancel"
382 ? harness.controller.cancel("owner", harness.input.flowId)
383 : harness.controller.logout(Effect.void)
384 ).pipe(Effect.forkChild);
385 yield* Deferred.await(harness.cleanupStarted);
386 assert.isTrue(yield* harness.controller.isChangingCredentials!);
387 assert.isUndefined(stopping.pollUnsafe());
388 const premature = yield* Effect.flip(harness.controller.start("other"));
389 assert.include(premature.detail, "in progress");
390 yield* Deferred.succeed(harness.cleanupReleased, undefined);
391 yield* Fiber.join(stopping);
392 assert.isTrue(yield* Deferred.isDone(harness.cleanupFinished));
393 assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response)));
394 assert.isFalse(yield* harness.controller.isChangingCredentials!);
395 assert.notEqual((yield* harness.controller.start("other")).flowId, harness.input.flowId);
396 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
397);
398
399it.effect(
400 "successful authentication drains a still-running response before admitting provider access",
401 () =>
402 Effect.gen(function* () {
403 const harness = yield* makeBlockingResponseHarness;
404 yield* Deferred.succeed(harness.authenticationFinished, undefined);
405 yield* Deferred.await(harness.cleanupStarted);
406 const denied = yield* Effect.flip(harness.controller.withAccess!(Effect.void));
407 assert.include(denied.detail, "changing");
408 yield* Deferred.succeed(harness.cleanupReleased, undefined);
409 const succeeded = yield* harness.controller.subscribe("owner").pipe(
410 Stream.filter((state) => state.phase === "succeeded"),
411 Stream.runHead,
412 Effect.map(Option.getOrThrow),
413 );
414 assert.equal(succeeded.phase, "succeeded");
415 assert.isTrue(yield* Deferred.isDone(harness.cleanupFinished));
416 assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response)));
417 yield* harness.controller.withAccess!(Effect.void);
418 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
419);
420
421it.effect("closing the controller scope interrupts and drains its adapter response", () =>
422 Effect.gen(function* () {
423 const scope = yield* Scope.make();
424 const harness = yield* makeBlockingResponseHarness.pipe(
425 Effect.provideService(Scope.Scope, scope),
426 );
427 const closing = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild);
428 yield* Deferred.await(harness.cleanupStarted);
429 assert.isUndefined(closing.pollUnsafe());
430 yield* Deferred.succeed(harness.cleanupReleased, undefined);
431 yield* Fiber.join(closing);
432 assert.isTrue(yield* Deferred.isDone(harness.cleanupFinished));
433 assert.isTrue(Exit.isFailure(yield* Fiber.join(harness.response)));
434 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
435);
436
437it.effect("a failed method refresh keeps the last discovered methods", () =>
438 Effect.gen(function* () {
439 let fail = false;
440 const controller = yield* ProviderAuthFlow.make({
441 instanceId,
442 credentialBinding: { owner: "provider", key: "shared-agent" },
443 methods: Effect.suspend(() =>
444 fail
445 ? Effect.fail(
446 new ProviderSetupError({ instanceId, operation: "status", detail: "interrupted" }),
447 )
448 : Effect.succeed([method]),
449 ),
450 authenticate: () => Effect.void,
451 logout: Effect.void,
452 });
453 yield* controller.refreshMethods!;
454 fail = true;
455 yield* controller.refreshMethods!;
456 const state = yield* controller
457 .subscribe("owner")
458 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
459 assert.deepEqual(state.methods, [method]);
460 assert.strictEqual(state.message, "interrupted");
461 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
462);
463
464it.effect("rebuilding a controller leaves sessions it admitted to their owners", () =>
465 Effect.gen(function* () {
466 const scope = yield* Scope.make();
467 const { controller } = yield* makeHarness.pipe(Effect.provideService(Scope.Scope, scope));
468 let closed = false;
469 yield* controller.withAccess!(
470 Effect.addFinalizer(() =>
471 Effect.sync(() => {
472 closed = true;
473 }),
474 ),
475 );
476 yield* Scope.close(scope, Exit.void);
477 assert.isFalse(closed);
478 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
479);
480
481it.effect("profile import stops owned sessions and gates access until credentials are saved", () =>
482 Effect.gen(function* () {
483 const controller = yield* ProviderAuthFlow.make({
484 instanceId,
485 credentialBinding: { owner: "t3", key: "handoff-binding" },
486 methods: Effect.succeed([method]),
487 authenticate: () => Effect.void,
488 logout: Effect.void,
489 });
490 let closed = false;
491 yield* controller.withAccess!(
492 Effect.addFinalizer(() =>
493 Effect.sync(() => {
494 closed = true;
495 }),
496 ),
497 );
498 const writing = yield* Deferred.make<void>();
499 const release = yield* Deferred.make<void>();
500 const imported = yield* controller.adoptCredentials!(
501 Deferred.succeed(writing, undefined).pipe(Effect.andThen(Deferred.await(release))),
502 Effect.sync(() => {
503 assert.isTrue(closed);
504 }),
505 ).pipe(Effect.forkChild);
506 yield* Deferred.await(writing);
507 const denied = yield* controller.withAccess!(Effect.succeed("old credential process")).pipe(
508 Effect.result,
509 );
510 assert.strictEqual(denied._tag, "Failure");
511 yield* Deferred.succeed(release, undefined);
512 assert.strictEqual((yield* Fiber.join(imported)).phase, "succeeded");
513 assert.strictEqual(
514 yield* controller.withAccess!(Effect.succeed("new credential process")),
515 "new credential process",
516 );
517 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
518);