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

managedAuth.tsx

74 lines2.7 KB

1import { useClerk } from "@clerk/react";
2import {
3 createCloudAccountService,
4 ManagedRelay,
5 setManagedRelaySession,
6} from "@t3tools/client-runtime/relay";
7import {
8 reportAtomCommandResult,
9 runAtomCommand,
10 settleAsyncResult,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import * as Effect from "effect/Effect";
14import { useEffect, type ReactNode } from "react";
15​
16import { environmentCatalog } from "../connection/catalog";
17import { runtime } from "../lib/runtime";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import { resolveRelayClerkTokenOptions } from "./publicConfig";
20​
21export function deactivateManagedRelayAuthentication(): void {
22 setManagedRelaySession(appAtomRegistry, null);
24​
25export function activateManagedRelayAuthentication(
26 accountId: string,
27 readClerkToken: () => Promise<string | null>,
28): void {
29 setManagedRelaySession(appAtomRegistry, {
30 accountId,
31 readClerkToken,
32 });
34​
35type ClerkInstance = ReturnType<typeof useClerk>;
36​
37function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
38 return async () =>
39 clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
41​
42// A failed route removal fails the switch, so the next account never activates over the old routes.
43async function cleanUpManagedRelayAccount(): Promise<void> {
44 const [removal, tokenReset] = await Promise.all([
45 runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, {
46 reportFailure: false,
47 reportDefect: false,
48 }),
49 settleAsyncResult(() =>
50 runtime.runPromiseExit(
51 ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
52 ),
53 ),
54 ]);
55 reportAtomCommandResult(tokenReset, { label: "cloud account cleanup" });
56 if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
58​
59const managedRelayAccountService = createCloudAccountService<ClerkInstance>({
60 deactivate: deactivateManagedRelayAuthentication,
61 detach: deactivateManagedRelayAuthentication,
62 cleanUp: cleanUpManagedRelayAccount,
63 activate: ({ source, accountId }) =>
64 activateManagedRelayAuthentication(accountId, clerkTokenReader(source)),
65});
66​
67export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
68 // ClerkProvider creates the Clerk instance and owns its lifetime, so the
69 // account service observes it for as long as this provider is mounted.
70 const clerk = useClerk();
71 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches the Clerk instance to the managed relay account service for the provider's lifetime
72 useEffect(() => managedRelayAccountService.attach(clerk), [clerk]);
73 return children;