Open History to see the last commit
1import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
2import * as Data from "effect/Data";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Stream from "effect/Stream";
6import * as SubscriptionRef from "effect/SubscriptionRef";
7import { HttpClient } from "effect/http";
8import { AsyncResult, Atom } from "effect/reactivity";
9
10import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
11import * as EnvironmentRegistry from "../connection/registry.ts";
12import type { PreparedConnection } from "../connection/model.ts";
13import * as EnvironmentSupervisor from "../connection/supervisor.ts";
14import { environmentEndpointUrl } from "../environment/endpoint.ts";
15import * as ManagedRelay from "../relay/managedRelay.ts";
16import { safeErrorLogAttributes } from "../errors/safeLog.ts";
17import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
18import { followStreamInEnvironment } from "./environmentStreams.ts";
19
20/** @public Required to name the error in consumers' inferred session results. */
21export class SessionHttpClientUnavailable extends Data.TaggedError(
22 "SessionHttpClientUnavailable",
23) {}
24
25function initialConfigOption<E>(
26 initialConfig: Effect.Effect<ServerConfig, E>,
27): Effect.Effect<Option.Option<ServerConfig>> {
28 return initialConfig.pipe(
29 Effect.asSome,
30 Effect.catch((error) =>
31 Effect.logWarning("Could not load the initial environment configuration.").pipe(
32 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
33 Effect.as(Option.none<ServerConfig>()),
34 ),
35 ),
36 );
37}
38
39// Bounded so a wedged environment cannot pin the permissions check (and with it
40// the settings UI) in a loading state for long.
41const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;
42
43/**
44 * Read the granted scopes of this client's session on one environment via its
45 * `/api/auth/session` endpoint, using the connection's authentication method
46 * and refreshing relay credentials when needed.
47 */
48export const fetchEnvironmentSessionState = Effect.fn(
49 "clientRuntime.state.fetchEnvironmentSessionState",
50)(function* (input: {
51 readonly prepared: PreparedConnection;
52 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
53 readonly remoteAuthorization?: Option.Option<
54 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
55 >;
56 readonly timeoutMs?: number;
57}) {
58 return yield* executeAuthenticatedEnvironmentHttpRequest({
59 ...input,
60 group: "auth",
61 method: "GET",
62 url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/auth/session"),
63 timeoutMs: input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,
64 request: ({ client, headers }) => client.session({ headers }),
65 // This endpoint returns 200 with authenticated:false for expired credentials.
66 isUnauthorizedResponse: (response) => !response.authenticated,
67 });
68});
69
70function makeEnvironmentSessionAtoms<R, E>(
71 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
72) {
73 const initialConfigAtom = Atom.family((environmentId: EnvironmentId) =>
74 runtime.atom(
75 followStreamInEnvironment(
76 environmentId,
77 Stream.unwrap(
78 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
79 Effect.map((supervisor) =>
80 SubscriptionRef.changes(supervisor.session).pipe(
81 Stream.mapEffect(
82 Option.match({
83 onNone: () => Effect.succeed(Option.none<ServerConfig>()),
84 onSome: (session) => initialConfigOption(session.initialConfig),
85 }),
86 ),
87 ),
88 ),
89 ),
90 ),
91 ),
92 { initialValue: Option.none() },
93 ),
94 );
95
96 // This is only the bootstrap config captured when a transport session is
97 // established. Consumers that need current provider/settings state must use
98 // createServerEnvironmentAtoms(...).configValueAtom instead.
99 const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
100 Atom.make((get): ServerConfig | null =>
101 Option.getOrNull(
102 Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () =>
103 Option.none(),
104 ),
105 ),
106 ).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
107 );
108
109 const preparedConnectionAtom = Atom.family((environmentId: EnvironmentId) =>
110 runtime.atom(
111 followStreamInEnvironment(
112 environmentId,
113 Stream.unwrap(
114 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
115 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.prepared)),
116 ),
117 ),
118 ),
119 { initialValue: Option.none<PreparedConnection>() },
120 ),
121 );
122
123 const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
124 Atom.make((get) =>
125 Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () =>
126 Option.none<PreparedConnection>(),
127 ),
128 ).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
129 );
130
131 // Keyed on the prepared connection's identity: a reconnect (new credential,
132 // new base URL) swaps the prepared value, which re-runs the fetch, so scope
133 // changes from re-pairing are picked up without an explicit refresh.
134 const sessionStateAtom = Atom.family((environmentId: EnvironmentId) =>
135 runtime
136 .atom((get) => {
137 const prepared = Option.getOrNull(get(preparedConnectionValueAtom(environmentId)));
138 if (prepared === null) {
139 return Effect.never;
140 }
141 return Effect.gen(function* () {
142 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
143 const remoteAuthorization = yield* Effect.serviceOption(
144 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
145 );
146 const client = yield* Effect.serviceOption(HttpClient.HttpClient);
147 if (Option.isNone(client)) return yield* new SessionHttpClientUnavailable();
148 return yield* fetchEnvironmentSessionState({
149 prepared,
150 signer,
151 remoteAuthorization,
152 }).pipe(Effect.provideService(HttpClient.HttpClient, client.value));
153 });
154 })
155 .pipe(
156 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
157 Atom.setIdleTTL(5 * 60_000),
158 Atom.withLabel(`environment-session-state:${environmentId}`),
159 ),
160 );
161
162 const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
163 Atom.make(
164 (get): AuthSessionState | null =>
165 Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
166 ).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
167 );
168
169 return {
170 initialConfigAtom,
171 initialConfigValueAtom,
172 preparedConnectionAtom,
173 preparedConnectionValueAtom,
174 sessionStateAtom,
175 sessionStateValueAtom,
176 };
177}
178
179const sessionAtomsByRuntime = new WeakMap<object, ReturnType<typeof makeEnvironmentSessionAtoms>>();
180
181/** Commands and UI share one session fetch and the same reconnect invalidation. */
182export function createEnvironmentSessionAtoms<R, E>(
183 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
184): ReturnType<typeof makeEnvironmentSessionAtoms<R, E>> {
185 const existing = sessionAtomsByRuntime.get(runtime);
186 if (existing) return existing as ReturnType<typeof makeEnvironmentSessionAtoms<R, E>>;
187 const atoms = makeEnvironmentSessionAtoms(runtime);
188 sessionAtomsByRuntime.set(runtime, atoms);
189 return atoms;
190}