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