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: (update, stopSessions) =>
144 Effect.gen(function* () {
145 yield* lock.withPermit(
146 Effect.gen(function* () {
147 if (operation !== "idle")
148 return yield* new ProviderSetupError({
149 instanceId: options.instanceId,
150 operation: "import",
151 detail: "Finish or cancel the existing sign-in first.",
152 });
153 operation = "stopping";
154 }),
155 );
156 const result = yield* Effect.gen(function* () {
157 yield* stopOwnedSessions;
158 yield* stopSessions;
159 yield* update;
160 yield* refreshMethods;
161 }).pipe(Effect.exit);
162 const state: ProviderAuthState = {
163 ...empty,
164 methods: snapshot.value.state.methods ?? [],
165 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
166 message: Exit.isSuccess(result) ? null : failureMessage(result.cause),
167 };
168 yield* lock.withPermit(
169 Effect.gen(function* () {
170 yield* SubscriptionRef.set(snapshot, { owner: null, state });
171 operation = "idle";
172 }),
173 );
174 if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
175 return state;
176 }).pipe(Effect.uninterruptible),
177 refreshMethods,
178 invalidate: lock.withPermit(
179 Effect.gen(function* () {
180 if (operation !== "idle") return;
181 yield* stopOwnedSessions;
182 yield* SubscriptionRef.set(snapshot, {
183 owner: null,
184 state: {
185 ...empty,
186 methods: snapshot.value.state.methods ?? [],
187 message: "This provider's shared sign-in changed.",
188 },
189 });
190 }),
191 ),
192 isChangingCredentials: Effect.sync(() => operation !== "idle"),
193 withAccess: (task) =>
194 Effect.uninterruptibleMask((restore) =>
195 Effect.gen(function* () {
196 const parent = yield* Scope.Scope;
197 const child = yield* lock.withPermit(
198 Effect.gen(function* () {
199 if (operation !== "idle")
200 return yield* new ProviderSetupError({
201 instanceId: options.instanceId,
202 operation: "session",
203 detail: "Provider sign-in is changing. Try again after it finishes.",
204 });
205 const child = yield* Scope.make();
206 sessions.add(child);
207 yield* Scope.addFinalizer(
208 child,
209 Effect.sync(() => {
210 sessions.delete(child);
211 }),
212 );
213 yield* Scope.addFinalizer(parent, Scope.close(child, Exit.void));
214 return child;
215 }),
216 );
217 const fiber = yield* restore(task).pipe(
218 Effect.provideService(Scope.Scope, child),
219 Effect.forkIn(child),
220 );
221 return yield* restore(Fiber.await(fiber)).pipe(
222 Effect.flatMap((result) => result),
223 Effect.onExit((result) =>
224 Exit.isFailure(result) ? Scope.close(child, Exit.void) : Effect.void,
225 ),
226 );
227 }),
228 ),
229 start: (owner, stopSessions = Effect.void, selectedMethodId, returnUrl, callbackMode) =>
230 lock.withPermit(
231 Effect.gen(function* () {
232 if (operation === "auth" && active?.owner === owner) return snapshot.value.state;
233 if (operation !== "idle")
234 return yield* new ProviderSetupError({
235 instanceId: options.instanceId,
236 operation: "start",
237 detail: "Provider setup is already in progress.",
238 });
239 const id = yield* crypto.randomUUIDv4().pipe(
240 Effect.mapError(
241 () =>
242 new ProviderSetupError({
243 instanceId: options.instanceId,
244 operation: "start",
245 detail: "Could not start sign-in. Try again.",
246 }),
247 ),
248 );
249 const flow: Flow = {
250 id,
251 owner,
252 expiresAt: (yield* Clock.currentTimeMillis) + timeoutMs,
253 respond: undefined,
254 };
255 active = flow;
256 operation = "auth";
257 const state: ProviderAuthState = {
258 ...empty,
259 methods: snapshot.value.state.methods ?? [],
260 phase: "starting",
261 flowId: id,
262 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(flow.expiresAt)),
263 message: "Starting sign-in.",
264 };
265 yield* SubscriptionRef.set(snapshot, { owner, state });
266 flow.fiber = yield* Effect.gen(function* () {
267 const methods = yield* options.methods;
268 yield* publish(flow, { methods });
269 const methodId = selectedMethodId ?? options.defaultMethodId ?? methods[0]?.id;
270 if (!methodId || !methods.some((method) => method.id === methodId))
271 return yield* new ProviderSetupError({
272 instanceId: options.instanceId,
273 operation: "start",
274 detail: "The provider did not advertise this sign-in method.",
275 });
276 yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));
277 yield* options.authenticate(methodId, {
278 flowId: id,
279 expiresAt: flow.expiresAt,
280 ...(returnUrl ? { returnUrl } : {}),
281 ...(callbackMode ? { callbackMode } : {}),
282 setInteraction: (interaction, respond, complete) =>
283 Effect.gen(function* () {
284 if (active !== flow) return;
285 flow.respond = respond;
286 flow.complete = complete;
287 yield* publish(flow, {
288 phase: "waiting",
289 interaction,
290 authorizationUrl:
291 interaction.type === "browser" || interaction.type === "deviceCode"
292 ? interaction.url
293 : null,
294 message: "Complete sign-in to continue.",
295 });
296 }),
297 verifying: Effect.gen(function* () {
298 flow.respond = undefined;
299 flow.complete = undefined;
300 yield* publish(flow, {
301 phase: "verifying",
302 interaction: null,
303 authorizationUrl: null,
304 message: "Checking provider sign-in.",
305 });
306 }),
307 });
308 }).pipe(
309 Effect.scoped,
310 Effect.timeoutOrElse({
311 duration: timeoutMs,
312 orElse: () =>
313 Effect.fail(
314 new ProviderSetupError({
315 instanceId: options.instanceId,
316 operation: "start",
317 detail: "Sign-in expired. Start again.",
318 }),
319 ),
320 }),
321 Effect.exit,
322 Effect.flatMap((result) =>
323 Effect.gen(function* () {
324 const finishing = yield* lock.withPermit(
325 Effect.sync(() => {
326 if (active !== flow) return false;
327 operation = "stopping";
328 return true;
329 }),
330 );
331 if (!finishing) return;
332 if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
333 yield* lock.withPermit(
334 Effect.gen(function* () {
335 if (active !== flow) return;
336 if (options.refreshMethodsAfterAuth) yield* refreshMethods;
337 yield* publish(flow, {
338 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
339 interaction: null,
340 authorizationUrl: null,
341 expiresAt: null,
342 message: Exit.isSuccess(result)
343 ? "Sign-in complete."
344 : failureMessage(result.cause),
345 });
346 active = undefined;
347 operation = "idle";
348 }),
349 );
350 }),
351 ),
352 Effect.interruptible,
353 Effect.forkIn(scope),
354 );
355 return state;
356 }).pipe(Effect.uninterruptible),
357 ),
358 respond: (owner, input) =>
359 Effect.uninterruptibleMask((restore) =>
360 Effect.gen(function* () {
361 const { flow, fiber, ready } = yield* lock.withPermit(
362 Effect.gen(function* () {
363 const flow = yield* requireFlow(owner, input.flowId);
364 const interaction = snapshot.value.state.interaction;
365 if (
366 !interaction ||
367 interaction.id !== input.interactionId ||
368 interaction.type !== input.response.type ||
369 !flow.respond
370 )
371 return yield* new ProviderSetupError({
372 instanceId: options.instanceId,
373 operation: "respond",
374 detail: "This sign-in interaction is no longer available.",
375 });
376 if (flow.responseFiber)
377 return yield* new ProviderSetupError({
378 instanceId: options.instanceId,
379 operation: "respond",
380 detail: "A sign-in response is already in progress.",
381 });
382 const ready = yield* Deferred.make<void>();
383 const callback = flow.respond;
384 const fiber = yield* Deferred.await(ready).pipe(
385 Effect.andThen(Effect.suspend(() => callback(input.response))),
386 Effect.interruptible,
387 Effect.forkIn(scope),
388 );
389 flow.responseFiber = fiber;
390 return { flow, fiber, ready };
391 }),
392 );
393 yield* Deferred.succeed(ready, undefined);
394 yield* restore(Fiber.join(fiber)).pipe(
395 Effect.onInterrupt(() => Fiber.interrupt(fiber).pipe(Effect.asVoid)),
396 Effect.ensuring(
397 lock.withPermit(
398 Effect.sync(() => {
399 if (flow.responseFiber === fiber) delete flow.responseFiber;
400 }),
401 ),
402 ),
403 );
404 return snapshot.value.state;
405 }),
406 ),
407 complete: (owner, input) =>
408 lock.withPermit(
409 Effect.gen(function* () {
410 const flow = yield* requireFlow(owner, input.flowId);
411 const interaction = snapshot.value.state.interaction;
412 if (
413 snapshot.value.state.phase !== "waiting" ||
414 interaction?.type !== "browser" ||
415 !interaction.acceptsCallback ||
416 !flow.complete
417 )
418 return yield* new ProviderSetupError({
419 instanceId: options.instanceId,
420 operation: "complete",
421 detail: "This sign-in does not accept a redirect URL.",
422 });
423 yield* flow.complete(input.callbackUrl);
424 return snapshot.value.state;
425 }),
426 ),
427 cancel: (owner, id) =>
428 Effect.gen(function* () {
429 const flow = yield* lock.withPermit(
430 Effect.gen(function* () {
431 const flow = yield* requireFlow(owner, id);
432 yield* publish(flow, {
433 phase: "cancelled",
434 interaction: null,
435 authorizationUrl: null,
436 expiresAt: null,
437 message: "Sign-in cancelled.",
438 });
439 active = undefined;
440 operation = "stopping";
441 return flow;
442 }),
443 );
444 if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
445 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
446 operation = "idle";
447 return snapshot.value.state;
448 }).pipe(Effect.uninterruptible),
449 logout: (stopSessions) =>
450 Effect.gen(function* () {
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 }).pipe(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 edits rebuild instances; admitted sessions (including those of
516 // peers sharing this binding) end with their own scopes, not this one.
517 }),
518 );
519 return controller;
520});