feat(connect): deregister account environments from any client (#4844)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-08-12 22:46:23 +02:00
1 parent 9666b87516
commit d0b8d6306b
10 files changed
+573 -70

No files matched your search

+22
View File
@@ -1,14 +1,20 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
deregisterManagedRelayEnvironment,
ManagedRelay,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime/relay";
import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type {
RelayClientDeviceRecord,
RelayClientEnvironmentRecord,
} from "@t3tools/contracts/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -29,6 +35,22 @@ const managedRelayAtomRuntime = Atom.runtime(
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
const managedRelayMutationScheduler = createAtomCommandScheduler();
export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
managedRelayAtomRuntime,
{
label: "web:managed-relay:deregister-environment",
scheduler: managedRelayMutationScheduler,
concurrency: {
mode: "serial",
key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) =>
input.accountId,
},
execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input),
},
);
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
@@ -0,0 +1,86 @@
import { RefreshCwIcon } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
export function ClerkUserProfilePage({
action,
children,
className,
description,
title,
}: {
readonly action?: ReactNode;
readonly children: ReactNode;
readonly className?: string;
readonly description?: ReactNode;
readonly title: ReactNode;
}) {
return (
<div className={cn("w-full min-w-0 text-foreground", className)}>
<header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<div className="min-w-0">
<h2 className="text-[1.0625rem] leading-6 font-semibold">{title}</h2>
{description ? (
<p className="mt-1 max-w-[34rem] text-[0.8125rem] leading-[1.125rem] text-muted-foreground sm:min-h-9">
{description}
</p>
) : null}
</div>
{action ? <div className="shrink-0">{action}</div> : null}
</header>
{children}
</div>
);
}
export function ClerkUserProfileRefreshButton({
className,
disabled = false,
isPending,
onClick,
}: {
readonly className?: string;
readonly disabled?: boolean;
readonly isPending: boolean;
readonly onClick: () => void;
}) {
return (
<Button
size="sm"
variant="outline"
className={cn("text-[0.8125rem]", className)}
disabled={disabled || isPending}
onClick={onClick}
>
<RefreshCwIcon aria-hidden="true" className={cn("size-3.5", isPending && "animate-spin")} />
Refresh
</Button>
);
}
export function ClerkUserProfileRow({
children,
className,
icon,
}: {
readonly children: ReactNode;
readonly className?: string;
readonly icon: ReactNode;
}) {
return (
<li className={cn("border-t py-4 first:border-t-0", className)}>
<div className="flex items-start gap-3">
<div
aria-hidden="true"
className="flex size-8 shrink-0 items-center justify-center rounded-lg border bg-muted/32 text-muted-foreground"
>
{icon}
</div>
<div className="min-w-0 flex-1">{children}</div>
</div>
</li>
);
}
@@ -1,8 +1,7 @@
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
import { RefreshCwIcon, SmartphoneIcon } from "lucide-react";
import { SmartphoneIcon } from "lucide-react";
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
import { cn } from "../../lib/utils";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
@@ -12,6 +11,11 @@ import {
mobileClientPlatformLabel,
mobileClientUpdatedAtLabel,
} from "./MobileClientsUserProfilePage.logic";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
ClerkUserProfileRow,
} from "./ClerkUserProfilePage";
const MOBILE_CLIENT_SKELETON_ROWS = ["primary", "secondary"] as const;
@@ -31,53 +35,47 @@ function MobileClientStatusBadge({
function MobileClientRow({ device }: { readonly device: RelayClientDeviceRecord }) {
return (
<li className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm/4">
<div className="flex items-start gap-3">
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg border bg-muted/40 text-muted-foreground">
<SmartphoneIcon className="size-4" />
</div>
<div className="min-w-0 flex-1">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-foreground">{device.label}</h3>
<p className="text-xs text-muted-foreground">{mobileClientPlatformLabel(device)}</p>
</div>
<p className="shrink-0 text-[11px] text-muted-foreground/75">
{mobileClientUpdatedAtLabel(device.updatedAt)}
</p>
</div>
<div className="mt-3 flex flex-wrap gap-1.5">
<MobileClientStatusBadge
enabled={device.notifications.enabled}
label="Push notifications"
/>
<MobileClientStatusBadge
enabled={device.liveActivities.enabled}
label="Live Activities"
/>
</div>
<p className="mt-2 text-xs leading-relaxed text-muted-foreground/80">
{mobileClientNotificationDetail(device)}
<ClerkUserProfileRow icon={<SmartphoneIcon className="size-4" />}>
<div className="flex flex-col gap-0.5 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
<div className="min-w-0">
<h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">
{device.label}
</h3>
<p className="text-xs leading-[1.125rem] text-muted-foreground">
{mobileClientPlatformLabel(device)}
</p>
</div>
<p className="shrink-0 text-[0.6875rem] leading-4 text-muted-foreground/75">
{mobileClientUpdatedAtLabel(device.updatedAt)}
</p>
</div>
</li>
<div className="mt-2 flex flex-wrap gap-1.5">
<MobileClientStatusBadge
enabled={device.notifications.enabled}
label="Push notifications"
/>
<MobileClientStatusBadge enabled={device.liveActivities.enabled} label="Live Activities" />
</div>
<p className="mt-1.5 text-xs leading-[1.125rem] text-muted-foreground/80">
{mobileClientNotificationDetail(device)}
</p>
</ClerkUserProfileRow>
);
}
function MobileClientsSkeleton() {
return (
<div aria-label="Loading mobile clients" className="space-y-3" role="status">
<div aria-label="Loading mobile clients" className="divide-y border-t" role="status">
{MOBILE_CLIENT_SKELETON_ROWS.map((row) => (
<div key={row} className="rounded-xl border p-4">
<div key={row} className="py-4">
<div className="flex gap-3">
<Skeleton className="size-9 shrink-0 rounded-lg" />
<Skeleton className="size-8 shrink-0 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-3.5 w-36" />
<Skeleton className="h-3 w-28" />
<div className="flex gap-2 pt-1">
<Skeleton className="h-5 w-28" />
<Skeleton className="h-5 w-24" />
<div className="flex gap-2">
<Skeleton className="h-4.5 w-28" />
<Skeleton className="h-4.5 w-24" />
</div>
</div>
</div>
@@ -89,13 +87,13 @@ function MobileClientsSkeleton() {
function EmptyMobileClients() {
return (
<Empty className="min-h-72 rounded-xl border border-dashed bg-muted/15">
<EmptyMedia variant="icon">
<Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">
<EmptyMedia className="mb-0" variant="icon">
<SmartphoneIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No mobile clients</EmptyTitle>
<EmptyDescription>
<EmptyTitle className="text-[1.0625rem] leading-6">No mobile clients</EmptyTitle>
<EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">
Sign in to T3 Code on your iPhone to register it for push notifications and Live
Activities.
</EmptyDescription>
@@ -112,29 +110,20 @@ export function MobileClientsUserProfilePage() {
const hasErrorWithoutData = devicesState.error !== null && devicesState.data === null;
return (
<div className="flex min-h-[30rem] w-full flex-col bg-background text-foreground">
<header className="flex flex-col gap-4 border-b px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="text-base font-semibold tracking-[-0.01em]">Mobile clients</h2>
<p className="mt-1 text-sm text-muted-foreground">
Devices registered to receive T3 Connect activity from your environments.
</p>
</div>
<Button
size="sm"
variant="outline"
disabled={devicesState.isPending}
<ClerkUserProfilePage
title="Mobile clients"
description="Devices registered to receive T3 Connect activity from your environments."
action={
<ClerkUserProfileRefreshButton
isPending={devicesState.isPending}
onClick={devicesState.refresh}
>
<RefreshCwIcon className={cn("size-3.5", devicesState.isPending && "animate-spin")} />
Refresh
</Button>
</header>
<div className="flex-1 p-6">
/>
}
>
<div>
{devicesState.error ? (
<div
className="mb-4 flex flex-col gap-3 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm sm:flex-row sm:items-center sm:justify-between"
className="mb-4 flex flex-col gap-3 border-t border-destructive/35 py-3 text-[0.8125rem] sm:flex-row sm:items-center sm:justify-between"
role="alert"
>
<div>
@@ -152,7 +141,7 @@ export function MobileClientsUserProfilePage() {
{isInitialLoad ? (
<MobileClientsSkeleton />
) : hasErrorWithoutData ? null : devices.length > 0 ? (
<ul className="space-y-3">
<ul className="border-t">
{devices.map((device) => (
<MobileClientRow key={device.deviceId} device={device} />
))}
@@ -161,6 +150,6 @@ export function MobileClientsUserProfilePage() {
<EmptyMobileClients />
)}
</div>
</div>
</ClerkUserProfilePage>
);
}
@@ -1,9 +1,10 @@
import { UserButton, useAuth } from "@clerk/react";
import { LogInIcon, SmartphoneIcon } from "lucide-react";
import { LogInIcon, ServerIcon, SmartphoneIcon } from "lucide-react";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
export function T3ConnectSidebarSignIn() {
@@ -39,6 +40,13 @@ function ConfiguredT3ConnectSidebarAvatar() {
>
<MobileClientsUserProfilePage />
</UserButton.UserProfilePage>
<UserButton.UserProfilePage
label="T3 Connect"
labelIcon={<ServerIcon className="size-4" />}
url="t3-connect"
>
<T3ConnectUserProfilePage />
</UserButton.UserProfilePage>
</UserButton>
);
}
@@ -0,0 +1,63 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { T3ConnectEnvironmentRow } from "./T3ConnectUserProfilePage";
const environment: RelayClientEnvironmentRecord = {
environmentId: "environment-1" as EnvironmentId,
label: "Studio Mac",
endpoint: {
httpBaseUrl: "https://studio.example.com",
wsBaseUrl: "wss://studio.example.com",
providerKind: "cloudflare_tunnel",
},
linkedAt: "2026-08-12T12:00:00.000Z",
};
function renderRow({
confirmationOpen = false,
mutationPending = false,
}: {
readonly confirmationOpen?: boolean;
readonly mutationPending?: boolean;
} = {}) {
return renderToStaticMarkup(
<T3ConnectEnvironmentRow
environment={environment}
confirmationOpen={confirmationOpen}
mutationPending={mutationPending}
onConfirmationChange={vi.fn()}
onDeregister={vi.fn()}
/>,
);
}
describe("T3 Connect environment row", () => {
it("keeps deregistration confirmation inline and collapsed by default", () => {
const markup = renderRow();
expect(markup).toContain("Studio Mac");
expect(markup).toContain("Deregister");
expect(markup).not.toContain("Deregister server");
expect(markup).not.toContain("Confirm deregistration of Studio Mac");
});
it("expands Clerk-style confirmation content beneath the environment row", () => {
const markup = renderRow({ confirmationOpen: true });
expect(markup).toContain("Deregister server");
expect(markup).toContain("“Studio Mac” will be removed from this account.");
expect(markup).toContain("Confirm deregistration of Studio Mac");
expect(markup).toContain("Local connections on your devices are not changed.");
expect(markup).toContain("Cancel");
});
it("locks the confirmation actions while deregistration is pending", () => {
const markup = renderRow({ confirmationOpen: true, mutationPending: true });
expect(markup).toContain("Deregistering…");
expect(markup.match(/ disabled=""/g)).toHaveLength(3);
});
});
@@ -0,0 +1,260 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import { ServerIcon } from "lucide-react";
import { useRef, useState } from "react";
import {
deregisterManagedRelayEnvironmentCommand,
useManagedRelayEnvironments,
} from "../../cloud/managedRelayState";
import { useAtomCommand } from "../../state/use-atom-command";
import { Button } from "../ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { toastManager } from "../ui/toast";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
ClerkUserProfileRow,
} from "./ClerkUserProfilePage";
const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
function linkedAtLabel(value: string): string {
const linkedAt = new Date(value);
return Number.isNaN(linkedAt.getTime())
? "Link date unavailable"
: `Linked ${linkedAtFormatter.format(linkedAt)}`;
}
function endpointLabel(environment: RelayClientEnvironmentRecord): string {
return environment.endpoint.providerKind === "cloudflare_tunnel"
? "Managed tunnel"
: "Activity publishing only";
}
export function T3ConnectEnvironmentRow(props: {
readonly environment: RelayClientEnvironmentRecord;
readonly confirmationOpen: boolean;
readonly mutationPending: boolean;
readonly onConfirmationChange: (open: boolean) => void;
readonly onDeregister: (environment: RelayClientEnvironmentRecord) => void;
}) {
const { environment } = props;
return (
<ClerkUserProfileRow icon={<ServerIcon className="size-4" />}>
<Collapsible open={props.confirmationOpen} onOpenChange={props.onConfirmationChange}>
<div className="flex items-start gap-4">
<div className="min-w-0 flex-1">
<h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">
{environment.label}
</h3>
<p className="mt-1 text-xs leading-[1.125rem] text-muted-foreground">
{linkedAtLabel(environment.linkedAt)} · {endpointLabel(environment)}
</p>
</div>
<CollapsibleTrigger
render={
<Button
size="sm"
variant="destructive-outline"
className="text-[0.8125rem]"
disabled={props.mutationPending}
>
Deregister
</Button>
}
/>
</div>
<CollapsiblePanel>
<div className="pt-3">
<div
className="rounded-lg border border-input bg-muted/32 px-5 py-4 shadow-xs/5"
role="group"
aria-label={`Confirm deregistration of ${environment.label}`}
>
<h4 className="text-[0.8125rem] leading-[1.125rem] font-semibold text-foreground">
Deregister server
</h4>
<p className="mt-1 text-[0.8125rem] leading-[1.125rem] text-muted-foreground">
“{environment.label}” will be removed from this account.
</p>
<p className="mt-4 max-w-xl text-[0.8125rem] leading-[1.125rem] text-muted-foreground">
T3 Connect access will be revoked, any managed tunnel will be removed, and a host
space will become available. Local connections on your devices are not changed.
</p>
<div className="mt-4 flex justify-end gap-2">
<Button
size="sm"
variant="ghost"
className="text-[0.8125rem]"
disabled={props.mutationPending}
onClick={() => props.onConfirmationChange(false)}
>
Cancel
</Button>
<Button
size="sm"
variant="destructive"
className="text-[0.8125rem]"
disabled={props.mutationPending}
onClick={() => props.onDeregister(environment)}
>
{props.mutationPending ? "Deregistering…" : "Deregister"}
</Button>
</div>
</div>
</div>
</CollapsiblePanel>
</Collapsible>
</ClerkUserProfileRow>
);
}
export function T3ConnectUserProfilePage() {
const environmentsState = useManagedRelayEnvironments();
const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
reportFailure: false,
});
const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
useState<EnvironmentId | null>(null);
const [confirmingEnvironmentId, setConfirmingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const mutationPendingRef = useRef(false);
const [removedEnvironments, setRemovedEnvironments] = useState<{
readonly accountId: string | null;
readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;
}>({ accountId: null, linkedAtById: new Map() });
const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {
const accountId = environmentsState.accountId;
if (!accountId || mutationPendingRef.current) return;
mutationPendingRef.current = true;
setDeregisteringEnvironmentId(environment.environmentId);
const result = await deregisterEnvironment({
accountId,
environmentId: environment.environmentId,
});
mutationPendingRef.current = false;
setDeregisteringEnvironmentId(null);
if (result._tag === "Success") {
setConfirmingEnvironmentId(null);
setRemovedEnvironments((current) => {
const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);
linkedAtById.set(environment.environmentId, environment.linkedAt);
return { accountId, linkedAtById };
});
environmentsState.refresh();
toastManager.add({
type: "success",
title: "Server deregistered",
description: "T3 Connect access was revoked and a host space is now available.",
});
return;
}
if (isAtomCommandInterrupted(result)) return;
const cause = squashAtomCommandFailure(result);
const message = cause instanceof Error ? cause.message : "Could not deregister the server.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not deregister environment", {
environmentId: environment.environmentId,
message,
traceId,
cause,
});
toastManager.add({
type: "error",
title: "Could not deregister server",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const removedEnvironmentLinkedAt =
removedEnvironments.accountId === environmentsState.accountId
? removedEnvironments.linkedAtById
: new Map<EnvironmentId, string>();
const environments = (environmentsState.data ?? []).filter(
(environment) =>
removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
);
const isInitialLoad =
!environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
return (
<ClerkUserProfilePage
title="T3 Connect"
description="Environments registered to your account. Connections on this device are managed in Settings."
action={
<ClerkUserProfileRefreshButton
disabled={deregisteringEnvironmentId !== null}
isPending={environmentsState.isPending}
onClick={environmentsState.refresh}
/>
}
>
<div>
{environmentsState.error ? (
<div className="mb-4 border-t border-destructive/35 py-3 text-[0.8125rem]" role="alert">
<p className="font-medium text-destructive-foreground">
Could not load T3 Connect environments
</p>
<p className="mt-1 text-xs text-muted-foreground">{environmentsState.error}</p>
</div>
) : null}
{isInitialLoad ? (
<p className="border-t py-4 text-[0.8125rem] text-muted-foreground" role="status">
Loading environments…
</p>
) : environments.length > 0 ? (
<ul className="border-t">
{environments.map((environment) => (
<T3ConnectEnvironmentRow
key={environment.environmentId}
environment={environment}
confirmationOpen={confirmingEnvironmentId === environment.environmentId}
mutationPending={deregisteringEnvironmentId !== null}
onConfirmationChange={(open) =>
setConfirmingEnvironmentId(open ? environment.environmentId : null)
}
onDeregister={(selected) => void handleDeregister(selected)}
/>
))}
</ul>
) : environmentsState.error ? null : (
<Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">
<EmptyMedia className="mb-0" variant="icon">
<ServerIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle className="text-[1.0625rem] leading-6">
No T3 Connect environments
</EmptyTitle>
<EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">
Link an environment from its local Settings to make it available through T3 Connect.
</EmptyDescription>
</EmptyHeader>
</Empty>
)}
</div>
</ClerkUserProfilePage>
);
}
+3 -1
View File
@@ -46,12 +46,14 @@ function AlertDialogViewport({ className, ...props }: AlertDialogPrimitive.Viewp
function AlertDialogPopup({
className,
bottomStickOnMobile = true,
portalContainer,
...props
}: AlertDialogPrimitive.Popup.Props & {
bottomStickOnMobile?: boolean;
portalContainer?: AlertDialogPrimitive.Portal.Props["container"];
}) {
return (
<AlertDialogPortal>
<AlertDialogPortal container={portalContainer}>
<AlertDialogBackdrop />
<AlertDialogViewport
className={cn(bottomStickOnMobile && "max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12")}
+11
View File
@@ -218,6 +218,17 @@ Typical uses:
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
### Deregister a T3 Connect Environment
Open your account menu and choose **T3 Connect** to see every environment registered to your
account. On mobile, open **Settings** → **T3 Connect**. Choose **Deregister** to revoke an
environment's T3 Connect access, remove any managed tunnel, and free its host space.
Deregistration is an account action and does not need a connection to the environment, so it also
works for a server that was wiped or is no longer reachable. Device-local connect and disconnect
controls remain in **Settings** → **Connections** on web and desktop or **Settings** →
**Environments** on mobile.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
@@ -16,8 +16,10 @@ import * as ManagedRelay from "./managedRelay.ts";
import {
createManagedRelayQueryManager,
createManagedRelaySession,
deregisterManagedRelayEnvironment,
managedRelayAccountChanges,
type ManagedRelayQueryEvent,
ManagedRelaySessionError,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
setManagedRelaySession,
@@ -61,11 +63,8 @@ function resetRegistry() {
registry = AtomRegistry.make();
}
function createManager(
overrides?: Partial<ManagedRelay.ManagedRelayClient["Service"]>,
onQueryEvent?: (event: ManagedRelayQueryEvent) => void,
) {
const client = ManagedRelay.ManagedRelayClient.of({
function createClient(overrides?: Partial<ManagedRelay.ManagedRelayClient["Service"]>) {
return ManagedRelay.ManagedRelayClient.of({
relayUrl: "https://relay.example.test",
listEnvironments: () => Effect.succeed([environment]),
listDevices: () => Effect.succeed([device]),
@@ -87,6 +86,13 @@ function createManager(
resetTokenCache: Effect.void,
...overrides,
});
}
function createManager(
overrides?: Partial<ManagedRelay.ManagedRelayClient["Service"]>,
onQueryEvent?: (event: ManagedRelayQueryEvent) => void,
) {
const client = createClient(overrides);
const runtime = Atom.runtime(Layer.succeed(ManagedRelay.ManagedRelayClient, client));
return createManagedRelayQueryManager(runtime, {
staleTimeMs: 60_000,
@@ -121,6 +127,43 @@ describe("createManagedRelayQueryManager", () => {
}),
);
it.effect("deregisters an environment through the current Clerk session", () =>
Effect.gen(function* () {
const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));
setSession();
yield* deregisterManagedRelayEnvironment(registry, {
accountId: "account-1",
environmentId: environment.environmentId,
}).pipe(
Effect.provideService(ManagedRelay.ManagedRelayClient, createClient({ unlinkEnvironment })),
);
expect(unlinkEnvironment).toHaveBeenCalledWith({
clerkToken: "clerk-token",
environmentId: environment.environmentId,
});
}),
);
it.effect("rejects deregistration after the account changes", () =>
Effect.gen(function* () {
const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));
setSession();
const error = yield* deregisterManagedRelayEnvironment(registry, {
accountId: "previous-account",
environmentId: environment.environmentId,
}).pipe(
Effect.provideService(ManagedRelay.ManagedRelayClient, createClient({ unlinkEnvironment })),
Effect.flip,
);
expect(error).toBeInstanceOf(ManagedRelaySessionError);
expect(unlinkEnvironment).not.toHaveBeenCalled();
}),
);
it.effect("deduplicates concurrent Clerk token reads and reuses the token until JWT expiry", () =>
Effect.gen(function* () {
const token = clerkToken(4_102_444_800);
@@ -2,6 +2,7 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import {
RelayEnvironmentConnectScope,
RelayEnvironmentStatusScope,
@@ -218,6 +219,24 @@ export const waitForManagedRelayClerkToken = Effect.fn(
});
});
/** Removes an environment from the signed-in account without contacting that environment. */
export const deregisterManagedRelayEnvironment = Effect.fn(
"clientRuntime.managedRelaySession.deregisterEnvironment",
)(function* (
registry: AtomRegistry.AtomRegistry,
input: { readonly accountId: string; readonly environmentId: EnvironmentId },
) {
const session = registry.get(managedRelaySessionAtom);
if (!session || session.accountId !== input.accountId) {
return yield* new ManagedRelaySessionError({
message: "Sign in to T3 Connect before deregistering an environment.",
});
}
const clerkToken = yield* readSessionClerkToken(session);
const relay = yield* ManagedRelay.ManagedRelayClient;
yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });
});
function requireClerkToken(
get: Atom.AtomContext,
accountId: string,