Open History to see the last commit
1import {
2 ProviderSetupError,
3 type ProviderAuthInteraction,
4 type ProviderAuthMethod,
5 type ProviderAuthResponse,
6 type ProviderAuthState,
7 type ProviderInstanceId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as Clock from "effect/Clock";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Deferred from "effect/Deferred";
17import * as Exit from "effect/Exit";
18import * as Fiber from "effect/Fiber";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23
24import type * as ProviderAuthService from "./Services/ProviderAuthService.ts";
25
26export interface ProviderAuthFlowContext {
27 readonly flowId: string;
28 readonly setInteraction: (
29 interaction: ProviderAuthInteraction,
30 respond?: (response: ProviderAuthResponse) => Effect.Effect<void, ProviderSetupError>,
31 ) => Effect.Effect<void>;
32 readonly verifying: Effect.Effect<void>;
33}
34
35const isSetupError = Schema.is(ProviderSetupError);
36
37const failureMessage = (cause: Cause.Cause<ProviderSetupError>) => {
38 const error = Cause.findErrorOption(cause);
39 return Option.isSome(error) && isSetupError(error.value)
40 ? error.value.detail
41 : "Sign-in failed. Start again.";
42};
43
44interface Flow {
45 readonly id: string;
46 readonly owner: string;
47 readonly expiresAt: number;
48 fiber?: Fiber.Fiber<void>;
49 responseFiber?: Fiber.Fiber<void, ProviderSetupError>;
50 respond:
51 | ((response: ProviderAuthResponse) => Effect.Effect<void, ProviderSetupError>)
52 | undefined;
53}
54
55/** Adapters do login and credential handling; this owns client consent and flow lifetime. */
56export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {
57 readonly instanceId: ProviderInstanceId;
58 readonly credentialBinding: NonNullable<
59 ProviderAuthService.ProviderAuthController["credentialBinding"]
60 >;
61 readonly methods: Effect.Effect<ReadonlyArray<ProviderAuthMethod>, ProviderSetupError>;
62 readonly defaultMethodId?: string;
63 /** Fail with ProviderSetupError containing safe text for the user, never native token data. */
64 readonly authenticate: (
65 methodId: string,
66 context: ProviderAuthFlowContext,
67 ) => Effect.Effect<void, ProviderSetupError, Scope.Scope>;
68 readonly logout: Effect.Effect<void, ProviderSetupError>;
69 readonly timeoutMs?: number;
70}) {
71 const scope = yield* Scope.Scope;
72 const crypto = yield* Crypto.Crypto;
73 const lock = yield* Semaphore.make(1);
74 const timeoutMs = options.timeoutMs ?? 300_000;
75 const empty: ProviderAuthState = {
76 instanceId: options.instanceId,
77 phase: "idle",
78 flowId: null,
79 authorizationUrl: null,
80 expiresAt: null,
81 message: null,
82 interaction: null,
83 credentialOwner: options.credentialBinding.owner,
84 };
85 const snapshot = yield* SubscriptionRef.make({ owner: null as string | null, state: empty });
86 let active: Flow | undefined;
87 let operation: "idle" | "auth" | "stopping" | "closed" = "idle";
88 const sessions = new Set<Scope.Closeable>();
89 const stopOwnedSessions = Effect.suspend(() =>
90 Effect.forEach(Array.from(sessions), (session) => Scope.close(session, Exit.void), {
91 discard: true,
92 concurrency: "unbounded",
93 }),
94 );
95 const publish = (flow: Flow, patch: Partial<ProviderAuthState>) =>
96 Effect.suspend(() =>
97 active === flow
98 ? SubscriptionRef.update(snapshot, (current) => ({
99 owner: flow.owner,
100 state: { ...current.state, ...patch },
101 }))
102 : Effect.void,
103 );
104
105 const requireFlow = Effect.fnUntraced(function* (owner: string, id: string) {
106 if (
107 operation !== "auth" ||
108 !active ||
109 active.owner !== owner ||
110 active.id !== id ||
111 (yield* Clock.currentTimeMillis) >= active.expiresAt
112 ) {
113 return yield* new ProviderSetupError({
114 instanceId: options.instanceId,
115 operation: "respond",
116 detail: "This sign-in is no longer active in this client.",
117 });
118 }
119 return active;
120 });
121
122 // Method discovery does not start a sign-in flow.
123 const refreshMethods = options.methods.pipe(
124 Effect.flatMap((methods) =>
125 SubscriptionRef.update(snapshot, (current) => ({
126 ...current,
127 state: { ...current.state, methods },
128 })),
129 ),
130 // Keep the last known methods when a refresh fails or is interrupted.
131 Effect.catch((error) =>
132 SubscriptionRef.update(snapshot, (current) => ({
133 ...current,
134 state: { ...current.state, methods: current.state.methods ?? [], message: error.detail },
135 })),
136 ),
137 );
138 yield* refreshMethods.pipe(Effect.forkIn(scope));
139
140 const controller: ProviderAuthService.ProviderAuthController = {
141 credentialBinding: options.credentialBinding,
142 refreshMethods,
143 invalidate: lock.withPermit(
144 Effect.gen(function* () {
145 if (operation !== "idle") return;
146 yield* stopOwnedSessions;
147 yield* SubscriptionRef.set(snapshot, {
148 owner: null,
149 state: {
150 ...empty,
151 methods: snapshot.value.state.methods ?? [],
152 message: "This provider's shared sign-in changed.",
153 },
154 });
155 }),
156 ),
157 isChangingCredentials: Effect.sync(() => operation !== "idle"),
158 withAccess: (task) =>
159 Effect.uninterruptibleMask((restore) =>
160 Effect.gen(function* () {
161 const parent = yield* Scope.Scope;
162 const child = yield* lock.withPermit(
163 Effect.gen(function* () {
164 if (operation !== "idle")
165 return yield* new ProviderSetupError({
166 instanceId: options.instanceId,
167 operation: "session",
168 detail: "Provider sign-in is changing. Try again after it finishes.",
169 });
170 const child = yield* Scope.make();
171 sessions.add(child);
172 yield* Scope.addFinalizer(
173 child,
174 Effect.sync(() => {
175 sessions.delete(child);
176 }),
177 );
178 yield* Scope.addFinalizer(parent, Scope.close(child, Exit.void));
179 return child;
180 }),
181 );
182 const fiber = yield* restore(task).pipe(
183 Effect.provideService(Scope.Scope, child),
184 Effect.forkIn(child),
185 );
186 return yield* restore(Fiber.await(fiber)).pipe(
187 Effect.flatMap((result) => result),
188 Effect.onExit((result) =>
189 Exit.isFailure(result) ? Scope.close(child, Exit.void) : Effect.void,
190 ),
191 );
192 }),
193 ),
194 start: (owner, stopSessions = Effect.void, selectedMethodId) =>
195 lock.withPermit(
196 Effect.gen(function* () {
197 if (operation === "auth" && active?.owner === owner) return snapshot.value.state;
198 if (operation !== "idle")
199 return yield* new ProviderSetupError({
200 instanceId: options.instanceId,
201 operation: "start",
202 detail: "Provider setup is already in progress.",
203 });
204 const id = yield* crypto.randomUUIDv4.pipe(
205 Effect.mapError(
206 () =>
207 new ProviderSetupError({
208 instanceId: options.instanceId,
209 operation: "start",
210 detail: "Could not start sign-in. Try again.",
211 }),
212 ),
213 );
214 const flow: Flow = {
215 id,
216 owner,
217 expiresAt: (yield* Clock.currentTimeMillis) + timeoutMs,
218 respond: undefined,
219 };
220 active = flow;
221 operation = "auth";
222 const state: ProviderAuthState = {
223 ...empty,
224 methods: snapshot.value.state.methods ?? [],
225 phase: "starting",
226 flowId: id,
227 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(flow.expiresAt)),
228 message: "Starting sign-in.",
229 };
230 yield* SubscriptionRef.set(snapshot, { owner, state });
231 flow.fiber = yield* Effect.gen(function* () {
232 const methods = yield* options.methods;
233 yield* publish(flow, { methods });
234 const methodId = selectedMethodId ?? options.defaultMethodId ?? methods[0]?.id;
235 if (!methodId || !methods.some((method) => method.id === methodId))
236 return yield* new ProviderSetupError({
237 instanceId: options.instanceId,
238 operation: "start",
239 detail: "The provider did not advertise this sign-in method.",
240 });
241 yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));
242 yield* options.authenticate(methodId, {
243 flowId: id,
244 setInteraction: (interaction, respond) =>
245 Effect.gen(function* () {
246 if (active !== flow) return;
247 flow.respond = respond;
248 yield* publish(flow, {
249 phase: "waiting",
250 interaction,
251 authorizationUrl:
252 interaction.type === "browser" || interaction.type === "deviceCode"
253 ? interaction.url
254 : null,
255 message: "Complete sign-in to continue.",
256 });
257 }),
258 verifying: Effect.gen(function* () {
259 flow.respond = undefined;
260 yield* publish(flow, {
261 phase: "verifying",
262 interaction: null,
263 authorizationUrl: null,
264 message: "Checking provider sign-in.",
265 });
266 }),
267 });
268 }).pipe(
269 Effect.scoped,
270 Effect.timeoutOrElse({
271 duration: timeoutMs,
272 orElse: () =>
273 Effect.fail(
274 new ProviderSetupError({
275 instanceId: options.instanceId,
276 operation: "start",
277 detail: "Sign-in expired. Start again.",
278 }),
279 ),
280 }),
281 Effect.exit,
282 Effect.flatMap((result) =>
283 Effect.gen(function* () {
284 const finishing = yield* lock.withPermit(
285 Effect.sync(() => {
286 if (active !== flow) return false;
287 operation = "stopping";
288 return true;
289 }),
290 );
291 if (!finishing) return;
292 if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
293 yield* lock.withPermit(
294 Effect.gen(function* () {
295 if (active !== flow) return;
296 yield* publish(flow, {
297 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
298 interaction: null,
299 authorizationUrl: null,
300 expiresAt: null,
301 message: Exit.isSuccess(result)
302 ? "Sign-in complete."
303 : failureMessage(result.cause),
304 });
305 active = undefined;
306 operation = "idle";
307 }),
308 );
309 }),
310 ),
311 Effect.interruptible,
312 Effect.forkIn(scope),
313 );
314 return state;
315 }).pipe(Effect.uninterruptible),
316 ),
317 respond: (owner, input) =>
318 Effect.uninterruptibleMask((restore) =>
319 Effect.gen(function* () {
320 const { flow, fiber, ready } = yield* lock.withPermit(
321 Effect.gen(function* () {
322 const flow = yield* requireFlow(owner, input.flowId);
323 const interaction = snapshot.value.state.interaction;
324 if (
325 !interaction ||
326 interaction.id !== input.interactionId ||
327 interaction.type !== input.response.type ||
328 !flow.respond
329 )
330 return yield* new ProviderSetupError({
331 instanceId: options.instanceId,
332 operation: "respond",
333 detail: "This sign-in interaction is no longer available.",
334 });
335 if (flow.responseFiber)
336 return yield* new ProviderSetupError({
337 instanceId: options.instanceId,
338 operation: "respond",
339 detail: "A sign-in response is already in progress.",
340 });
341 const ready = yield* Deferred.make<void>();
342 const callback = flow.respond;
343 const fiber = yield* Deferred.await(ready).pipe(
344 Effect.andThen(Effect.suspend(() => callback(input.response))),
345 Effect.interruptible,
346 Effect.forkIn(scope),
347 );
348 flow.responseFiber = fiber;
349 return { flow, fiber, ready };
350 }),
351 );
352 yield* Deferred.succeed(ready, undefined);
353 yield* restore(Fiber.join(fiber)).pipe(
354 Effect.onInterrupt(() => Fiber.interrupt(fiber).pipe(Effect.asVoid)),
355 Effect.ensuring(
356 lock.withPermit(
357 Effect.sync(() => {
358 if (flow.responseFiber === fiber) delete flow.responseFiber;
359 }),
360 ),
361 ),
362 );
363 return snapshot.value.state;
364 }),
365 ),
366 complete: () =>
367 Effect.fail(
368 new ProviderSetupError({
369 instanceId: options.instanceId,
370 operation: "complete",
371 detail: "This provider does not accept a pasted redirect URL.",
372 }),
373 ),
374 cancel: (owner, id) =>
375 Effect.gen(function* () {
376 const flow = yield* lock.withPermit(
377 Effect.gen(function* () {
378 const flow = yield* requireFlow(owner, id);
379 yield* publish(flow, {
380 phase: "cancelled",
381 interaction: null,
382 authorizationUrl: null,
383 expiresAt: null,
384 message: "Sign-in cancelled.",
385 });
386 active = undefined;
387 operation = "stopping";
388 return flow;
389 }),
390 );
391 if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
392 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
393 operation = "idle";
394 return snapshot.value.state;
395 }).pipe(Effect.uninterruptible),
396 logout: (stopSessions) =>
397 Effect.gen(function* () {
398 const flow = yield* lock.withPermit(
399 Effect.gen(function* () {
400 if (operation !== "idle" && operation !== "auth")
401 return yield* new ProviderSetupError({
402 instanceId: options.instanceId,
403 operation: "logout",
404 detail: "Provider setup is already stopping.",
405 });
406 operation = "stopping";
407 const flow = active;
408 active = undefined;
409 return flow;
410 }),
411 );
412 const result = yield* Effect.gen(function* () {
413 if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
414 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
415 yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));
416 yield* options.logout;
417 }).pipe(Effect.exit);
418 const state: ProviderAuthState = {
419 ...empty,
420 methods: snapshot.value.state.methods ?? [],
421 phase: Exit.isSuccess(result) ? "idle" : "failed",
422 message: Exit.isSuccess(result) ? "Signed out." : "Could not sign out. Try again.",
423 };
424 yield* lock.withPermit(
425 Effect.gen(function* () {
426 yield* SubscriptionRef.set(snapshot, { owner: null, state });
427 operation = "idle";
428 }),
429 );
430 if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
431 return state;
432 }).pipe(Effect.uninterruptible),
433 subscribe: (owner) =>
434 SubscriptionRef.changes(snapshot).pipe(
435 Stream.map((current) =>
436 current.owner === null || current.owner === owner
437 ? current.state
438 : {
439 ...current.state,
440 flowId: null,
441 authorizationUrl: null,
442 interaction: null,
443 expiresAt: null,
444 message: active
445 ? "Sign-in is in progress in another client."
446 : current.state.message,
447 },
448 ),
449 ),
450 };
451 yield* Effect.addFinalizer(() =>
452 Effect.gen(function* () {
453 operation = "closed";
454 const flow = active;
455 active = undefined;
456 if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
457 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
458 // Settings edits rebuild instances; admitted sessions (including those of
459 // peers sharing this binding) end with their own scopes, not this one.
460 }),
461 );
462 return controller;
463});