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

ProviderAuthFlow.ts

527 lines19.7 KB

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