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

CloudAuthProvider.tsx

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