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

CloudAuthProvider.tsx

218 lines7.7 KB

1import { ClerkProvider, useAuth } from "@clerk/expo";
2import { tokenCache } from "@clerk/expo/token-cache";
3import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
4import {
5 reportAtomCommandResult,
6 settleAsyncResult,
7 settlePromise,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import * as Effect from "effect/Effect";
11import { type ReactNode, useEffect, useRef } from "react";
12​
13import { runtime } from "../../lib/runtime";
14import { appAtomRegistry } from "../../state/atom-registry";
15import { useAtomCommand } from "../../state/use-atom-command";
16import {
17 getComposerCloudAccountId,
18 restoreCloudComposerDrafts,
19} from "../../state/use-composer-drafts";
20import {
21 releaseAgentAwarenessRelayTokenProvider,
22 setAgentAwarenessRelayTokenProvider,
23 unregisterAgentAwarenessDeviceForCurrentUser,
24} from "../agent-awareness/remoteRegistration";
25import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
26import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
27import { removeCloudEnvironments } from "./cloud-drafts";
28​
29function resetManagedRelayTokenCache() {
30 return settleAsyncResult(() =>
31 runtime.runPromiseExit(
32 ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
33 ),
34 );
36​
37export function deactivateCloudRelayAccount(): void {
38 setAgentAwarenessRelayTokenProvider(null);
39 setManagedRelaySession(appAtomRegistry, null);
41​
42export function activateCloudRelayAccount(
43 accountId: string,
44 tokenProvider: () => Promise<string | null>,
45): void {
46 setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
47 setManagedRelaySession(appAtomRegistry, {
48 accountId,
49 readClerkToken: tokenProvider,
50 });
52​
53function CloudAuthBridge(props: { readonly children: ReactNode }) {
54 const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
55 const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, {
56 reportFailure: false,
57 reportDefect: false,
58 });
59 const previousTokenProviderRef = useRef<{
60 readonly userId: string;
61 readonly provider: () => Promise<string | null>;
62 } | null>(null);
63 const observedAccountRef = useRef<string | null | undefined>(undefined);
64 const accountTransitionRef = useRef<Promise<void> | null>(null);
65​
66 useEffect(() => {
67 let cancelled = false;
68 if (!isLoaded) {
69 return;
70 }
71​
72 const previousObservedAccount = observedAccountRef.current;
73 const nextAccount = isSignedIn && userId ? userId : null;
74 observedAccountRef.current = nextAccount;
75​
76 // Every sign-in or account switch that completes during this session (a
77 // cold start observes undefined → account and must not re-prompt) requests
78 // the T3 Connect onboarding sheet — account transitions clear the
79 // connected environments, so each new session starts with no devices to
80 // reach. The request itself is issued after the cleanup transition inside
81 // activateSession, so the sheet never lists the previous account's
82 // environments; sign-out drops any not-yet-presented request instead.
83 const isAccountTransition =
84 previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
85 if (isAccountTransition && nextAccount === null) {
86 clearConnectOnboardingRequest();
87 }
88​
89 const cleanUpAccount = async (
90 previous: {
91 readonly userId: string;
92 readonly provider: () => Promise<string | null>;
93 } | null,
94 accountId: string | null,
95 ) => {
96 const removal = await removeRelayEnvironments(accountId);
97 if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
98 const cleanup = [
99 resetManagedRelayTokenCache(),
100 ...(previous
101 ? [
102 settleAsyncResult(() =>
103 runtime.runPromiseExit(
104 unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),
105 ),
106 ),
107 ]
108 : []),
109 ];
110 const results = await Promise.all(cleanup);
111 for (const result of results) {
112 reportAtomCommandResult(result, { label: "cloud account cleanup" });
113 }
114 };
115 const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => {
116 const previousTransition = accountTransitionRef.current ?? Promise.resolve();
117 accountTransitionRef.current = previousTransition
118 .catch(() => {})
119 .then(() => cleanUpAccount(previous, previousObservedAccount ?? null));
120 return accountTransitionRef.current;
121 };
122​
123 if (!isSignedIn || !userId) {
124 const previous = previousTokenProviderRef.current;
125 previousTokenProviderRef.current = null;
126 deactivateCloudRelayAccount();
127 if (previousObservedAccount !== null) {
128 void settlePromise(() => queueAccountCleanup(previous)).then((result) => {
129 reportAtomCommandResult(result, { label: "cloud account cleanup" });
130 });
131 }
132 return;
133 }
134​
135 const previous = previousTokenProviderRef.current;
136 const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
137 const activateSession = () => {
138 if (cancelled) {
139 return;
140 }
141 previousTokenProviderRef.current = { userId, provider: tokenProvider };
142 activateCloudRelayAccount(userId, tokenProvider);
143 if (isAccountTransition) {
144 requestConnectOnboarding(userId);
145 }
146 };
147 const activateAfterTransition = (transition: Promise<void>) => {
148 const activation = (async () => {
149 await transition;
150 if (cancelled) return;
151 const storedAccount = await getComposerCloudAccountId();
152 if (storedAccount !== null && storedAccount !== userId) {
153 await cleanUpAccount(null, storedAccount);
154 }
155 if (cancelled) return;
156 await restoreCloudComposerDrafts(userId);
157 activateSession();
158 })();
159 accountTransitionRef.current = activation;
160 void settlePromise(() => activation).then((result) => {
161 reportAtomCommandResult(result, { label: "cloud account activation" });
162 });
163 };
164 if (
165 previousObservedAccount !== undefined &&
166 previousObservedAccount !== null &&
167 previousObservedAccount !== userId
168 ) {
169 previousTokenProviderRef.current = null;
170 deactivateCloudRelayAccount();
171 activateAfterTransition(queueAccountCleanup(previous));
172 } else {
173 // A failed disk write can be retried. The persisted account check above
174 // still requires cleanup before activating a different account.
175 activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {}));
176 }
177​
178 return () => {
179 cancelled = true;
180 };
181 }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
182​
183 useEffect(
184 () => () => {
185 previousTokenProviderRef.current = null;
186 // Unmounting is not a sign-out: the user is usually still signed in, so
187 // detach the provider without ending lock-screen activities or wiping the
188 // persisted registration (a remount reuses both).
189 releaseAgentAwarenessRelayTokenProvider();
190 setManagedRelaySession(appAtomRegistry, null);
191 },
192 [],
193 );
194​
195 return props.children;
197​
198export function CloudAuthProvider(props: { readonly children: ReactNode }) {
199 const config = resolveCloudPublicConfig();
200 const publishableKey = config.clerk.publishableKey;
201 const relayUrl = config.relay.url;
202​
203 useEffect(() => {
204 if (!publishableKey || !relayUrl) {
205 deactivateCloudRelayAccount();
206 }
207 }, [publishableKey, relayUrl]);
208​
209 if (!publishableKey || !relayUrl) {
210 return props.children;
211 }
212​
213 return (
214 <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
215 <CloudAuthBridge>{props.children}</CloudAuthBridge>
216 </ClerkProvider>
217 );