@devries-cameron20 / t3code-1 / commits / a2edd281df
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(connect): require approval for new T3 Connect devices (#36419)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 13, 2026 at 17:05 UTC a2edd281df232ddb635d006a7569b3e8e628b875
68 files changed +2932 -145
apps/mobile/src/App.tsx
+2
@@ -75,6 +75,7 @@ import {
75 import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
76 import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
77 import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
78 +import { ConnectDeviceApprovalCoordinator } from "./features/connection/ConnectDeviceApprovalCoordinator";
79 import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage";
80 import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
81 import {
@@ -281,6 +282,7 @@ function AppContent() {
282 <>
283 <SplashScreenCoordinator />
284 <SubscriptionUsageCoordinator />
285 + <ConnectDeviceApprovalCoordinator />
286 <GestureHandlerRootView className="flex-1">
287 <KeyboardProvider statusBarTranslucent>
288 <SafeAreaProvider>
apps/mobile/src/components/ui/Dialog.android.test.tsx
+9
@@ -90,6 +90,15 @@ it("keeps a dialog raised while the activity is replaced", () => {
90 expect(current.container.textContent).toContain("Shared content imported");
91 });
92
93 +it("tells a replaced alert it was dismissed", () => {
94 + mountHost();
95 + const onDismiss = vi.fn();
96 + act(() => Dialog.alert("Older", undefined, [{ text: "OK" }], { onDismiss }));
97 + act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }]));
98 +
99 + expect(onDismiss).toHaveBeenCalledOnce();
100 +});
101 +
102 it("ignores a late action from a dialog that a newer one replaced", () => {
103 const { container } = mountHost();
104 const olderAction = vi.fn();
apps/mobile/src/components/ui/Dialog.android.tsx
+3
@@ -49,7 +49,10 @@ function setPresented(next: PresentedDialog | null) {
49 }
50
51 function submitRequest(dialog: DialogRequest) {
52 + const replaced = presented;
53 setPresented({ ...dialog, id: ++nextPresentationId });
54 + // A replaced alert closed without an answer, which its owner hears as a dismissal.
55 + if (replaced?.kind === "alert") replaced.request.options?.onDismiss?.();
56 }
57
58 /** Closes the dialog only if it is still the one the action came from. */
apps/mobile/src/features/connection/CloudEnvironmentRows.tsx
+5 -1
@@ -203,6 +203,7 @@ function ConnectedCloudEnvironmentRow(props: {
203 connectionError={enabled || unsupported ? props.environment.connectionError : null}
204 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
205 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
206 + awaitingApproval={enabled && presentation?.connection.awaitingApproval === true}
207 errorExpanded={props.errorExpanded}
208 label={props.environment.environmentLabel}
209 machine={resolveEnvironmentMachineKind(
@@ -269,6 +270,8 @@ function CloudEnvironmentRowShell(props: {
270 readonly connectionError: string | null;
271 readonly connectionErrorTraceId: string | null;
272 readonly connectionState: EnvironmentConnectionPhase;
273 + /** Waiting on the host to approve this device: say so plainly, not as a failure. */
274 + readonly awaitingApproval?: boolean;
275 readonly disabled?: boolean;
276 readonly errorExpanded: boolean;
277 readonly label: string;
@@ -287,9 +290,10 @@ function CloudEnvironmentRowShell(props: {
290 phase: props.connectionState,
291 error: props.connectionError,
292 traceId: props.connectionErrorTraceId,
293 + ...(props.awaitingApproval ? { awaitingApproval: true as const } : {}),
294 });
295 const statusClassName =
292 - props.connectionError && props.connectionState !== "unsupported"
296 + props.connectionError && props.connectionState !== "unsupported" && !props.awaitingApproval
297 ? "text-danger-foreground"
298 : "text-foreground-muted";
299 const [errorMeasurement, setErrorMeasurement] = useState<{
apps/mobile/src/features/connection/ConnectDeviceApprovalCoordinator.tsx new
+141
@@ -0,0 +1,141 @@
1 +import { AuthAccessWriteScope, type AuthPairingLink, type EnvironmentId } from "@t3tools/contracts";
2 +import { useEffect, useEffectEvent } from "react";
3 +
4 +import * as Dialog from "../../components/ui/Dialog";
5 +import { authEnvironment } from "../../state/auth";
6 +import { useEnvironments } from "../../state/environments";
7 +import { useEnvironmentQuery } from "../../state/query";
8 +import { useEnvironmentsWithScope } from "../../state/session";
9 +import { useAtomCommand } from "../../state/use-atom-command";
10 +import {
11 + type ConnectDeviceApprovalPrompt,
12 + connectDeviceApprovalPrompts,
13 + createApprovalPromptQueue,
14 +} from "./connectDeviceApproval";
15 +
16 +/** Asks to approve T3 Connect devices waiting on hosts that require it and this phone manages. */
17 +export function ConnectDeviceApprovalCoordinator() {
18 + const { environments } = useEnvironments();
19 + const requiring = environments.filter(
20 + (environment) =>
21 + environment.connection.phase === "connected" &&
22 + environment.serverConfig?.settings.requireConnectDeviceApproval === true,
23 + );
24 + const managed = useEnvironmentsWithScope(requiring, AuthAccessWriteScope);
25 + return (
26 + <>
27 + {requiring
28 + .filter((environment) => managed.has(environment.environmentId))
29 + .map((environment) => (
30 + <EnvironmentApprovalWatcher
31 + key={environment.environmentId}
32 + environmentId={environment.environmentId}
33 + environmentLabel={environment.label}
34 + />
35 + ))}
36 + </>
37 + );
38 +}
39 +
40 +/** "gone": the request expired or was answered elsewhere before this answer arrived. */
41 +type ApprovalAnswer = "done" | "failed" | "gone";
42 +
43 +interface QueuedApprovalPrompt extends ConnectDeviceApprovalPrompt {
44 + readonly environmentId: EnvironmentId;
45 + readonly approve: () => Promise<ApprovalAnswer>;
46 + readonly deny: () => Promise<ApprovalAnswer>;
47 +}
48 +
49 +const watchedEnvironments = new Set<EnvironmentId>();
50 +
51 +// One queue for every host: a second Android alert would replace an unanswered first one.
52 +const approvalPrompts = createApprovalPromptQueue<QueuedApprovalPrompt>((prompt, answer) => {
53 + const respond = (action: () => Promise<ApprovalAnswer>, failure: string) => () =>
54 + void action().then((outcome) => {
55 + // A host that went away or lost access cannot be retried; let the next prompt show.
56 + if (outcome === "done" || !watchedEnvironments.has(prompt.environmentId)) {
57 + return answer("done");
58 + }
59 + if (outcome === "gone") {
60 + return Dialog.alert(
61 + "Request no longer waiting",
62 + "It expired or was answered elsewhere.",
63 + [{ text: "OK", onPress: () => answer("done") }],
64 + { onDismiss: () => answer("done") },
65 + );
66 + }
67 + const retryIfWatched = () =>
68 + answer(watchedEnvironments.has(prompt.environmentId) ? "retry" : "done");
69 + Dialog.alert(
70 + failure,
71 + "The request is still waiting. Try again.",
72 + [{ text: "OK", onPress: retryIfWatched }],
73 + // Another dialog took the screen; offer the request again on the next update.
74 + { onDismiss: () => answer("later") },
75 + );
76 + });
77 + Dialog.alert(
78 + prompt.title,
79 + prompt.message,
80 + [
81 + { text: "Deny", onPress: respond(prompt.deny, "Could not deny the device") },
82 + { text: "Approve", onPress: respond(prompt.approve, "Could not approve the device") },
83 + ],
84 + // Another dialog took the screen; offer the request again on the next update.
85 + { cancelable: false, onDismiss: () => answer("later") },
86 + );
87 +});
88 +
89 +function EnvironmentApprovalWatcher(props: {
90 + readonly environmentId: EnvironmentId;
91 + readonly environmentLabel: string;
92 +}) {
93 + const access = useEnvironmentQuery(
94 + authEnvironment.accessChanges({ environmentId: props.environmentId, input: null }),
95 + );
96 + const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });
97 + const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });
98 + const pairingLinks =
99 + access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;
100 +
101 + const offerPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {
102 + const prompts = connectDeviceApprovalPrompts({
103 + environmentLabel: props.environmentLabel,
104 + pairingLinks: links,
105 + shownIds: approvalPrompts.known,
106 + });
107 + approvalPrompts.offer(
108 + prompts.map((prompt) => ({
109 + ...prompt,
110 + environmentId: props.environmentId,
111 + approve: () =>
112 + approve({
113 + environmentId: props.environmentId,
114 + input: { pairingLinkId: prompt.pairingLinkId },
115 + }).then((result) =>
116 + result._tag !== "Success" ? "failed" : result.value.approved ? "done" : "gone",
117 + ),
118 + deny: () =>
119 + deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }).then(
120 + (result) =>
121 + result._tag !== "Success" ? "failed" : result.value.revoked ? "done" : "gone",
122 + ),
123 + })),
124 + );
125 + });
126 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this host with the module-level prompt queue and drops its prompts when it goes away
127 + useEffect(() => {
128 + const environmentId = props.environmentId;
129 + watchedEnvironments.add(environmentId);
130 + return () => {
131 + watchedEnvironments.delete(environmentId);
132 + approvalPrompts.drop((prompt) => prompt.environmentId === environmentId);
133 + };
134 + }, [props.environmentId]);
135 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new request on the access stream opens a native alert
136 + useEffect(() => {
137 + if (pairingLinks !== undefined) offerPrompts(pairingLinks);
138 + }, [pairingLinks]);
139 +
140 + return null;
141 +}
apps/mobile/src/features/connection/EnvironmentConnectionNotice.tsx
+19 -3
@@ -10,7 +10,12 @@ import { View } from "react-native";
10
11 import { AppText as Text } from "../../components/ui/AppText";
12
13 -function noticeTitle(phase: EnvironmentConnectionPhase, environmentLabel: string): string {
13 +function noticeTitle(
14 + phase: EnvironmentConnectionPhase,
15 + environmentLabel: string,
16 + awaitingApproval: boolean,
17 +): string {
18 + if (awaitingApproval) return `Waiting for ${environmentLabel} to approve this device`;
19 switch (phase) {
20 case "offline":
21 return "You are offline";
@@ -33,7 +38,9 @@ function noticeDetail(
38 phase: EnvironmentConnectionPhase,
39 resourceName: string,
40 error: string | null,
41 + awaitingApproval: boolean,
42 ): string {
43 + if (error && awaitingApproval) return error;
44 if (error) {
45 return phase === "reconnecting" ? `The app will keep retrying automatically. ${error}` : error;
46 }
@@ -78,10 +85,19 @@ export function EnvironmentConnectionNotice(props: {
85 )}
86
87 <Text className="text-center text-lg font-t3-bold text-foreground">
81 - {noticeTitle(props.connection.phase, props.environmentLabel)}
88 + {noticeTitle(
89 + props.connection.phase,
90 + props.environmentLabel,
91 + props.connection.awaitingApproval === true,
92 + )}
93 </Text>
94 <Text className="text-center text-sm leading-normal text-foreground-muted">
84 - {noticeDetail(props.connection.phase, props.resourceName, props.connection.error)}
95 + {noticeDetail(
96 + props.connection.phase,
97 + props.resourceName,
98 + props.connection.error,
99 + props.connection.awaitingApproval === true,
100 + )}
101 {props.connection.traceId ? (
102 <ConnectionTraceId traceId={props.connection.traceId} />
103 ) : null}
apps/mobile/src/features/connection/connectDeviceApproval.test.ts new
+113
@@ -0,0 +1,113 @@
1 +import type { AuthPairingLink } from "@t3tools/contracts";
2 +import * as DateTime from "effect/DateTime";
3 +import { describe, expect, it } from "vite-plus/test";
4 +
5 +import { connectDeviceApprovalPrompts, createApprovalPromptQueue } from "./connectDeviceApproval";
6 +
7 +const link = (id: string, createdAtMs: number, request?: AuthPairingLink["connectDeviceRequest"]) =>
8 + ({
9 + id,
10 + scopes: [],
11 + subject: "cloud-connect",
12 + createdAt: DateTime.makeUnsafe(createdAtMs),
13 + expiresAt: DateTime.makeUnsafe(createdAtMs + 600_000),
14 + ...(request ? { connectDeviceRequest: request } : {}),
15 + }) as unknown as AuthPairingLink;
16 +
17 +describe("connectDeviceApprovalPrompts", () => {
18 + it("prompts once per waiting device, oldest first, and skips ordinary pairing links", () => {
19 + const pairingLinks = [
20 + link("newer", 2_000, { verificationCode: "WXYZ-2345" }),
21 + link("plain", 500),
22 + link("older", 1_000, {
23 + verificationCode: "ABCD-EFGH",
24 + client: { deviceType: "desktop", browser: "Chrome", os: "macOS" },
25 + }),
26 + ];
27 +
28 + const prompts = connectDeviceApprovalPrompts({
29 + environmentLabel: "Mac mini",
30 + pairingLinks,
31 + shownIds: new Set(["newer"]),
32 + });
33 +
34 + expect(prompts.map((prompt) => prompt.pairingLinkId)).toEqual(["older"]);
35 + expect(prompts[0]?.message).toContain("Chrome on macOS wants to connect to Mac mini");
36 + expect(prompts[0]?.message).toContain("ABCD-EFGH");
37 + });
38 +});
39 +
40 +describe("createApprovalPromptQueue", () => {
41 + it("shows one prompt at a time and offers a failed one again before the rest", () => {
42 + const shown: string[] = [];
43 + const answers: Array<(outcome: "done" | "retry" | "later") => void> = [];
44 + const queue = createApprovalPromptQueue<{ pairingLinkId: string }>((prompt, answer) => {
45 + shown.push(prompt.pairingLinkId);
46 + answers.push(answer);
47 + });
48 +
49 + queue.offer([{ pairingLinkId: "a" }, { pairingLinkId: "b" }]);
50 + queue.offer([{ pairingLinkId: "a" }]);
51 + expect(shown).toEqual(["a"]);
52 +
53 + answers.at(-1)!("retry");
54 + expect(shown).toEqual(["a", "a"]);
55 + answers.at(-1)!("done");
56 + expect(shown).toEqual(["a", "a", "b"]);
57 + });
58 +
59 + it("waits for the next offer when another dialog replaced the prompt", () => {
60 + const shown: string[] = [];
61 + const answers: Array<(outcome: "done" | "retry" | "later") => void> = [];
62 + const queue = createApprovalPromptQueue<{ pairingLinkId: string }>((prompt, answer) => {
63 + shown.push(prompt.pairingLinkId);
64 + answers.push(answer);
65 + });
66 +
67 + queue.offer([{ pairingLinkId: "a" }]);
68 + answers.at(-1)!("later");
69 + expect(shown).toEqual(["a"]);
70 + queue.offer([]);
71 + expect(shown).toEqual(["a", "a"]);
72 + });
73 +
74 + it("offers a dropped host's on-screen prompt again once the host is back", () => {
75 + const shown: string[] = [];
76 + const answers: Array<(outcome: "done" | "retry" | "later") => void> = [];
77 + const queue = createApprovalPromptQueue<{ pairingLinkId: string; host: string }>(
78 + (prompt, answer) => {
79 + shown.push(prompt.pairingLinkId);
80 + answers.push(answer);
81 + },
82 + );
83 +
84 + queue.offer([{ pairingLinkId: "a", host: "mini" }]);
85 + queue.drop((prompt) => prompt.host === "mini");
86 + answers.at(-1)!("retry");
87 + expect(shown).toEqual(["a"]);
88 + queue.offer([{ pairingLinkId: "a", host: "mini" }]);
89 + expect(shown).toEqual(["a", "a"]);
90 + });
91 +
92 + it("drops a host's waiting prompts so they cannot hold up other hosts", () => {
93 + const shown: string[] = [];
94 + const answers: Array<(outcome: "done" | "retry" | "later") => void> = [];
95 + const queue = createApprovalPromptQueue<{ pairingLinkId: string; host: string }>(
96 + (prompt, answer) => {
97 + shown.push(prompt.pairingLinkId);
98 + answers.push(answer);
99 + },
100 + );
101 +
102 + queue.offer([
103 + { pairingLinkId: "a", host: "mini" },
104 + { pairingLinkId: "b", host: "mini" },
105 + { pairingLinkId: "c", host: "laptop" },
106 + ]);
107 + queue.drop((prompt) => prompt.host === "mini");
108 + answers.at(-1)!("done");
109 + expect(shown).toEqual(["a", "c"]);
110 + // A dropped host's request can be offered again once the host is back.
111 + expect(queue.known.has("b")).toBe(false);
112 + });
113 +});
apps/mobile/src/features/connection/connectDeviceApproval.ts new
+91
@@ -0,0 +1,91 @@
1 +import type { AuthClientMetadata, AuthPairingLink } from "@t3tools/contracts";
2 +
3 +export interface ConnectDeviceApprovalPrompt {
4 + readonly pairingLinkId: string;
5 + readonly title: string;
6 + readonly message: string;
7 +}
8 +
9 +export function describeConnectDevice(device: AuthClientMetadata | undefined): string {
10 + const { label, browser, os } = device ?? {};
11 + if (label) return label;
12 + if (browser && os) return `${browser} on ${os}`;
13 + return browser ?? os ?? "A new device";
14 +}
15 +
16 +/** Requests waiting on approval that have not been shown yet, oldest first. */
17 +export function connectDeviceApprovalPrompts(input: {
18 + readonly environmentLabel: string;
19 + readonly pairingLinks: ReadonlyArray<AuthPairingLink>;
20 + readonly shownIds: ReadonlySet<string>;
21 +}): ReadonlyArray<ConnectDeviceApprovalPrompt> {
22 + const waiting = input.pairingLinks.flatMap((link) =>
23 + link.connectDeviceRequest !== undefined && !input.shownIds.has(link.id)
24 + ? [{ link, ...link.connectDeviceRequest }]
25 + : [],
26 + );
27 + return [...waiting]
28 + .sort(
29 + (left, right) =>
30 + left.link.createdAt.epochMilliseconds - right.link.createdAt.epochMilliseconds,
31 + )
32 + .map(({ link, verificationCode, client: device }) => ({
33 + pairingLinkId: link.id,
34 + title: "Approve this device?",
35 + message: `${describeConnectDevice(device)} wants to connect to ${input.environmentLabel} through T3 Connect. It shows code ${verificationCode}. Approve it only if that code matches.`,
36 + }));
37 +}
38 +
39 +/**
40 + * Shows approval prompts one at a time: an Android alert replaces the one on screen, which
41 + * would drop an unanswered request. A prompt answered with "retry" goes back to the front;
42 + * "later" puts it back without showing anything until the next offer.
43 + */
44 +export function createApprovalPromptQueue<P extends { readonly pairingLinkId: string }>(
45 + present: (prompt: P, answer: (outcome: "done" | "retry" | "later") => void) => void,
46 +) {
47 + const known = new Set<string>();
48 + const waiting: P[] = [];
49 + let showing: { readonly prompt: P; dropped: boolean } | null = null;
50 + const next = () => {
51 + if (showing) return;
52 + const prompt = waiting.shift();
53 + if (prompt === undefined) return;
54 + const current = { prompt, dropped: false };
55 + showing = current;
56 + let answered = false;
57 + present(prompt, (outcome) => {
58 + if (answered) return;
59 + answered = true;
60 + showing = null;
61 + // A dropped prompt is forgotten, so its host can offer it again when it comes back.
62 + if (outcome !== "done" && !current.dropped) waiting.unshift(prompt);
63 + if (outcome !== "later") next();
64 + });
65 + };
66 + return {
67 + known: known as ReadonlySet<string>,
68 + /** Forgets waiting prompts that match, such as a host that went away. */
69 + drop(matches: (prompt: P) => boolean) {
70 + if (showing && matches(showing.prompt)) {
71 + showing.dropped = true;
72 + known.delete(showing.prompt.pairingLinkId);
73 + }
74 + for (let index = waiting.length - 1; index >= 0; index--) {
75 + const prompt = waiting[index]!;
76 + if (!matches(prompt)) continue;
77 + waiting.splice(index, 1);
78 + known.delete(prompt.pairingLinkId);
79 + }
80 + },
81 + offer(prompts: ReadonlyArray<P>) {
82 + // Also re-shows a prompt deferred because another dialog took the screen.
83 + for (const prompt of prompts) {
84 + if (known.has(prompt.pairingLinkId)) continue;
85 + known.add(prompt.pairingLinkId);
86 + waiting.push(prompt);
87 + }
88 + next();
89 + },
90 + };
91 +}
apps/mobile/src/features/connection/connectionTone.ts
+11 -1
@@ -1,7 +1,17 @@
1 import type { StatusTone } from "../../components/StatusPill";
2 import type { RemoteClientConnectionState } from "../../lib/connection";
3
4 -export function connectionTone(state: RemoteClientConnectionState): StatusTone {
4 +export function connectionTone(
5 + state: RemoteClientConnectionState,
6 + awaitingApproval?: boolean,
7 +): StatusTone {
8 + if (state === "reconnecting" && awaitingApproval) {
9 + return {
10 + label: "Waiting for approval",
11 + pillClassName: "bg-update",
12 + textClassName: "text-update-foreground",
13 + };
14 + }
15 switch (state) {
16 case "connected":
17 return {
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+4 -1
@@ -980,7 +980,10 @@ export function NewTaskDraftScreen(props: {
980 selectedThread={thread}
981 selectedThreadDetailRef={null}
982 contentPresentation={{ kind: "ready" }}
983 - screenTone={connectionTone(connectionState)}
983 + screenTone={connectionTone(
984 + connectionState,
985 + environmentRuntime?.connectionAwaitingApproval === true,
986 + )}
987 connectionError={environmentRuntime?.connectionError ?? null}
988 environmentLabel={selectedEnvironmentLabel}
989 feedbackSubmissions={[]}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+2
@@ -268,6 +268,7 @@ export interface ThreadDetailScreenProps {
268 readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
269 readonly respondingUserInputId: RuntimeRequestId | null;
270 readonly connectionStateLabel: EnvironmentConnectionPhase;
271 + readonly connectionAwaitingApproval?: boolean;
272 readonly threadSyncStatus?: EnvironmentThreadStatus;
273 readonly historyControls?: ThreadFeedHistoryControls;
274 readonly activeThreadBusy: boolean;
@@ -765,6 +766,7 @@ function ThreadDetailBody(
766 const connectionStatus = connectionFloatingStatus({
767 connectionError: connectionRetrying ? retryConnectionError : props.connectionError,
768 connectionState: props.connectionStateLabel,
769 + connectionAwaitingApproval: props.connectionAwaitingApproval === true,
770 environmentLabel: props.environmentLabel,
771 onReconnect: props.onReconnectEnvironment,
772 });
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+5 -1
@@ -990,7 +990,10 @@ function ThreadRouteContent(
990 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
991 selectedThreadDetailRef={selectedThreadDetailRef}
992 contentPresentation={contentPresentation}
993 - screenTone={connectionTone(routeConnectionState)}
993 + screenTone={connectionTone(
994 + routeConnectionState,
995 + routeEnvironmentRuntime?.connectionAwaitingApproval === true,
996 + )}
997 connectionError={routeConnectionError}
998 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
999 feedbackSubmissions={composer.feedbackSubmissions}
@@ -1039,6 +1042,7 @@ function ThreadRouteContent(
1042 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1043 respondingUserInputId={requests.respondingUserInputId}
1044 connectionStateLabel={routeConnectionState}
1045 + connectionAwaitingApproval={routeEnvironmentRuntime?.connectionAwaitingApproval === true}
1046 threadSyncStatus={selectedThreadDetailState.status}
1047 historyControls={historyControls}
1048 activeThreadBusy={composer.activeThreadBusy}
apps/mobile/src/features/threads/floating-working-status.ts
+9
@@ -51,6 +51,7 @@ export type FloatingWorkingStatus =
51 export function connectionFloatingStatus(input: {
52 readonly connectionError: string | null;
53 readonly connectionState: EnvironmentConnectionPhase;
54 + readonly connectionAwaitingApproval?: boolean;
55 readonly environmentLabel: string | null;
56 readonly onReconnect: () => void;
57 }): FloatingWorkingStatus | null {
@@ -62,6 +63,14 @@ export function connectionFloatingStatus(input: {
63 onPress: input.onReconnect,
64 });
65
66 + if (input.connectionState === "reconnecting" && input.connectionAwaitingApproval) {
67 + return {
68 + kind: "connection",
69 + tone: "reconnecting",
70 + label: `Waiting for ${environmentLabel} to approve this device`,
71 + onPress: input.onReconnect,
72 + };
73 + }
74 switch (input.connectionState) {
75 case "connecting":
76 case "reconnecting":
apps/mobile/src/state/auth.ts new
+5
@@ -0,0 +1,5 @@
1 +import { createAuthEnvironmentAtoms } from "@t3tools/client-runtime/state/auth";
2 +
3 +import { connectionAtomRuntime } from "../connection/runtime";
4 +
5 +export const authEnvironment = createAuthEnvironmentAtoms(connectionAtomRuntime);
apps/mobile/src/state/remote-environment-projections.ts
+2
@@ -102,6 +102,7 @@ export function createRemoteEnvironmentProjectionAtoms(input: {
102 connection.phase === previousConnection?.phase &&
103 connection.error === previousConnection?.error &&
104 connection.traceId === previousConnection?.traceId &&
105 + connection.awaitingApproval === previousConnection?.awaitingApproval &&
106 serverConfig === previousServerConfig
107 ) {
108 return previous;
@@ -113,6 +114,7 @@ export function createRemoteEnvironmentProjectionAtoms(input: {
114 connectionState: connection.phase,
115 connectionError: connection.error,
116 connectionErrorTraceId: connection.traceId,
117 + ...(connection.awaitingApproval ? { connectionAwaitingApproval: true as const } : {}),
118 serverConfig,
119 };
120 return previous;
apps/mobile/src/state/remote-runtime-types.ts
+2
@@ -5,6 +5,8 @@ export interface EnvironmentRuntimeState {
5 readonly connectionState: EnvironmentConnectionPhase;
6 readonly connectionError: string | null;
7 readonly connectionErrorTraceId: string | null;
8 + /** Reconnecting only because the host has not approved this device yet. */
9 + readonly connectionAwaitingApproval?: true;
10 readonly serverConfig: ServerConfig | null;
11 }
12
apps/server/src/auth/EnvironmentAuth.test.ts
+116 -1
@@ -1,6 +1,10 @@
1 import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { authScopeResponse, AuthStandardClientScopes } from "@t3tools/contracts";
3 +import {
4 + authScopeResponse,
5 + AuthStandardClientScopes,
6 + connectDeviceVerificationCode,
7 +} from "@t3tools/contracts";
8 import { expect, it } from "@effect/vitest";
9 import * as DateTime from "effect/DateTime";
10 import * as Effect from "effect/Effect";
@@ -300,6 +304,117 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
304 }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
305 );
306
307 + it.effect(
308 + "holds an untrusted T3 Connect device until it is approved, and revocation cuts it off",
309 + () =>
310 + Effect.gen(function* () {
311 + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
312 + const deviceKey = "Kq3vZ8sYbTn0eW1pLr5uXc7dHf9gJm2aQs4tVw6yBzE";
313 + const admin = yield* serverAuth.issueSession({ label: "Owner" });
314 + const exchange = (credential: string) =>
315 + serverAuth.exchangeBootstrapCredentialForAccessToken(
316 + credential,
317 + undefined,
318 + requestMetadata,
319 + { proofKeyThumbprint: deviceKey },
320 + );
321 +
322 + // Relay mints can arrive together; they must share one request and one code.
323 + const mint = serverAuth.issueConnectCredential({
324 + proofKeyThumbprint: deviceKey,
325 + requireApproval: true,
326 + });
327 + const [requested, concurrent] = yield* Effect.all([mint, mint], {
328 + concurrency: "unbounded",
329 + });
330 + expect(concurrent.credential).toBe(requested.credential);
331 + expect((yield* exchange(requested.credential).pipe(Effect.flip))._tag).toBe(
332 + "ServerAuthConnectApprovalPendingError",
333 + );
334 + const [request] = (yield* serverAuth.listPairingLinks()).filter(
335 + (link) => link.connectDeviceRequest !== undefined,
336 + );
337 + expect(request?.connectDeviceRequest).toEqual({
338 + verificationCode: connectDeviceVerificationCode(deviceKey),
339 + client: requestMetadata,
340 + });
341 + // A retry through the relay keeps the one request the approver is looking at.
342 + const retried = yield* serverAuth.issueConnectCredential({
343 + proofKeyThumbprint: deviceKey,
344 + requireApproval: true,
345 + });
346 + expect(retried.credential).toBe(requested.credential);
347 +
348 + expect(yield* serverAuth.approveConnectDevice(request!.id)).toBe(true);
349 + expect(
350 + (yield* serverAuth.listPairingLinks()).some((link) => link.connectDeviceRequest),
351 + ).toBe(false);
352 + yield* exchange(requested.credential);
353 + expect(
354 + (yield* serverAuth.listConnectDevices()).map((device) => device.proofKeyThumbprint),
355 + ).toEqual([deviceKey]);
356 +
357 + const refreshed = yield* serverAuth.issueConnectCredential({
358 + proofKeyThumbprint: deviceKey,
359 + requireApproval: true,
360 + });
361 + yield* exchange(refreshed.credential);
362 +
363 + const deviceSessions = () =>
364 + serverAuth
365 + .listClientSessions(admin.sessionId)
366 + .pipe(
367 + Effect.map((sessions) =>
368 + sessions.filter(
369 + (session) => session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT,
370 + ),
371 + ),
372 + );
373 + // A credential minted before revocation must not let the device back in afterwards.
374 + const unspent = yield* serverAuth.issueConnectCredential({
375 + proofKeyThumbprint: deviceKey,
376 + requireApproval: true,
377 + });
378 + const [oldestDeviceSession, newestDeviceSession] = yield* deviceSessions();
379 + expect(newestDeviceSession).toBeDefined();
380 + // Authorized clients lists T3 Connect sessions under this name.
381 + expect(newestDeviceSession?.client.label).toBe("T3 Connect");
382 + // Revoking any one of the device's sessions ends all of them and its trust.
383 + expect(
384 + yield* serverAuth.revokeClientSession(admin.sessionId, oldestDeviceSession!.sessionId),
385 + ).toBe(true);
386 + expect(yield* deviceSessions()).toEqual([]);
387 + expect(yield* serverAuth.listConnectDevices()).toEqual([]);
388 + expect((yield* exchange(unspent.credential).pipe(Effect.flip))._tag).toBe(
389 + "ServerAuthInvalidCredentialError",
390 + );
391 + expect(yield* serverAuth.listConnectDevices()).toEqual([]);
392 + const afterRevoke = yield* serverAuth.issueConnectCredential({
393 + proofKeyThumbprint: deviceKey,
394 + requireApproval: true,
395 + });
396 + expect((yield* exchange(afterRevoke.credential).pipe(Effect.flip))._tag).toBe(
397 + "ServerAuthConnectApprovalPendingError",
398 + );
399 + // Deny sticks: retries get the dead request back instead of a fresh prompt.
400 + const [denied] = (yield* serverAuth.listPairingLinks()).filter(
401 + (link) => link.connectDeviceRequest !== undefined,
402 + );
403 + expect(yield* serverAuth.revokePairingLink(denied!.id)).toBe(true);
404 + const afterDeny = yield* serverAuth.issueConnectCredential({
405 + proofKeyThumbprint: deviceKey,
406 + requireApproval: true,
407 + });
408 + expect(afterDeny.credential).toBe(afterRevoke.credential);
409 + expect((yield* exchange(afterDeny.credential).pipe(Effect.flip))._tag).toBe(
410 + "ServerAuthInvalidCredentialError",
411 + );
412 + expect(
413 + (yield* serverAuth.listPairingLinks()).some((link) => link.connectDeviceRequest),
414 + ).toBe(false);
415 + }).pipe(Effect.provide(layerEnvironmentAuth())),
416 + );
417 +
418 it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
419 Effect.gen(function* () {
420 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuth.ts
+235 -17
@@ -8,6 +8,7 @@ import {
8 type AuthBrowserSessionResult,
9 type AuthClientMetadata,
10 type AuthClientSession,
11 + type AuthConnectDevice,
12 type AuthCreatePairingCredentialInput,
13 type AuthEnvironmentScope,
14 type AuthPairingLink,
@@ -34,6 +35,7 @@ import * as Layer from "effect/Layer";
35 import * as Option from "effect/Option";
36 import * as Redacted from "effect/Redacted";
37 import * as Schema from "effect/Schema";
38 +import * as Semaphore from "effect/Semaphore";
39 import * as HttpServerRequest from "effect/http/HttpServerRequest";
40
41 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
@@ -53,6 +55,8 @@ import { requestUrl } from "../requestUrl.ts";
55
56 const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
57 export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
58 +/** Sessions and pairing links T3 Connect minted for a device signed in to the linked account. */
59 +export const CLOUD_CONNECT_SUBJECT = "cloud-connect";
60
61 export interface IssuedPairingLink {
62 readonly id: string;
@@ -335,6 +339,17 @@ export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedError<Serve
339 }
340 }
341
342 +export class ServerAuthConnectDevicesError extends Schema.TaggedError<ServerAuthConnectDevicesError>()(
343 + "ServerAuthConnectDevicesError",
344 + {
345 + ...serverAuthInternalErrorContext,
346 + },
347 +) {
348 + override get message(): string {
349 + return "Failed to update T3 Connect devices.";
350 + }
351 +}
352 +
353 export const ServerAuthInternalError = Schema.Union([
354 ServerAuthBootstrapCredentialValidationError,
355 ServerAuthSessionCredentialValidationError,
@@ -358,6 +373,7 @@ export const ServerAuthInternalError = Schema.Union([
373 ServerAuthCloudRelayIssuerMissingError,
374 ServerAuthCloudHealthJwtSigningError,
375 ServerAuthCloudMintJwtSigningError,
376 + ServerAuthConnectDevicesError,
377 ]);
378 export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
379 export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
@@ -429,6 +445,16 @@ export const serverAuthInvalidRequestReason = (
445 ): "invalid_scope" | "scope_not_granted" =>
446 error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
447
448 +/** The credential is fine, but the host has not approved this T3 Connect device yet. */
449 +export class ServerAuthConnectApprovalPendingError extends Schema.TaggedError<ServerAuthConnectApprovalPendingError>()(
450 + "ServerAuthConnectApprovalPendingError",
451 + {},
452 +) {
453 + override get message(): string {
454 + return "This T3 Connect device is waiting for approval.";
455 + }
456 +}
457 +
458 export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError<ServerAuthMcpApprovalCodeError>()(
459 "ServerAuthMcpApprovalCodeError",
460 { reason: Schema.Literals(["unknown_or_used", "not_a_pairing_code", "insufficient_scope"]) },
@@ -480,7 +506,10 @@ export class EnvironmentAuth extends Context.Service<
506 },
507 ) => Effect.Effect<
508 AuthAccessTokenResult,
483 - ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
509 + | ServerAuthInvalidCredentialError
510 + | ServerAuthInvalidRequestError
511 + | ServerAuthConnectApprovalPendingError
512 + | ServerAuthInternalError
513 >;
514 readonly createPairingLink: (input?: {
515 readonly ttl?: Duration.Duration;
@@ -490,10 +519,41 @@ export class EnvironmentAuth extends Context.Service<
519 readonly proofKeyThumbprint?: string;
520 readonly purpose?: "startup";
521 readonly mcpApproval?: AuthMcpClientAccess;
522 + readonly requiresConnectApproval?: boolean;
523 }) => Effect.Effect<
524 IssuedPairingLink,
525 ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
526 >;
527 + /**
528 + * The one-time credential T3 Connect hands a device. With approval required, an untrusted
529 + * device key gets one that waits for approval, and keeps it across retries.
530 + */
531 + readonly issueConnectCredential: (input: {
532 + readonly proofKeyThumbprint: string;
533 + readonly requireApproval: boolean;
534 + }) => Effect.Effect<
535 + { readonly credential: string; readonly expiresAt: DateTime.Utc },
536 + ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
537 + >;
538 + readonly approveConnectDevice: (
539 + pairingLinkId: string,
540 + ) => Effect.Effect<boolean, ServerAuthInternalError>;
541 + /** Approves the waiting device that shows this code, for hosts without a client at hand. */
542 + readonly approveConnectDeviceByCode: (
543 + verificationCode: string,
544 + ) => Effect.Effect<boolean, ServerAuthInternalError>;
545 + /** Revokes the one trusted device that shows this code; two that share it are ambiguous. */
546 + readonly revokeConnectDeviceByCode: (
547 + verificationCode: string,
548 + ) => Effect.Effect<"revoked" | "not-found" | "ambiguous", ServerAuthInternalError>;
549 + readonly listConnectDevices: () => Effect.Effect<
550 + ReadonlyArray<AuthConnectDevice>,
551 + ServerAuthInternalError
552 + >;
553 + /** Stops trusting a device key and ends the sessions it holds. */
554 + readonly revokeConnectDevice: (
555 + proofKeyThumbprint: string,
556 + ) => Effect.Effect<boolean, ServerAuthInternalError>;
557 readonly issuePairingCredential: (
558 input?: AuthCreatePairingCredentialInput,
559 ) => Effect.Effect<
@@ -925,21 +985,33 @@ export const make = Effect.gen(function* () {
985 readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
986 /** Only an agent sign-in opts in to spending a code issued for it. */
987 readonly mcpApproval?: AuthMcpClientAccess;
988 + /** Shown to approvers when the credential waits on T3 Connect device approval. */
989 + readonly requestMetadata?: AuthClientMetadata;
990 },
991 ): Effect.Effect<
992 ResolvedBootstrapGrant,
931 - ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
993 + | ServerAuthInvalidCredentialError
994 + | ServerAuthInternalError
995 + | ServerAuthScopeNotGrantedError
996 + | ServerAuthConnectApprovalPendingError
997 > => {
998 if (!devAuth?.matches(credential)) {
934 - return bootstrapCredentials
935 - .consume(credential, input)
936 - .pipe(
937 - Effect.mapError((cause) =>
938 - cause._tag === "BootstrapCredentialScopeNotGrantedError"
939 - ? new ServerAuthScopeNotGrantedError({})
999 + return bootstrapCredentials.consume(credential, input).pipe(
1000 + Effect.catchTags({
1001 + BootstrapCredentialConnectApprovalPendingError: (pending) =>
1002 + recordConnectRequest(pending.pairingLinkId, input?.requestMetadata).pipe(
1003 + Effect.andThen(Effect.fail(new ServerAuthConnectApprovalPendingError({}))),
1004 + ),
1005 + }),
1006 + Effect.mapError((cause) =>
1007 + cause._tag === "BootstrapCredentialScopeNotGrantedError"
1008 + ? new ServerAuthScopeNotGrantedError({})
1009 + : cause._tag === "ServerAuthConnectApprovalPendingError" ||
1010 + cause._tag === "ServerAuthConnectDevicesError"
1011 + ? cause
1012 : toBootstrapExchangeError(cause),
941 - ),
942 - );
1013 + ),
1014 + );
1015 }
1016 return sessions.verify(credential).pipe(
1017 mapSessionVerificationErrors,
@@ -960,12 +1032,27 @@ export const make = Effect.gen(function* () {
1032 );
1033 };
1034
1035 + // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints
1036 + // at once would open two requests with one code, and a revoke landing between an exchange
1037 + // spending its credential and trusting the key would be undone by that exchange.
1038 + const connectTrustLock = yield* Semaphore.make(1);
1039 +
1040 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
1041 (credential, requestedScopes, requestMetadata, input) => {
1042 return resolveBootstrapGrant(credential, {
1043 ...input,
1044 + requestMetadata,
1045 ...(requestedScopes !== undefined ? { requestedScopes } : {}),
1046 }).pipe(
1047 + // Every T3 Connect key that gets in is remembered, so turning approval on later
1048 + // keeps the devices already in use and lists them for review.
1049 + Effect.tap((grant) =>
1050 + grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint
1051 + ? bootstrapCredentials
1052 + .trustConnectDevice(input.proofKeyThumbprint, requestMetadata)
1053 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })))
1054 + : Effect.void,
1055 + ),
1056 Effect.flatMap((grant) =>
1057 Effect.gen(function* () {
1058 const grantedScopes =
@@ -1018,6 +1105,8 @@ export const make = Effect.gen(function* () {
1105 ),
1106 ),
1107 ),
1108 + (exchange) =>
1109 + input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange,
1110 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
1111 );
1112 };
@@ -1040,6 +1129,7 @@ export const make = Effect.gen(function* () {
1129 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
1130 ...(input?.purpose ? { purpose: input.purpose } : {}),
1131 ...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
1132 + ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
1133 });
1134 return {
1135 id: issued.id,
@@ -1094,6 +1184,106 @@ export const make = Effect.gen(function* () {
1184 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
1185 );
1186
1187 + const recordConnectRequest = (pairingLinkId: string, client: AuthClientMetadata | undefined) =>
1188 + client === undefined
1189 + ? Effect.void
1190 + : bootstrapCredentials
1191 + .recordConnectRequestClient(pairingLinkId, client)
1192 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1193 +
1194 + const issueConnectCredential: EnvironmentAuth["Service"]["issueConnectCredential"] = Effect.fn(
1195 + "EnvironmentAuth.issueConnectCredential",
1196 + )(function* ({ proofKeyThumbprint, requireApproval }) {
1197 + return yield* issueConnectCredentialLocked({ proofKeyThumbprint, requireApproval }).pipe(
1198 + connectTrustLock.withPermits(1),
1199 + );
1200 + });
1201 + // Untraced: the issueConnectCredential span above already covers it.
1202 + const issueConnectCredentialLocked = Effect.fnUntraced(function* ({
1203 + proofKeyThumbprint,
1204 + requireApproval,
1205 + }: Parameters<EnvironmentAuth["Service"]["issueConnectCredential"]>[0]) {
1206 + const mustWait =
1207 + requireApproval &&
1208 + !(yield* bootstrapCredentials
1209 + .isConnectDeviceTrusted(proofKeyThumbprint)
1210 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))));
1211 + if (mustWait) {
1212 + const pending = yield* bootstrapCredentials
1213 + .findPendingConnect(proofKeyThumbprint)
1214 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1215 + if (Option.isSome(pending)) {
1216 + return { credential: pending.value.credential, expiresAt: pending.value.expiresAt };
1217 + }
1218 + }
1219 + const issued = yield* createPairingLink({
1220 + scopes: AuthStandardClientScopes,
1221 + subject: CLOUD_CONNECT_SUBJECT,
1222 + // Long enough for someone to notice the request and approve it.
1223 + ttl: mustWait ? Duration.minutes(10) : Duration.minutes(2),
1224 + label: "T3 Connect",
1225 + proofKeyThumbprint,
1226 + ...(mustWait ? { requiresConnectApproval: true } : {}),
1227 + });
1228 + return { credential: issued.credential, expiresAt: issued.expiresAt };
1229 + });
1230 +
1231 + const approveConnectDevice: EnvironmentAuth["Service"]["approveConnectDevice"] = (
1232 + pairingLinkId,
1233 + ) =>
1234 + bootstrapCredentials.approveConnectRequest(pairingLinkId).pipe(
1235 + Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })),
1236 + Effect.withSpan("EnvironmentAuth.approveConnectDevice"),
1237 + );
1238 +
1239 + const approveConnectDeviceByCode: EnvironmentAuth["Service"]["approveConnectDeviceByCode"] =
1240 + Effect.fn("EnvironmentAuth.approveConnectDeviceByCode")(function* (verificationCode) {
1241 + const wanted = normalizeVerificationCode(verificationCode);
1242 + const links = yield* bootstrapCredentials
1243 + .listActive()
1244 + .pipe(Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })));
1245 + const matches = links.filter(
1246 + (link) =>
1247 + link.connectDeviceRequest !== undefined &&
1248 + normalizeVerificationCode(link.connectDeviceRequest.verificationCode) === wanted,
1249 + );
1250 + // Two waiting devices that share a code are ambiguous; approve neither.
1251 + if (matches.length !== 1) return false;
1252 + return yield* approveConnectDevice(matches[0]!.id);
1253 + });
1254 +
1255 + const listConnectDevices: EnvironmentAuth["Service"]["listConnectDevices"] = () =>
1256 + bootstrapCredentials.listConnectDevices().pipe(
1257 + Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })),
1258 + Effect.withSpan("EnvironmentAuth.listConnectDevices"),
1259 + );
1260 +
1261 + const revokeConnectDevice: EnvironmentAuth["Service"]["revokeConnectDevice"] = Effect.fn(
1262 + "EnvironmentAuth.revokeConnectDevice",
1263 + )(function* (proofKeyThumbprint) {
1264 + return yield* Effect.gen(function* () {
1265 + const removed = yield* bootstrapCredentials
1266 + .revokeConnectDevice(proofKeyThumbprint)
1267 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1268 + const revokedSessions = yield* sessions
1269 + .revokeByProofKey(proofKeyThumbprint)
1270 + .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1271 + return removed || revokedSessions > 0;
1272 + }).pipe(connectTrustLock.withPermits(1));
1273 + });
1274 +
1275 + const revokeConnectDeviceByCode: EnvironmentAuth["Service"]["revokeConnectDeviceByCode"] =
1276 + Effect.fn("EnvironmentAuth.revokeConnectDeviceByCode")(function* (verificationCode) {
1277 + const wanted = normalizeVerificationCode(verificationCode);
1278 + const matches = (yield* listConnectDevices()).filter(
1279 + (device) => normalizeVerificationCode(device.verificationCode) === wanted,
1280 + );
1281 + if (matches.length === 0) return "not-found" as const;
1282 + if (matches.length > 1) return "ambiguous" as const;
1283 + yield* revokeConnectDevice(matches[0]!.proofKeyThumbprint);
1284 + return "revoked" as const;
1285 + });
1286 +
1287 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
1288 sessions
1289 .issue({
@@ -1206,15 +1396,33 @@ export const make = Effect.gen(function* () {
1396 if (currentSessionId === targetSessionId) {
1397 return yield* new ServerAuthForbiddenOperationError({});
1398 }
1399 + const proofKeyThumbprint = yield* sessions
1400 + .proofKeyThumbprintOf(targetSessionId)
1401 + .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1402 + // A T3 Connect device would otherwise mint itself a new session right away.
1403 + if (Option.isSome(proofKeyThumbprint)) {
1404 + const currentProofKey = yield* sessions
1405 + .proofKeyThumbprintOf(currentSessionId)
1406 + .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1407 + if (Option.getOrUndefined(currentProofKey) !== proofKeyThumbprint.value) {
1408 + return yield* revokeConnectDevice(proofKeyThumbprint.value);
1409 + }
1410 + }
1411 return yield* revokeSession(targetSessionId);
1412 });
1413
1212 - const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
1213 - currentSessionId,
1214 - ) =>
1215 - revokeOtherSessionsExcept(currentSessionId).pipe(
1216 - Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
1217 - );
1414 + const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] =
1415 + Effect.fn("EnvironmentAuth.revokeOtherClientSessions")(function* (currentSessionId) {
1416 + const currentProofKey = yield* sessions
1417 + .proofKeyThumbprintOf(currentSessionId)
1418 + .pipe(Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })));
1419 + return yield* Effect.gen(function* () {
1420 + yield* bootstrapCredentials
1421 + .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey))
1422 + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1423 + return yield* revokeOtherSessionsExcept(currentSessionId);
1424 + }).pipe(connectTrustLock.withPermits(1));
1425 + });
1426
1427 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
1428 issueStartupPairingCredential().pipe(
@@ -1370,6 +1578,8 @@ export const make = Effect.gen(function* () {
1578 Effect.catchTags({
1579 ServerAuthInvalidCredentialError: () =>
1580 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1581 + ServerAuthConnectApprovalPendingError: () =>
1582 + Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1583 ServerAuthScopeNotGrantedError: () =>
1584 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1585 }),
@@ -1394,6 +1604,12 @@ export const make = Effect.gen(function* () {
1604 createBrowserSession,
1605 exchangeBootstrapCredentialForAccessToken,
1606 createPairingLink,
1607 + issueConnectCredential,
1608 + approveConnectDevice,
1609 + approveConnectDeviceByCode,
1610 + listConnectDevices,
1611 + revokeConnectDevice,
1612 + revokeConnectDeviceByCode,
1613 issuePairingCredential,
1614 issueStartupPairingCredential,
1615 listPairingLinks,
@@ -1416,6 +1632,8 @@ export const make = Effect.gen(function* () {
1632
1633 const isMcpClientAccess = Schema.is(AuthMcpClientAccess);
1634
1635 +const normalizeVerificationCode = (code: string) => code.toUpperCase().replace(/[^0-9A-Z]/g, "");
1636 +
1637 /** The level an approval code's subject names, or undefined for any other code. */
1638 const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
1639 const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)
@@ -1425,7 +1643,7 @@ const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
1643 };
1644
1645 /** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
1428 -const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;
1646 +const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: CLOUD_CONNECT_SUBJECT } as const;
1647
1648 /**
1649 * Revokes sessions and unused links from pairing the policy no longer allows, so a policy rolled
apps/server/src/auth/PairingGrantStore.ts
+237 -19
@@ -1,5 +1,7 @@
1 import {
2 AuthStandardClientScopes,
3 + type AuthClientMetadata,
4 + type AuthConnectDevice,
5 type AuthEnvironmentScope,
6 type AuthMcpClientAccess,
7 type AuthPairingLink,
@@ -8,6 +10,7 @@ import {
10 PAIRING_CODE_LENGTH,
11 parseMcpApprovalCode,
12 type ServerAuthBootstrapMethod,
13 + connectDeviceVerificationCode,
14 } from "@t3tools/contracts";
15 import {
16 DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,
@@ -27,6 +30,7 @@ import * as Schema from "effect/Schema";
30 import * as Stream from "effect/Stream";
31
32 import * as ServerConfig from "../config.ts";
33 +import * as AuthConnectDevices from "../persistence/AuthConnectDevices.ts";
34 import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
35
36 export interface BootstrapGrant {
@@ -83,11 +87,24 @@ export class BootstrapCredentialScopeNotGrantedError extends Schema.TaggedError<
87 }
88 }
89
90 +/** The credential is valid but its T3 Connect device key still waits for approval. */
91 +export class BootstrapCredentialConnectApprovalPendingError extends Schema.TaggedError<BootstrapCredentialConnectApprovalPendingError>()(
92 + "BootstrapCredentialConnectApprovalPendingError",
93 + {
94 + pairingLinkId: Schema.String,
95 + },
96 +) {
97 + override get message(): string {
98 + return "This T3 Connect device is waiting for approval.";
99 + }
100 +}
101 +
102 export const BootstrapCredentialInvalidError = Schema.Union([
103 UnknownBootstrapCredentialError,
104 ExpiredBootstrapCredentialError,
105 BootstrapCredentialProofKeyMismatchError,
106 UnavailableBootstrapCredentialError,
107 + BootstrapCredentialConnectApprovalPendingError,
108 ]);
109 export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
110
@@ -162,6 +179,18 @@ export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedError
179 }
180 }
181
182 +export class ConnectDevicesError extends Schema.TaggedError<ConnectDevicesError>()(
183 + "ConnectDevicesError",
184 + {
185 + operation: Schema.Literals(["list", "trust", "revoke", "record-request"]),
186 + cause: Schema.Defect(),
187 + },
188 +) {
189 + override get message(): string {
190 + return `Failed to ${this.operation} T3 Connect devices.`;
191 + }
192 +}
193 +
194 export class BootstrapCredentialLookupError extends Schema.TaggedError<BootstrapCredentialLookupError>()(
195 "BootstrapCredentialLookupError",
196 {
@@ -181,6 +210,7 @@ export const BootstrapCredentialInternalError = Schema.Union([
210 BootstrapCredentialConsumeError,
211 BootstrapCredentialConsumeAvailableError,
212 BootstrapCredentialLookupError,
213 + ConnectDevicesError,
214 ]);
215 export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
216 export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
@@ -208,6 +238,9 @@ export type BootstrapCredentialChange =
238 | {
239 readonly type: "pairingLinkRemoved";
240 readonly id: string;
241 + }
242 + | {
243 + readonly type: "connectDevicesChanged";
244 };
245
246 export class PairingGrantStore extends Context.Service<
@@ -222,7 +255,39 @@ export class PairingGrantStore extends Context.Service<
255 readonly purpose?: "startup";
256 /** Issues a hidden `<LEVEL>-` code that only an agent sign-in at this level can spend. */
257 readonly mcpApproval?: AuthMcpClientAccess;
258 + /** Spendable only after someone trusts `proofKeyThumbprint` as a T3 Connect device. */
259 + readonly requiresConnectApproval?: boolean;
260 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
261 + /** A device's open or denied request, reused so retries keep one request and one code. */
262 + readonly findPendingConnect: (
263 + proofKeyThumbprint: string,
264 + ) => Effect.Effect<Option.Option<IssuedBootstrapCredential>, BootstrapCredentialInternalError>;
265 + /** Shows approvers what a waiting device says it is. Only its first description sticks. */
266 + readonly recordConnectRequestClient: (
267 + pairingLinkId: string,
268 + client: AuthClientMetadata,
269 + ) => Effect.Effect<void, BootstrapCredentialInternalError>;
270 + /** Trusts the device key behind a waiting request. False when it is gone or not a request. */
271 + readonly approveConnectRequest: (
272 + pairingLinkId: string,
273 + ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
274 + readonly isConnectDeviceTrusted: (
275 + proofKeyThumbprint: string,
276 + ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
277 + readonly trustConnectDevice: (
278 + proofKeyThumbprint: string,
279 + client: AuthClientMetadata,
280 + ) => Effect.Effect<void, BootstrapCredentialInternalError>;
281 + readonly listConnectDevices: () => Effect.Effect<
282 + ReadonlyArray<AuthConnectDevice>,
283 + BootstrapCredentialInternalError
284 + >;
285 + readonly revokeConnectDevice: (
286 + proofKeyThumbprint: string,
287 + ) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
288 + readonly revokeConnectDevicesExcept: (
289 + keepProofKeyThumbprint: string | null,
290 + ) => Effect.Effect<number, BootstrapCredentialInternalError>;
291 readonly listActive: () => Effect.Effect<
292 ReadonlyArray<AuthPairingLink>,
293 BootstrapCredentialInternalError
@@ -259,6 +324,23 @@ type ConsumeResult =
324 };
325
326 const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
327 +
328 +const toPairingLink = (row: AuthPairingLinks.AuthPairingLinkRecord): AuthPairingLink => ({
329 + id: row.id,
330 + scopes: row.scopes,
331 + subject: row.subject,
332 + ...(row.label ? { label: row.label } : {}),
333 + createdAt: row.createdAt,
334 + expiresAt: row.expiresAt,
335 + ...(row.requiresConnectApproval === 1 && row.proofKeyThumbprint
336 + ? {
337 + connectDeviceRequest: {
338 + verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint),
339 + ...(row.requestedClient ? { client: row.requestedClient } : {}),
340 + },
341 + }
342 + : {}),
343 +});
344 const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
345 const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
346 const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -273,6 +355,7 @@ const make = Effect.gen(function* () {
355 const random = yield* SecureRandom.SecureRandom;
356 const config = yield* ServerConfig.ServerConfig;
357 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
358 + const connectDevices = yield* AuthConnectDevices.AuthConnectDeviceRepository;
359 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
360 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
361 const generatePairingToken = Effect.gen(function* () {
@@ -348,25 +431,10 @@ const make = Effect.gen(function* () {
431 function* () {
432 const now = yield* DateTime.now;
433 const rows = yield* pairingLinks.listActive({ now });
351 -
352 - return rows.map((row) =>
353 - row.label
354 - ? ({
355 - id: row.id,
356 - scopes: row.scopes,
357 - subject: row.subject,
358 - label: row.label,
359 - createdAt: row.createdAt,
360 - expiresAt: row.expiresAt,
361 - } satisfies AuthPairingLink)
362 - : ({
363 - id: row.id,
364 - scopes: row.scopes,
365 - subject: row.subject,
366 - createdAt: row.createdAt,
367 - expiresAt: row.expiresAt,
368 - } satisfies AuthPairingLink),
369 - );
434 + // An approved request only waits for its device to come back and spend it.
435 + return rows
436 + .filter((row) => !(row.requiresConnectApproval === 1 && row.connectApproved === 1))
437 + .map(toPairingLink);
438 },
439 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
440 );
@@ -426,6 +494,7 @@ const make = Effect.gen(function* () {
494 subject,
495 label: input?.label ?? null,
496 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
497 + ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
498 createdAt: now,
499 expiresAt: expiresAt,
500 })
@@ -449,6 +518,13 @@ const make = Effect.gen(function* () {
518 ...(input?.label ? { label: input.label } : {}),
519 createdAt: now,
520 expiresAt,
521 + ...(input?.requiresConnectApproval && input.proofKeyThumbprint
522 + ? {
523 + connectDeviceRequest: {
524 + verificationCode: connectDeviceVerificationCode(input.proofKeyThumbprint),
525 + },
526 + }
527 + : {}),
528 });
529 }
530 return issued;
@@ -635,12 +711,153 @@ const make = Effect.gen(function* () {
711 return yield* new BootstrapCredentialScopeNotGrantedError({});
712 }
713
714 + if (matching.value.requiresConnectApproval === 1 && matching.value.connectApproved === 0) {
715 + return yield* new BootstrapCredentialConnectApprovalPendingError({
716 + pairingLinkId: matching.value.id,
717 + });
718 + }
719 +
720 return yield* new UnavailableBootstrapCredentialError({});
721 },
722 );
723
724 + const emitConnectDevicesChanged = PubSub.publish(changesPubSub, {
725 + type: "connectDevicesChanged",
726 + }).pipe(Effect.asVoid);
727 +
728 + const findPendingConnect: PairingGrantStore["Service"]["findPendingConnect"] = Effect.fn(
729 + "PairingGrantStore.findPendingConnect",
730 + )(
731 + function* (proofKeyThumbprint) {
732 + const now = yield* DateTime.now;
733 + const row = yield* pairingLinks.findPendingConnect({ proofKeyThumbprint, now });
734 + return Option.map(row, (link): IssuedBootstrapCredential => ({
735 + id: link.id,
736 + credential: link.credential,
737 + ...(link.label ? { label: link.label } : {}),
738 + proofKeyThumbprint,
739 + expiresAt: link.expiresAt,
740 + }));
741 + },
742 + Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })),
743 + );
744 +
745 + const recordConnectRequestClient: PairingGrantStore["Service"]["recordConnectRequestClient"] =
746 + Effect.fn("PairingGrantStore.recordConnectRequestClient")(function* (pairingLinkId, client) {
747 + const recorded = yield* pairingLinks
748 + .recordConnectRequestClient({ id: pairingLinkId, client })
749 + .pipe(
750 + Effect.mapError(
751 + (cause) => new ConnectDevicesError({ operation: "record-request", cause }),
752 + ),
753 + );
754 + if (!recorded) return;
755 + const now = yield* DateTime.now;
756 + const row = yield* pairingLinks
757 + .getActiveById({ id: pairingLinkId, now })
758 + .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
759 + if (Option.isSome(row)) yield* emitUpsert(toPairingLink(row.value));
760 + });
761 +
762 + const trustConnectDevice: PairingGrantStore["Service"]["trustConnectDevice"] = Effect.fn(
763 + "PairingGrantStore.trustConnectDevice",
764 + )(function* (proofKeyThumbprint, client) {
765 + const approvedAt = yield* DateTime.now;
766 + yield* connectDevices
767 + .trust({ proofKeyThumbprint, client, approvedAt })
768 + .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
769 + yield* emitConnectDevicesChanged;
770 + });
771 +
772 + const approveConnectRequest: PairingGrantStore["Service"]["approveConnectRequest"] = Effect.fn(
773 + "PairingGrantStore.approveConnectRequest",
774 + )(function* (pairingLinkId) {
775 + const now = yield* DateTime.now;
776 + const row = yield* pairingLinks
777 + .getActiveById({ id: pairingLinkId, now })
778 + .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
779 + if (
780 + Option.isNone(row) ||
781 + row.value.requiresConnectApproval !== 1 ||
782 + row.value.proofKeyThumbprint === null
783 + ) {
784 + return false;
785 + }
786 + yield* connectDevices
787 + .trust({
788 + proofKeyThumbprint: row.value.proofKeyThumbprint,
789 + client: row.value.requestedClient,
790 + approvedAt: now,
791 + })
792 + .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "trust", cause })));
793 + yield* emitRemoved(pairingLinkId);
794 + yield* emitConnectDevicesChanged;
795 + return true;
796 + });
797 +
798 + const isConnectDeviceTrusted: PairingGrantStore["Service"]["isConnectDeviceTrusted"] = (
799 + proofKeyThumbprint,
800 + ) =>
801 + connectDevices
802 + .isTrusted(proofKeyThumbprint)
803 + .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
804 +
805 + const listConnectDevices: PairingGrantStore["Service"]["listConnectDevices"] = () =>
806 + connectDevices.list().pipe(
807 + Effect.map((rows) =>
808 + rows.map((row): AuthConnectDevice => ({
809 + proofKeyThumbprint: row.proofKeyThumbprint,
810 + verificationCode: connectDeviceVerificationCode(row.proofKeyThumbprint),
811 + ...(row.client ? { client: row.client } : {}),
812 + approvedAt: row.approvedAt,
813 + })),
814 + ),
815 + Effect.mapError((cause) => new ConnectDevicesError({ operation: "list", cause })),
816 + );
817 +
818 + // A credential minted before revocation is still spendable; it must die with the trust,
819 + // or exchanging it would trust the key again without approval.
820 + const revokeUnspentLinks = Effect.fn("PairingGrantStore.revokeUnspentLinks")(function* (
821 + input: Omit<AuthPairingLinks.RevokeUnspentByProofKeyInput, "revokedAt">,
822 + ) {
823 + const revokedAt = yield* DateTime.now;
824 + const ids = yield* pairingLinks
825 + .revokeUnspentByProofKey({ ...input, revokedAt })
826 + .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
827 + yield* Effect.forEach(ids, emitRemoved, { discard: true });
828 + });
829 +
830 + const revokeConnectDevice: PairingGrantStore["Service"]["revokeConnectDevice"] = Effect.fn(
831 + "PairingGrantStore.revokeConnectDevice",
832 + )(function* (proofKeyThumbprint) {
833 + yield* revokeUnspentLinks({ proofKeyThumbprint, keepProofKeyThumbprint: null });
834 + const removed = yield* connectDevices
835 + .remove(proofKeyThumbprint)
836 + .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
837 + if (removed) yield* emitConnectDevicesChanged;
838 + return removed;
839 + });
840 +
841 + const revokeConnectDevicesExcept: PairingGrantStore["Service"]["revokeConnectDevicesExcept"] =
842 + Effect.fn("PairingGrantStore.revokeConnectDevicesExcept")(function* (keepProofKeyThumbprint) {
843 + yield* revokeUnspentLinks({ proofKeyThumbprint: null, keepProofKeyThumbprint });
844 + const removed = yield* connectDevices
845 + .removeAllExcept(keepProofKeyThumbprint)
846 + .pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
847 + if (removed > 0) yield* emitConnectDevicesChanged;
848 + return removed;
849 + });
850 +
851 return PairingGrantStore.of({
852 issueOneTimeToken,
853 + findPendingConnect,
854 + recordConnectRequestClient,
855 + approveConnectRequest,
856 + isConnectDeviceTrusted,
857 + trustConnectDevice,
858 + listConnectDevices,
859 + revokeConnectDevice,
860 + revokeConnectDevicesExcept,
861 listActive,
862 get streamChanges() {
863 return Stream.fromPubSub(changesPubSub);
@@ -652,4 +869,5 @@ const make = Effect.gen(function* () {
869
870 export const layer = Layer.effect(PairingGrantStore, make).pipe(
871 Layer.provideMerge(AuthPairingLinks.layer),
872 + Layer.provideMerge(AuthConnectDevices.layer),
873 );
apps/server/src/auth/RpcAuthorization.test.ts
+35 -27
@@ -4,6 +4,7 @@ import {
4 AuthFilesystemReadScope,
5 AuthProvidersManageScope,
6 AuthSettingsWriteScope,
7 + AuthAccessWriteScope,
8 DEFAULT_SERVER_SETTINGS,
9 ProviderDriverKind,
10 ProviderInstanceId,
@@ -263,35 +264,42 @@ describe("settings mutation authorization", () => {
264 }),
265 );
266
266 - it.effect("does not let a settings grant create or remove providers or secret providers", () =>
267 - Effect.gen(function* () {
268 - let handled = false;
269 - const client = yield* RpcTest.makeClient(group).pipe(
270 - Effect.provide(
271 - Layer.mergeAll(
272 - group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
273 - Effect.sync(() => {
274 - handled = true;
275 - return DEFAULT_SERVER_SETTINGS;
276 - }),
267 + it.effect(
268 + "does not let a settings grant manage providers or turn off T3 Connect device approval",
269 + () =>
270 + Effect.gen(function* () {
271 + let handled = false;
272 + const client = yield* RpcTest.makeClient(group).pipe(
273 + Effect.provide(
274 + Layer.mergeAll(
275 + group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
276 + Effect.sync(() => {
277 + handled = true;
278 + return DEFAULT_SERVER_SETTINGS;
279 + }),
280 + ),
281 + RpcAuthorization.layer([AuthSettingsWriteScope]),
282 ),
278 - RpcAuthorization.layer([AuthSettingsWriteScope]),
283 ),
280 - ),
281 - );
282 - expect(
283 - yield* client[WS_METHODS.serverUpdateSettings]({
284 - patch: {},
285 - providerInstanceMutation,
286 - }).pipe(Effect.flip),
287 - ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
288 - expect(
289 - yield* client[WS_METHODS.serverUpdateSettings]({
290 - patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
291 - }).pipe(Effect.flip),
292 - ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
293 - expect(handled).toBe(false);
294 - }),
284 + );
285 + expect(
286 + yield* client[WS_METHODS.serverUpdateSettings]({
287 + patch: {},
288 + providerInstanceMutation,
289 + }).pipe(Effect.flip),
290 + ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
291 + expect(
292 + yield* client[WS_METHODS.serverUpdateSettings]({
293 + patch: { secretProviders: { [SecretProviderId.make("personal")]: null } },
294 + }).pipe(Effect.flip),
295 + ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
296 + expect(
297 + yield* client[WS_METHODS.serverUpdateSettings]({
298 + patch: { requireConnectDeviceApproval: false },
299 + }).pipe(Effect.flip),
300 + ).toMatchObject({ requiredPermission: AuthAccessWriteScope });
301 + expect(handled).toBe(false);
302 + }),
303 );
304 });
305
apps/server/src/auth/SessionStore.ts
+44
@@ -350,6 +350,18 @@ export class OtherSessionsRevocationError extends Schema.TaggedError<OtherSessio
350 }
351 }
352
353 +export class ProofKeySessionsError extends Schema.TaggedError<ProofKeySessionsError>()(
354 + "ProofKeySessionsError",
355 + {
356 + operation: Schema.Literals(["lookup", "revoke"]),
357 + ...sessionCredentialInternalErrorContext,
358 + },
359 +) {
360 + override get message(): string {
361 + return `Failed to ${this.operation} sessions by proof key.`;
362 + }
363 +}
364 +
365 export const SessionCredentialInternalError = Schema.Union([
366 SessionClaimsEncodingError,
367 SessionCredentialIssueError,
@@ -359,6 +371,7 @@ export const SessionCredentialInternalError = Schema.Union([
371 ActiveSessionsListError,
372 SessionRevocationError,
373 OtherSessionsRevocationError,
374 + ProofKeySessionsError,
375 ]);
376 export type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;
377
@@ -419,6 +432,13 @@ export class SessionStore extends Context.Service<
432 readonly revokeAllExcept: (
433 sessionId: AuthSessionId,
434 ) => Effect.Effect<number, SessionCredentialInternalError>;
435 + readonly proofKeyThumbprintOf: (
436 + sessionId: AuthSessionId,
437 + ) => Effect.Effect<Option.Option<string>, SessionCredentialInternalError>;
438 + /** Revokes every session bound to this DPoP key, so a device it belongs to is cut off now. */
439 + readonly revokeByProofKey: (
440 + proofKeyThumbprint: string,
441 + ) => Effect.Effect<number, SessionCredentialInternalError>;
442 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
443 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
444 }
@@ -697,6 +717,7 @@ const make = Effect.gen(function* () {
717 },
718 issuedAt,
719 expiresAt,
720 + ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
721 } satisfies AuthSessions.CreateAuthSessionInput;
722 const replacedSessionIds = yield* (
723 input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod
@@ -1005,6 +1026,27 @@ const make = Effect.gen(function* () {
1026 },
1027 );
1028
1029 + const proofKeyThumbprintOf: SessionStore["Service"]["proofKeyThumbprintOf"] = (sessionId) =>
1030 + authSessions
1031 + .getProofKeyThumbprint({ sessionId })
1032 + .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "lookup", cause })));
1033 +
1034 + const revokeByProofKey: SessionStore["Service"]["revokeByProofKey"] = Effect.fn(
1035 + "SessionStore.revokeByProofKey",
1036 + )(function* (proofKeyThumbprint) {
1037 + const revokedAt = yield* DateTime.now;
1038 + const revokedSessionIds = yield* authSessions
1039 + .revokeByProofKey({ proofKeyThumbprint, revokedAt })
1040 + .pipe(Effect.mapError((cause) => new ProofKeySessionsError({ operation: "revoke", cause })));
1041 + yield* Ref.update(connectedSessionsRef, (current) => {
1042 + const next = new Map(current);
1043 + for (const revokedSessionId of revokedSessionIds) next.delete(revokedSessionId);
1044 + return next;
1045 + });
1046 + yield* Effect.forEach(revokedSessionIds, emitRemoved, { discard: true });
1047 + return revokedSessionIds.length;
1048 + });
1049 +
1050 const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
1051 "SessionStore.revokeAllExcept",
1052 )(function* (sessionId) {
@@ -1112,6 +1154,8 @@ const make = Effect.gen(function* () {
1154 },
1155 revoke,
1156 revokeAllExcept,
1157 + proofKeyThumbprintOf,
1158 + revokeByProofKey,
1159 markConnected,
1160 markDisconnected,
1161 });
apps/server/src/auth/http.ts
+43 -1
@@ -5,6 +5,7 @@ import {
5 AuthGrantScope,
6 EnvironmentAuthInvalidError,
7 type EnvironmentAuthInvalidReason,
8 + EnvironmentConnectApprovalPendingError,
9 EnvironmentHttpApi,
10 EnvironmentHttpForbiddenError,
11 EnvironmentInternalError,
@@ -253,7 +254,7 @@ export const layerAuthenticatedAuth = Layer.effect(
254 scopes: new Set(session.scopes),
255 }),
256 );
256 - return yield* session.subject === "cloud-connect"
257 + return yield* session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT
258 ? traceAuthenticatedRelayRequest(handler, { startTime, endTime })
259 : handler;
260 }).pipe(Effect.catchTags({ EnvironmentAuthInvalidError: appendDpopChallengeOnUnauthorized }));
@@ -407,6 +408,19 @@ export const layer = HttpApiBuilder.group(
408 EnvironmentAuth.serverAuthDpopFailureReason(error),
409 ),
410 ),
411 + Effect.catchTags({
412 + ServerAuthConnectApprovalPendingError: () =>
413 + currentEnvironmentTraceId.pipe(
414 + Effect.flatMap((traceId) =>
415 + Effect.fail(
416 + new EnvironmentConnectApprovalPendingError({
417 + code: "connect_approval_pending",
418 + traceId,
419 + }),
420 + ),
421 + ),
422 + ),
423 + }),
424 Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>
425 failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),
426 ),
@@ -509,6 +523,34 @@ export const layer = HttpApiBuilder.group(
523 ),
524 ),
525 )
526 + .handle(
527 + "approveConnectDevice",
528 + Effect.fn("environment.auth.approveConnectDevice")(
529 + function* (args) {
530 + yield* annotateEnvironmentRequest(args.endpoint.name);
531 + yield* requireEnvironmentScope(AuthAccessWriteScope);
532 + const approved = yield* serverAuth.approveConnectDevice(args.payload.pairingLinkId);
533 + return { approved };
534 + },
535 + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
536 + failEnvironmentInternal("connect_device_approve_failed", error),
537 + ),
538 + ),
539 + )
540 + .handle(
541 + "revokeConnectDevice",
542 + Effect.fn("environment.auth.revokeConnectDevice")(
543 + function* (args) {
544 + yield* annotateEnvironmentRequest(args.endpoint.name);
545 + yield* requireEnvironmentScope(AuthAccessWriteScope);
546 + const revoked = yield* serverAuth.revokeConnectDevice(args.payload.proofKeyThumbprint);
547 + return { revoked };
548 + },
549 + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
550 + failEnvironmentInternal("connect_device_revoke_failed", error),
551 + ),
552 + ),
553 + )
554 .handle(
555 "revokeOtherClients",
556 Effect.fn("environment.auth.revokeOtherClients")(
apps/server/src/cli/auth.ts
+78 -1
@@ -10,6 +10,7 @@ import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
10 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
11
12 import {
13 + formatConnectDeviceList,
14 formatIssuedPairingCredential,
15 formatIssuedSession,
16 formatPairingCredentialList,
@@ -166,6 +167,82 @@ const pairingCommand = Command.make("pairing").pipe(
167 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
168 );
169
170 +const connectDeviceListCommand = Command.make("list", {
171 + ...authLocationFlags,
172 + json: jsonFlag,
173 +}).pipe(
174 + Command.withDescription(
175 + "List T3 Connect devices waiting for approval and those already trusted.",
176 + ),
177 + Command.withHandler((flags) =>
178 + runWithEnvironmentAuth(
179 + flags,
180 + (environmentAuth) =>
181 + Effect.gen(function* () {
182 + const waiting = (yield* environmentAuth.listPairingLinks()).flatMap((link) =>
183 + link.connectDeviceRequest ? [link.connectDeviceRequest] : [],
184 + );
185 + const trusted = yield* environmentAuth.listConnectDevices();
186 + yield* Console.log(formatConnectDeviceList({ waiting, trusted }, { json: flags.json }));
187 + }),
188 + { quietLogs: flags.json },
189 + ),
190 + ),
191 +);
192 +
193 +const verificationCodeArgument = Argument.String("code").pipe(
194 + Argument.withDescription("The code the device shows, such as `K7QM-2XFD`."),
195 +);
196 +
197 +const connectDeviceApproveCommand = Command.make("approve", {
198 + ...authLocationFlags,
199 + code: verificationCodeArgument,
200 +}).pipe(
201 + Command.withDescription("Approve the waiting T3 Connect device that shows this code."),
202 + Command.withHandler((flags) =>
203 + runWithEnvironmentAuth(flags, (environmentAuth) =>
204 + Effect.gen(function* () {
205 + const approved = yield* environmentAuth.approveConnectDeviceByCode(flags.code);
206 + yield* Console.log(
207 + approved
208 + ? `Approved ${flags.code}. The device connects on its next try.\n`
209 + : `No device waiting for approval shows ${flags.code}.\n`,
210 + );
211 + }),
212 + ),
213 + ),
214 +);
215 +
216 +const connectDeviceRevokeCommand = Command.make("revoke", {
217 + ...authLocationFlags,
218 + code: verificationCodeArgument,
219 +}).pipe(
220 + Command.withDescription("Stop trusting a T3 Connect device and end its sessions."),
221 + Command.withHandler((flags) =>
222 + runWithEnvironmentAuth(flags, (environmentAuth) =>
223 + Effect.gen(function* () {
224 + const outcome = yield* environmentAuth.revokeConnectDeviceByCode(flags.code);
225 + yield* Console.log(
226 + outcome === "revoked"
227 + ? `Revoked ${flags.code}. If approval for new devices is off, it can connect again on its own.\n`
228 + : outcome === "ambiguous"
229 + ? `More than one trusted device shows ${flags.code}; revoke it from a client.\n`
230 + : `No trusted device shows ${flags.code}.\n`,
231 + );
232 + }),
233 + ),
234 + ),
235 +);
236 +
237 +const connectDeviceCommand = Command.make("connect-device").pipe(
238 + Command.withDescription("Approve and revoke devices that reach this host through T3 Connect."),
239 + Command.withSubcommands([
240 + connectDeviceListCommand,
241 + connectDeviceApproveCommand,
242 + connectDeviceRevokeCommand,
243 + ]),
244 +);
245 +
246 const sessionIssueCommand = Command.make("issue", {
247 ...authLocationFlags,
248 scopes: authScopesFlag(AuthStandardClientScopes),
@@ -250,5 +327,5 @@ const sessionCommand = Command.make("session").pipe(
327
328 export const authCommand = Command.make("auth").pipe(
329 Command.withDescription("Manage the local auth control plane for headless deployments."),
253 - Command.withSubcommands([pairingCommand, sessionCommand]),
330 + Command.withSubcommands([pairingCommand, sessionCommand, connectDeviceCommand]),
331 );
apps/server/src/cliAuthFormat.ts
+49 -1
@@ -1,4 +1,10 @@
1 -import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
1 +import type {
2 + AuthClientMetadata,
3 + AuthClientSession,
4 + AuthConnectDevice,
5 + AuthConnectDeviceRequest,
6 + AuthPairingLink,
7 +} from "@t3tools/contracts";
8 import * as DateTime from "effect/DateTime";
9
10 import type { IssuedBearerSession, IssuedPairingLink } from "./auth/EnvironmentAuth.ts";
@@ -190,3 +196,45 @@ export function formatSessionList(
196 .join(`${newline}${newline}`) + newline
197 );
198 }
199 +
200 +export function formatConnectDeviceList(
201 + devices: {
202 + readonly waiting: ReadonlyArray<AuthConnectDeviceRequest>;
203 + readonly trusted: ReadonlyArray<AuthConnectDevice>;
204 + },
205 + options?: {
206 + readonly json?: boolean;
207 + },
208 +): string {
209 + if (options?.json) {
210 + return `${JSON.stringify(
211 + {
212 + waiting: devices.waiting,
213 + trusted: devices.trusted.map((device) => ({
214 + ...device,
215 + approvedAt: toIsoString(device.approvedAt),
216 + })),
217 + },
218 + null,
219 + 2,
220 + )}${newline}`;
221 + }
222 + const describe = (client: AuthClientMetadata | undefined) =>
223 + client ? formatClientMetadata(client) : "unlabeled client";
224 + return (
225 + [
226 + devices.waiting.length === 0
227 + ? "No devices are waiting for approval."
228 + : "Waiting for approval:",
229 + ...devices.waiting.map(
230 + (request) => ` ${request.verificationCode} ${describe(request.client)}`,
231 + ),
232 + "",
233 + devices.trusted.length === 0 ? "No trusted T3 Connect devices." : "Trusted:",
234 + ...devices.trusted.map(
235 + (device) =>
236 + ` ${device.verificationCode} ${describe(device.client)} since ${toIsoString(device.approvedAt)}`,
237 + ),
238 + ].join(newline) + newline
239 + );
240 +}
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+2
@@ -62,6 +62,7 @@ import { pendingServiceUpdateExists } from "./updateHandoff.ts";
62 import { managedTunnelStartupAction } from "./managedTunnelStartup.ts";
63 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
64 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
65 +import * as ServerSettings from "../serverSettings.ts";
66
67 const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
68 new ServerSecretStore.SecretStorePersistError({
@@ -183,6 +184,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
184 CloudLink.layer.pipe(
185 Layer.provide(EnvironmentKeys.layer),
186 Layer.provide(ManagedPolicy.layerTest()),
187 + Layer.provide(ServerSettings.ServerSettingsService.layerTest()),
188 ),
189 ),
190 Effect.provideService(
apps/server/src/cloud/CloudLink.test.ts
+18 -16
@@ -33,6 +33,7 @@ import {
33 RELAY_URL_SECRET,
34 } from "./config.ts";
35 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36 +import * as ServerSettings from "../serverSettings.ts";
37
38 const encode = (value: string) => new TextEncoder().encode(value);
39
@@ -58,7 +59,9 @@ const withService = <A, E>(
59 readonly mintCredential: CloudLink.CloudLink["Service"]["mintCredential"];
60 readonly stored: Map<string, Uint8Array>;
61 readonly relayCalls: Array<boolean>;
61 - readonly pairingLinkLabels: Array<string | undefined>;
62 + readonly connectCredentialRequests: Array<
63 + Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["issueConnectCredential"]>[0]
64 + >;
65 }) => Effect.Effect<A, E, never>,
66 ) =>
67 Effect.gen(function* () {
@@ -71,7 +74,9 @@ const withService = <A, E>(
74 [CLOUD_LINKED_USER_ID, encode("cloud-user-1")],
75 ]);
76 const relayCalls: Array<boolean> = [];
74 - const pairingLinkLabels: Array<string | undefined> = [];
77 + const connectCredentialRequests: Array<
78 + Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["issueConnectCredential"]>[0]
79 + > = [];
80 const fetch: typeof globalThis.fetch = Object.assign(
81 (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {
82 const payload = JSON.parse(String(init?.body)) as { holdWebhooksWhileOffline: boolean };
@@ -87,6 +92,7 @@ const withService = <A, E>(
92 { preconnect: () => {} },
93 );
94 const layerDependencies = Layer.mergeAll(
95 + ServerSettings.ServerSettingsService.layerTest(),
96 Layer.mock(ServerSecretStore.ServerSecretStore)({
97 get: (name) =>
98 (options.failActivityRead && name === PUBLISH_AGENT_ACTIVITY_SECRET) ||
@@ -120,17 +126,10 @@ const withService = <A, E>(
126 latest: Effect.succeedNone,
127 }),
128 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
123 - createPairingLink: (input) =>
129 + issueConnectCredential: (input) =>
130 Effect.sync(() => {
125 - pairingLinkLabels.push(input?.label);
126 - return {
127 - id: "pairing-1",
128 - credential: "pairing-credential",
129 - scopes: input?.scopes ?? [],
130 - subject: input?.subject ?? "",
131 - createdAt: DateTime.makeUnsafe(0),
132 - expiresAt: DateTime.makeUnsafe(120_000),
133 - };
131 + connectCredentialRequests.push(input);
132 + return { credential: "pairing-credential", expiresAt: DateTime.makeUnsafe(120_000) };
133 }),
134 }),
135 Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
@@ -152,7 +151,7 @@ const withService = <A, E>(
151 mintCredential: link.mintCredential,
152 stored,
153 relayCalls,
155 - pairingLinkLabels,
154 + connectCredentialRequests,
155 });
156 }).pipe(
157 Effect.provide(
@@ -297,8 +296,8 @@ it.effect("an update the client walks away from still finishes", () => {
296 );
297 });
298
300 -it.effect('names T3 Connect sessions "T3 Connect" in authorized clients', () =>
301 - withService({}, ({ mintCredential, pairingLinkLabels }) =>
299 +it.effect("mints a T3 Connect credential under the host's device approval setting", () =>
300 + withService({}, ({ mintCredential, connectCredentialRequests }) =>
301 Effect.gen(function* () {
302 const proof = yield* signRelayJwt({
303 privateKey: cloudMintKeys.privateKey,
@@ -318,7 +317,9 @@ it.effect('names T3 Connect sessions "T3 Connect" in authorized clients', () =>
317 },
318 }).pipe(Effect.provide(NodePlatformCrypto.layerSignature));
319 yield* mintCredential({ proof });
321 - assert.deepEqual(pairingLinkLabels, ["T3 Connect"]);
320 + assert.deepEqual(connectCredentialRequests, [
321 + { proofKeyThumbprint: "client-jkt", requireApproval: false },
322 + ]);
323 }),
324 ),
325 );
@@ -331,6 +332,7 @@ it.effect("unlinks on startup and refuses to link when the policy turns Connect
332 ]);
333 const appliedConfigs: Array<unknown> = [];
334 const layerDependencies = Layer.mergeAll(
335 + ServerSettings.ServerSettingsService.layerTest(),
336 Layer.mock(ServerSecretStore.ServerSecretStore)({
337 get: (name) => Effect.succeed(Option.fromNullishOr(stored.get(name))),
338 set: (name, value) => Effect.sync(() => void stored.set(name, value)),
apps/server/src/cloud/CloudLink.ts
+7 -6
@@ -1,5 +1,4 @@
1 import {
2 - AuthStandardClientScopes,
2 EnvironmentAuthenticatedPrincipal,
3 type EnvironmentCloudLinkStateResult,
4 type EnvironmentCloudPreferencesRequest,
@@ -100,6 +99,7 @@ import * as ConnectReachability from "./ConnectReachability.ts";
99 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
100 import * as ManagedLimits from "../policy/managedLimits.ts";
101 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
102 +import * as ServerSettings from "../serverSettings.ts";
103 import { relayUrlConfig } from "./publicConfig.ts";
104 import {
105 filterRelayResponse,
@@ -519,6 +519,7 @@ const make = Effect.gen(function* () {
519 const endpointRuntime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
520 const reachability = yield* ConnectReachability.ConnectReachability;
521 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
522 + const serverSettings = yield* ServerSettings.ServerSettingsService;
523 const cliTokenManager = yield* CliTokenManager.CloudCliTokenManager;
524 const httpClient = yield* HttpClient.HttpClient;
525 const httpServer = yield* HttpServer.HttpServer;
@@ -1590,12 +1591,12 @@ const make = Effect.gen(function* () {
1591 return yield* new CloudLinkProofReplayedError({ request: "mint" });
1592 }
1593
1593 - const issued = yield* environmentAuth.createPairingLink({
1594 - scopes: AuthStandardClientScopes,
1595 - subject: "cloud-connect",
1596 - ttl: Duration.minutes(2),
1597 - label: "T3 Connect",
1594 + const settings = yield* serverSettings.getSettings.pipe(
1595 + Effect.catch(internalError("issue-credential")),
1596 + );
1597 + const issued = yield* environmentAuth.issueConnectCredential({
1598 proofKeyThumbprint: proof.clientProofKeyThumbprint,
1599 + requireApproval: settings.requireConnectDeviceApproval,
1600 });
1601 const responsePayload = {
1602 iss: `t3-env:${environmentId}`,
apps/server/src/cloud/http.test.ts
+2
@@ -39,6 +39,7 @@ import * as ConnectHttp from "./http.ts";
39 import * as ConnectReachability from "./ConnectReachability.ts";
40 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
41 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
42 +import * as ServerSettings from "../serverSettings.ts";
43
44 const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
45 const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773";
@@ -79,6 +80,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
80 Layer.provide([AuthHttp.layer, ConnectHttp.layer]),
81 Layer.provide(AuthHttp.layerAuthenticatedAuth),
82 Layer.provide(CloudLink.layer),
83 + Layer.provide(ServerSettings.ServerSettingsService.layerTest()),
84 Layer.provide(EnvironmentKeys.layer),
85 Layer.provide(
86 Layer.mock(ConnectReachability.ConnectReachability)({ latest: Effect.succeedNone }),
apps/server/src/persistence/AuthConnectDevices.ts new
+160
@@ -0,0 +1,160 @@
1 +import * as Context from "effect/Context";
2 +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 +import * as Effect from "effect/Effect";
4 +import * as Layer from "effect/Layer";
5 +import * as Schema from "effect/Schema";
6 +import * as SqlClient from "effect/sql/SqlClient";
7 +import * as SqlSchema from "effect/sql/SqlSchema";
8 +
9 +import { AuthClientMetadata } from "@t3tools/contracts";
10 +
11 +import { type AuthPairingLinkRepositoryError, PersistenceSqlError } from "./Errors.ts";
12 +
13 +export const AuthConnectDeviceRecord = Schema.Struct({
14 + proofKeyThumbprint: Schema.String,
15 + client: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)),
16 + approvedAt: Schema.DateTimeUtcFromString,
17 +});
18 +export type AuthConnectDeviceRecord = typeof AuthConnectDeviceRecord.Type;
19 +
20 +const TrustInput = Schema.Struct({
21 + proofKeyThumbprint: Schema.String,
22 + client: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)),
23 + approvedAt: Schema.DateTimeUtcFromString,
24 +});
25 +
26 +const ThumbprintInput = Schema.Struct({ proofKeyThumbprint: Schema.String });
27 +
28 +const RemoveAllExceptInput = Schema.Struct({
29 + keepProofKeyThumbprint: Schema.NullOr(Schema.String),
30 +});
31 +
32 +/** T3 Connect device keys this environment lets in without asking. A key leaves when revoked. */
33 +export class AuthConnectDeviceRepository extends Context.Service<
34 + AuthConnectDeviceRepository,
35 + {
36 + /** Adds the key, or refreshes how an already trusted key describes itself. */
37 + readonly trust: (
38 + input: typeof TrustInput.Type,
39 + ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;
40 + readonly isTrusted: (
41 + proofKeyThumbprint: string,
42 + ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
43 + readonly list: () => Effect.Effect<
44 + ReadonlyArray<AuthConnectDeviceRecord>,
45 + AuthPairingLinkRepositoryError
46 + >;
47 + readonly remove: (
48 + proofKeyThumbprint: string,
49 + ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
50 + readonly removeAllExcept: (
51 + keepProofKeyThumbprint: string | null,
52 + ) => Effect.Effect<number, AuthPairingLinkRepositoryError>;
53 + }
54 +>()("t3/persistence/AuthConnectDevices/AuthConnectDeviceRepository") {}
55 +
56 +const sqlError = (operation: string) => (cause: unknown) =>
57 + new PersistenceSqlError({ operation, cause });
58 +
59 +/** @public */
60 +export const make = Effect.gen(function* () {
61 + const sql = yield* SqlClient.SqlClient;
62 +
63 + const trustRow = SqlSchema.void({
64 + Request: TrustInput,
65 + execute: ({ proofKeyThumbprint, client, approvedAt }) =>
66 + sql`
67 + INSERT INTO auth_connect_devices (proof_key_thumbprint, client_json, approved_at)
68 + VALUES (${proofKeyThumbprint}, ${client}, ${approvedAt})
69 + ON CONFLICT (proof_key_thumbprint) DO UPDATE
70 + SET client_json = COALESCE(excluded.client_json, auth_connect_devices.client_json)
71 + `,
72 + });
73 +
74 + const isTrustedRow = SqlSchema.findAll({
75 + Request: ThumbprintInput,
76 + Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
77 + execute: ({ proofKeyThumbprint }) =>
78 + sql`
79 + SELECT proof_key_thumbprint AS "proofKeyThumbprint"
80 + FROM auth_connect_devices
81 + WHERE proof_key_thumbprint = ${proofKeyThumbprint}
82 + `,
83 + });
84 +
85 + const listRows = SqlSchema.findAll({
86 + Request: Schema.Void,
87 + Result: AuthConnectDeviceRecord,
88 + execute: () =>
89 + sql`
90 + SELECT
91 + proof_key_thumbprint AS "proofKeyThumbprint",
92 + client_json AS "client",
93 + approved_at AS "approvedAt"
94 + FROM auth_connect_devices
95 + ORDER BY approved_at DESC, proof_key_thumbprint
96 + `,
97 + });
98 +
99 + const removeRows = SqlSchema.findAll({
100 + Request: ThumbprintInput,
101 + Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
102 + execute: ({ proofKeyThumbprint }) =>
103 + sql`
104 + DELETE FROM auth_connect_devices
105 + WHERE proof_key_thumbprint = ${proofKeyThumbprint}
106 + RETURNING proof_key_thumbprint AS "proofKeyThumbprint"
107 + `,
108 + });
109 +
110 + const removeAllExceptRows = SqlSchema.findAll({
111 + Request: RemoveAllExceptInput,
112 + Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
113 + execute: ({ keepProofKeyThumbprint }) =>
114 + sql`
115 + DELETE FROM auth_connect_devices
116 + WHERE proof_key_thumbprint IS NOT ${keepProofKeyThumbprint}
117 + RETURNING proof_key_thumbprint AS "proofKeyThumbprint"
118 + `,
119 + });
120 +
121 + const trust: AuthConnectDeviceRepository["Service"]["trust"] = (input) =>
122 + trustRow(input).pipe(Effect.mapError(sqlError("AuthConnectDeviceRepository.trust")));
123 +
124 + const isTrusted: AuthConnectDeviceRepository["Service"]["isTrusted"] = (proofKeyThumbprint) =>
125 + isTrustedRow({ proofKeyThumbprint }).pipe(
126 + NodeSqliteClient.readOnly,
127 + Effect.map((rows) => rows.length > 0),
128 + Effect.mapError(sqlError("AuthConnectDeviceRepository.isTrusted")),
129 + );
130 +
131 + const list: AuthConnectDeviceRepository["Service"]["list"] = () =>
132 + listRows(undefined).pipe(
133 + NodeSqliteClient.readOnly,
134 + Effect.mapError(sqlError("AuthConnectDeviceRepository.list")),
135 + );
136 +
137 + const remove: AuthConnectDeviceRepository["Service"]["remove"] = (proofKeyThumbprint) =>
138 + removeRows({ proofKeyThumbprint }).pipe(
139 + Effect.map((rows) => rows.length > 0),
140 + Effect.mapError(sqlError("AuthConnectDeviceRepository.remove")),
141 + );
142 +
143 + const removeAllExcept: AuthConnectDeviceRepository["Service"]["removeAllExcept"] = (
144 + keepProofKeyThumbprint,
145 + ) =>
146 + removeAllExceptRows({ keepProofKeyThumbprint }).pipe(
147 + Effect.map((rows) => rows.length),
148 + Effect.mapError(sqlError("AuthConnectDeviceRepository.removeAllExcept")),
149 + );
150 +
151 + return {
152 + trust,
153 + isTrusted,
154 + list,
155 + remove,
156 + removeAllExcept,
157 + } satisfies AuthConnectDeviceRepository["Service"];
158 +});
159 +
160 +export const layer = Layer.effect(AuthConnectDeviceRepository, make);
apps/server/src/persistence/AuthPairingLinks.ts
+233 -5
@@ -7,7 +7,7 @@ import * as Schema from "effect/Schema";
7 import * as SqlClient from "effect/sql/SqlClient";
8 import * as SqlSchema from "effect/sql/SqlSchema";
9
10 -import { AuthEnvironmentScopes } from "@t3tools/contracts";
10 +import { AuthClientMetadata, AuthEnvironmentScopes } from "@t3tools/contracts";
11
12 import {
13 type AuthPairingLinkRepositoryError,
@@ -22,6 +22,8 @@ import {
22 */
23 export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:";
24
25 +const SqliteFlag = Schema.Literals([0, 1]);
26 +
27 export const AuthPairingLinkRecord = Schema.Struct({
28 id: Schema.String,
29 credential: Schema.String,
@@ -34,6 +36,10 @@ export const AuthPairingLinkRecord = Schema.Struct({
36 expiresAt: Schema.DateTimeUtcFromString,
37 consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
38 revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
39 + /** Spendable only once `proofKeyThumbprint` is a trusted T3 Connect device. */
40 + requiresConnectApproval: SqliteFlag,
41 + connectApproved: SqliteFlag,
42 + requestedClient: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)),
43 });
44 export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;
45
@@ -45,6 +51,7 @@ export const CreateAuthPairingLinkInput = Schema.Struct({
51 subject: Schema.String,
52 label: Schema.NullOr(Schema.String),
53 proofKeyThumbprint: Schema.NullOr(Schema.String),
54 + requiresConnectApproval: Schema.optionalKey(Schema.Boolean),
55 createdAt: Schema.DateTimeUtcFromString,
56 expiresAt: Schema.DateTimeUtcFromString,
57 });
@@ -78,6 +85,32 @@ export const GetAuthPairingLinkByCredentialInput = Schema.Struct({
85 });
86 export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;
87
88 +export const GetActiveAuthPairingLinkByIdInput = Schema.Struct({
89 + id: Schema.String,
90 + now: Schema.DateTimeUtcFromString,
91 +});
92 +export type GetActiveAuthPairingLinkByIdInput = typeof GetActiveAuthPairingLinkByIdInput.Type;
93 +
94 +export const FindPendingConnectPairingLinkInput = Schema.Struct({
95 + proofKeyThumbprint: Schema.String,
96 + now: Schema.DateTimeUtcFromString,
97 +});
98 +export type FindPendingConnectPairingLinkInput = typeof FindPendingConnectPairingLinkInput.Type;
99 +
100 +/** Unspent links bound to `proofKeyThumbprint`, or with `keepProofKeyThumbprint` every other bound one. */
101 +export const RevokeUnspentByProofKeyInput = Schema.Struct({
102 + proofKeyThumbprint: Schema.NullOr(Schema.String),
103 + keepProofKeyThumbprint: Schema.NullOr(Schema.String),
104 + revokedAt: Schema.DateTimeUtcFromString,
105 +});
106 +export type RevokeUnspentByProofKeyInput = typeof RevokeUnspentByProofKeyInput.Type;
107 +
108 +export const RecordConnectRequestClientInput = Schema.Struct({
109 + id: Schema.String,
110 + client: Schema.fromJsonString(AuthClientMetadata),
111 +});
112 +export type RecordConnectRequestClientInput = typeof RecordConnectRequestClientInput.Type;
113 +
114 const AuthPairingLinkRawDbRow = Schema.Struct({
115 id: Schema.String,
116 credential: Schema.Unknown,
@@ -90,6 +123,9 @@ const AuthPairingLinkRawDbRow = Schema.Struct({
123 expiresAt: Schema.Unknown,
124 consumedAt: Schema.Unknown,
125 revokedAt: Schema.Unknown,
126 + requiresConnectApproval: Schema.Unknown,
127 + connectApproved: Schema.Unknown,
128 + requestedClient: Schema.Unknown,
129 });
130
131 const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);
@@ -112,6 +148,20 @@ export class AuthPairingLinkRepository extends Context.Service<
148 readonly getByCredential: (
149 input: GetAuthPairingLinkByCredentialInput,
150 ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
151 + readonly getActiveById: (
152 + input: GetActiveAuthPairingLinkByIdInput,
153 + ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
154 + /** The device's open or denied request, so its retries do not stack up or re-prompt. */
155 + readonly findPendingConnect: (
156 + input: FindPendingConnectPairingLinkInput,
157 + ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
158 + /** Keeps the first description a device gave, so it cannot be swapped while someone decides. */
159 + readonly recordConnectRequestClient: (
160 + input: RecordConnectRequestClientInput,
161 + ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;
162 + readonly revokeUnspentByProofKey: (
163 + input: RevokeUnspentByProofKeyInput,
164 + ) => Effect.Effect<ReadonlyArray<string>, AuthPairingLinkRepositoryError>;
165 }
166 >()("t3/persistence/AuthPairingLinks/AuthPairingLinkRepository") {}
167
@@ -146,6 +196,7 @@ export const make = Effect.gen(function* () {
196 subject,
197 label,
198 proof_key_thumbprint,
199 + requires_connect_approval,
200 created_at,
201 expires_at,
202 consumed_at,
@@ -159,6 +210,7 @@ export const make = Effect.gen(function* () {
210 ${input.subject},
211 ${input.label},
212 ${input.proofKeyThumbprint},
213 + ${input.requiresConnectApproval ? 1 : 0},
214 ${input.createdAt},
215 ${input.expiresAt},
216 NULL,
@@ -194,6 +246,10 @@ export const make = Effect.gen(function* () {
246 proof_key_thumbprint IS NULL
247 OR proof_key_thumbprint = ${proofKeyThumbprint}
248 )
249 + AND (
250 + requires_connect_approval = 0
251 + OR proof_key_thumbprint IN (SELECT proof_key_thumbprint FROM auth_connect_devices)
252 + )
253 AND (${requestedScopes === undefined ? 1 : 0} OR EXISTS (
254 SELECT 1
255 FROM json_each(${JSON.stringify(requestedScopes ?? [])}) AS requested
@@ -219,7 +275,13 @@ export const make = Effect.gen(function* () {
275 created_at AS "createdAt",
276 expires_at AS "expiresAt",
277 consumed_at AS "consumedAt",
222 - revoked_at AS "revokedAt"
278 + revoked_at AS "revokedAt",
279 + requires_connect_approval AS "requiresConnectApproval",
280 + EXISTS (
281 + SELECT 1 FROM auth_connect_devices
282 + WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
283 + ) AS "connectApproved",
284 + requested_client_json AS "requestedClient"
285 `,
286 });
287
@@ -239,7 +301,13 @@ export const make = Effect.gen(function* () {
301 created_at AS "createdAt",
302 expires_at AS "expiresAt",
303 consumed_at AS "consumedAt",
242 - revoked_at AS "revokedAt"
304 + revoked_at AS "revokedAt",
305 + requires_connect_approval AS "requiresConnectApproval",
306 + EXISTS (
307 + SELECT 1 FROM auth_connect_devices
308 + WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
309 + ) AS "connectApproved",
310 + requested_client_json AS "requestedClient"
311 FROM auth_pairing_links
312 WHERE revoked_at IS NULL
313 AND consumed_at IS NULL
@@ -254,7 +322,9 @@ export const make = Effect.gen(function* () {
322 execute: ({ id, revokedAt }) =>
323 sql`
324 UPDATE auth_pairing_links
257 - SET revoked_at = ${revokedAt}
325 + SET revoked_at = ${revokedAt},
326 + -- Revoking a waiting approval request is a denial; see findPendingConnect.
327 + connect_denied = requires_connect_approval
328 WHERE id = ${id}
329 AND revoked_at IS NULL
330 AND consumed_at IS NULL
@@ -278,12 +348,166 @@ export const make = Effect.gen(function* () {
348 created_at AS "createdAt",
349 expires_at AS "expiresAt",
350 consumed_at AS "consumedAt",
281 - revoked_at AS "revokedAt"
351 + revoked_at AS "revokedAt",
352 + requires_connect_approval AS "requiresConnectApproval",
353 + EXISTS (
354 + SELECT 1 FROM auth_connect_devices
355 + WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
356 + ) AS "connectApproved",
357 + requested_client_json AS "requestedClient"
358 FROM auth_pairing_links
359 WHERE credential = ${credential}
360 `,
361 });
362
363 + const selectRow = sql`
364 + SELECT
365 + id AS "id",
366 + credential AS "credential",
367 + method AS "method",
368 + scopes AS "scopes",
369 + subject AS "subject",
370 + label AS "label",
371 + proof_key_thumbprint AS "proofKeyThumbprint",
372 + created_at AS "createdAt",
373 + expires_at AS "expiresAt",
374 + consumed_at AS "consumedAt",
375 + revoked_at AS "revokedAt",
376 + requires_connect_approval AS "requiresConnectApproval",
377 + EXISTS (
378 + SELECT 1 FROM auth_connect_devices
379 + WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint
380 + ) AS "connectApproved",
381 + requested_client_json AS "requestedClient"
382 + FROM auth_pairing_links
383 + `;
384 +
385 + const getActivePairingLinkRowById = SqlSchema.findOneOption({
386 + Request: GetActiveAuthPairingLinkByIdInput,
387 + Result: AuthPairingLinkRawDbRow,
388 + execute: ({ id, now }) =>
389 + sql`
390 + ${selectRow}
391 + WHERE id = ${id}
392 + AND revoked_at IS NULL
393 + AND consumed_at IS NULL
394 + AND expires_at > ${now}
395 + `,
396 + });
397 +
398 + const findPendingConnectPairingLinkRow = SqlSchema.findOneOption({
399 + Request: FindPendingConnectPairingLinkInput,
400 + Result: AuthPairingLinkRawDbRow,
401 + execute: ({ proofKeyThumbprint, now }) =>
402 + sql`
403 + ${selectRow}
404 + WHERE proof_key_thumbprint = ${proofKeyThumbprint}
405 + AND requires_connect_approval = 1
406 + -- A denied request stays the device's answer until it expires, so retries get a
407 + -- dead credential back instead of prompting the approver again.
408 + AND (revoked_at IS NULL OR connect_denied = 1)
409 + AND consumed_at IS NULL
410 + AND expires_at > ${now}
411 + ORDER BY created_at DESC, id DESC
412 + LIMIT 1
413 + `,
414 + });
415 +
416 + const recordConnectRequestClientRow = SqlSchema.findAll({
417 + Request: RecordConnectRequestClientInput,
418 + Result: Schema.Struct({ id: Schema.String }),
419 + execute: ({ id, client }) =>
420 + sql`
421 + UPDATE auth_pairing_links
422 + SET requested_client_json = ${client}
423 + WHERE id = ${id}
424 + AND requires_connect_approval = 1
425 + AND requested_client_json IS NULL
426 + RETURNING id AS "id"
427 + `,
428 + });
429 +
430 + const decodeOptionalRow =
431 + (operation: string) => (rowOption: Option.Option<typeof AuthPairingLinkRawDbRow.Type>) =>
432 + Option.match(rowOption, {
433 + onNone: () => Effect.succeedNone,
434 + onSome: (row) =>
435 + decodeAuthPairingLinkDbRow(row).pipe(
436 + Effect.mapError((cause) =>
437 + PersistenceDecodeError.fromSchemaError(operation, cause, { pairingLinkId: row.id }),
438 + ),
439 + Effect.asSome,
440 + ),
441 + });
442 +
443 + const getActiveById: AuthPairingLinkRepository["Service"]["getActiveById"] = (input) =>
444 + getActivePairingLinkRowById(input).pipe(
445 + NodeSqliteClient.readOnly,
446 + Effect.mapError(
447 + toPersistenceSqlOrDecodeError(
448 + "AuthPairingLinkRepository.getActiveById:query",
449 + "AuthPairingLinkRepository.getActiveById:decodeRow",
450 + { pairingLinkId: input.id },
451 + ),
452 + ),
453 + Effect.flatMap(decodeOptionalRow("AuthPairingLinkRepository.getActiveById:decodeRow")),
454 + );
455 +
456 + const findPendingConnect: AuthPairingLinkRepository["Service"]["findPendingConnect"] = (input) =>
457 + findPendingConnectPairingLinkRow(input).pipe(
458 + NodeSqliteClient.readOnly,
459 + Effect.mapError(
460 + toPersistenceSqlOrDecodeError(
461 + "AuthPairingLinkRepository.findPendingConnect:query",
462 + "AuthPairingLinkRepository.findPendingConnect:decodeRow",
463 + ),
464 + ),
465 + Effect.flatMap(decodeOptionalRow("AuthPairingLinkRepository.findPendingConnect:decodeRow")),
466 + );
467 +
468 + const recordConnectRequestClient: AuthPairingLinkRepository["Service"]["recordConnectRequestClient"] =
469 + (input) =>
470 + recordConnectRequestClientRow(input).pipe(
471 + Effect.mapError(
472 + toPersistenceSqlOrDecodeError(
473 + "AuthPairingLinkRepository.recordConnectRequestClient:query",
474 + "AuthPairingLinkRepository.recordConnectRequestClient:encodeRequest",
475 + { pairingLinkId: input.id },
476 + ),
477 + ),
478 + Effect.map((rows) => rows.length > 0),
479 + );
480 +
481 + const revokeUnspentByProofKeyRows = SqlSchema.findAll({
482 + Request: RevokeUnspentByProofKeyInput,
483 + Result: Schema.Struct({ id: Schema.String }),
484 + execute: ({ proofKeyThumbprint, keepProofKeyThumbprint, revokedAt }) =>
485 + sql`
486 + -- Only T3 Connect mints bind a proof key, so these are that key's connect credentials.
487 + UPDATE auth_pairing_links
488 + SET revoked_at = ${revokedAt}
489 + WHERE proof_key_thumbprint IS NOT NULL
490 + AND revoked_at IS NULL
491 + AND consumed_at IS NULL
492 + AND (${proofKeyThumbprint} IS NULL OR proof_key_thumbprint = ${proofKeyThumbprint})
493 + AND proof_key_thumbprint IS NOT ${keepProofKeyThumbprint}
494 + RETURNING id AS "id"
495 + `,
496 + });
497 +
498 + const revokeUnspentByProofKey: AuthPairingLinkRepository["Service"]["revokeUnspentByProofKey"] = (
499 + input,
500 + ) =>
501 + revokeUnspentByProofKeyRows(input).pipe(
502 + Effect.mapError(
503 + toPersistenceSqlOrDecodeError(
504 + "AuthPairingLinkRepository.revokeUnspentByProofKey:query",
505 + "AuthPairingLinkRepository.revokeUnspentByProofKey:decodeRows",
506 + ),
507 + ),
508 + Effect.map((rows) => rows.map((row) => row.id)),
509 + );
510 +
511 const create: AuthPairingLinkRepository["Service"]["create"] = (input) =>
512 createPairingLinkRow(input).pipe(
513 Effect.mapError(
@@ -390,6 +614,10 @@ export const make = Effect.gen(function* () {
614 listActive,
615 revoke,
616 getByCredential,
617 + getActiveById,
618 + findPendingConnect,
619 + recordConnectRequestClient,
620 + revokeUnspentByProofKey,
621 } satisfies AuthPairingLinkRepository["Service"];
622 });
623
apps/server/src/persistence/AuthSessions.ts
+70 -2
@@ -52,6 +52,7 @@ export const CreateAuthSessionInput = Schema.Struct({
52 client: AuthSessionClientMetadataRecord,
53 issuedAt: Schema.DateTimeUtcFromString,
54 expiresAt: Schema.DateTimeUtcFromString,
55 + proofKeyThumbprint: Schema.optionalKey(Schema.String),
56 });
57 export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;
58
@@ -86,6 +87,12 @@ export const RevokeOtherAuthSessionsInput = Schema.Struct({
87 });
88 export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;
89
90 +export const RevokeAuthSessionsByProofKeyInput = Schema.Struct({
91 + proofKeyThumbprint: Schema.String,
92 + revokedAt: Schema.DateTimeUtcFromString,
93 +});
94 +export type RevokeAuthSessionsByProofKeyInput = typeof RevokeAuthSessionsByProofKeyInput.Type;
95 +
96 export const SetAuthSessionLastConnectedAtInput = Schema.Struct({
97 sessionId: AuthSessionId,
98 lastConnectedAt: Schema.DateTimeUtcFromString,
@@ -119,6 +126,12 @@ export class AuthSessionRepository extends Context.Service<
126 readonly setLastConnectedAt: (
127 input: SetAuthSessionLastConnectedAtInput,
128 ) => Effect.Effect<void, AuthSessionRepositoryError>;
129 + readonly getProofKeyThumbprint: (
130 + input: GetAuthSessionByIdInput,
131 + ) => Effect.Effect<Option.Option<string>, AuthSessionRepositoryError>;
132 + readonly revokeByProofKey: (
133 + input: RevokeAuthSessionsByProofKeyInput,
134 + ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
135 }
136 >()("t3/persistence/AuthSessions/AuthSessionRepository") {}
137
@@ -216,7 +229,8 @@ export const make = Effect.gen(function* () {
229 client_browser,
230 issued_at,
231 expires_at,
219 - revoked_at
232 + revoked_at,
233 + proof_key_thumbprint
234 )
235 VALUES (
236 ${input.sessionId},
@@ -231,7 +245,8 @@ export const make = Effect.gen(function* () {
245 ${input.client.browser},
246 ${input.issuedAt},
247 ${input.expiresAt},
234 - NULL
248 + NULL,
249 + ${input.proofKeyThumbprint ?? null}
250 )
251 ${ignoreExisting ? sql`ON CONFLICT(session_id) DO NOTHING` : sql``}
252 `,
@@ -334,6 +349,31 @@ export const make = Effect.gen(function* () {
349 `,
350 });
351
352 + const proofKeyThumbprintRows = SqlSchema.findAll({
353 + Request: GetAuthSessionByIdInput,
354 + Result: Schema.Struct({ proofKeyThumbprint: Schema.String }),
355 + execute: ({ sessionId }) =>
356 + sql`
357 + SELECT proof_key_thumbprint AS "proofKeyThumbprint"
358 + FROM auth_sessions
359 + WHERE session_id = ${sessionId}
360 + AND proof_key_thumbprint IS NOT NULL
361 + `,
362 + });
363 +
364 + const revokeByProofKeyRows = SqlSchema.findAll({
365 + Request: RevokeAuthSessionsByProofKeyInput,
366 + Result: Schema.Struct({ sessionId: AuthSessionId }),
367 + execute: ({ proofKeyThumbprint, revokedAt }) =>
368 + sql`
369 + UPDATE auth_sessions
370 + SET revoked_at = ${revokedAt}
371 + WHERE proof_key_thumbprint = ${proofKeyThumbprint}
372 + AND revoked_at IS NULL
373 + RETURNING session_id AS "sessionId"
374 + `,
375 + });
376 +
377 const revokeOtherSessionRows = SqlSchema.findAll({
378 Request: RevokeOtherAuthSessionsInput,
379 Result: Schema.Struct({ sessionId: AuthSessionId }),
@@ -480,6 +520,32 @@ export const make = Effect.gen(function* () {
520 ),
521 );
522
523 + const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = (
524 + input,
525 + ) =>
526 + proofKeyThumbprintRows(input).pipe(
527 + NodeSqliteClient.readOnly,
528 + Effect.mapError(
529 + toPersistenceSqlOrDecodeError(
530 + "AuthSessionRepository.getProofKeyThumbprint:query",
531 + "AuthSessionRepository.getProofKeyThumbprint:decodeRows",
532 + { sessionId: input.sessionId },
533 + ),
534 + ),
535 + Effect.map((rows) => Option.fromNullishOr(rows[0]?.proofKeyThumbprint)),
536 + );
537 +
538 + const revokeByProofKey: AuthSessionRepository["Service"]["revokeByProofKey"] = (input) =>
539 + revokeByProofKeyRows(input).pipe(
540 + Effect.mapError(
541 + toPersistenceSqlOrDecodeError(
542 + "AuthSessionRepository.revokeByProofKey:query",
543 + "AuthSessionRepository.revokeByProofKey:decodeRows",
544 + ),
545 + ),
546 + Effect.map((rows) => rows.map((row) => row.sessionId)),
547 + );
548 +
549 return {
550 create,
551 createReplacingActive,
@@ -489,6 +555,8 @@ export const make = Effect.gen(function* () {
555 revoke,
556 revokeAllExcept,
557 setLastConnectedAt,
558 + getProofKeyThumbprint,
559 + revokeByProofKey,
560 } satisfies AuthSessionRepository["Service"];
561 });
562
apps/server/src/persistence/Migrations.ts
+4
@@ -97,6 +97,8 @@ import Migration0086 from "./Migrations/086_QueuedTurnInputIndex.ts";
97 import Migration0087 from "./Migrations/087_ProjectionProjectsCustomTitle.ts";
98 import Migration0088 from "./Migrations/088_TurnItemTypeStatusIndex.ts";
99 import Migration0089 from "./Migrations/089_ShellThreadReadIndexes.ts";
100 +import Migration0090 from "./Migrations/090_AuthConnectDevices.ts";
101 +import Migration0091 from "./Migrations/091_AuthConnectDeniedRequests.ts";
102
103 const migrationEntries = [
104 [1, "OrchestrationEvents", Migration0001],
@@ -189,6 +191,8 @@ const migrationEntries = [
191 [87, "ProjectionProjectsCustomTitle", Migration0087],
192 [88, "TurnItemTypeStatusIndex", Migration0088],
193 [89, "ShellThreadReadIndexes", Migration0089],
194 + [90, "AuthConnectDevices", Migration0090],
195 + [91, "AuthConnectDeniedRequests", Migration0091],
196 ] as const;
197
198 export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/090_AuthConnectDevices.ts new
+40
@@ -0,0 +1,40 @@
1 +import * as Effect from "effect/Effect";
2 +import * as SqlClient from "effect/sql/SqlClient";
3 +
4 +export default Effect.gen(function* () {
5 + const sql = yield* SqlClient.SqlClient;
6 +
7 + const pairingLinkColumns = yield* sql<{ readonly name: string }>`
8 + PRAGMA table_info(auth_pairing_links)
9 + `;
10 + if (!pairingLinkColumns.some((column) => column.name === "requires_connect_approval")) {
11 + yield* sql`
12 + ALTER TABLE auth_pairing_links
13 + ADD COLUMN requires_connect_approval INTEGER NOT NULL DEFAULT 0
14 + `;
15 + }
16 + if (!pairingLinkColumns.some((column) => column.name === "requested_client_json")) {
17 + yield* sql`
18 + ALTER TABLE auth_pairing_links
19 + ADD COLUMN requested_client_json TEXT
20 + `;
21 + }
22 +
23 + const sessionColumns = yield* sql<{ readonly name: string }>`
24 + PRAGMA table_info(auth_sessions)
25 + `;
26 + if (!sessionColumns.some((column) => column.name === "proof_key_thumbprint")) {
27 + yield* sql`
28 + ALTER TABLE auth_sessions
29 + ADD COLUMN proof_key_thumbprint TEXT
30 + `;
31 + }
32 +
33 + yield* sql`
34 + CREATE TABLE IF NOT EXISTS auth_connect_devices (
35 + proof_key_thumbprint TEXT PRIMARY KEY,
36 + client_json TEXT,
37 + approved_at TEXT NOT NULL
38 + )
39 + `;
40 +});
apps/server/src/persistence/Migrations/091_AuthConnectDeniedRequests.ts new
+16
@@ -0,0 +1,16 @@
1 +import * as Effect from "effect/Effect";
2 +import * as SqlClient from "effect/sql/SqlClient";
3 +
4 +export default Effect.gen(function* () {
5 + const sql = yield* SqlClient.SqlClient;
6 +
7 + const pairingLinkColumns = yield* sql<{ readonly name: string }>`
8 + PRAGMA table_info(auth_pairing_links)
9 + `;
10 + if (!pairingLinkColumns.some((column) => column.name === "connect_denied")) {
11 + yield* sql`
12 + ALTER TABLE auth_pairing_links
13 + ADD COLUMN connect_denied INTEGER NOT NULL DEFAULT 0
14 + `;
15 + }
16 +});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+4
@@ -69,6 +69,8 @@ describe("V2 preview upgrade", () => {
69 [87, "ProjectionProjectsCustomTitle"],
70 [88, "TurnItemTypeStatusIndex"],
71 [89, "ShellThreadReadIndexes"],
72 + [90, "AuthConnectDevices"],
73 + [91, "AuthConnectDeniedRequests"],
74 ]);
75 assert.deepStrictEqual(yield* runMigrations(), []);
76 assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -181,6 +183,8 @@ describe("V2 preview upgrade", () => {
183 [87, "ProjectionProjectsCustomTitle"],
184 [88, "TurnItemTypeStatusIndex"],
185 [89, "ShellThreadReadIndexes"],
186 + [90, "AuthConnectDevices"],
187 + [91, "AuthConnectDeniedRequests"],
188 ]);
189 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
190 );
apps/server/src/ws.test.ts
+13
@@ -1203,6 +1203,7 @@ it.effect("access changes made while the snapshot loads reach the client after i
1203 Layer.mock(ServerEnvironment.ServerEnvironment)({}),
1204 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
1205 listPairingLinks: () => Effect.succeed([]),
1206 + listConnectDevices: () => Effect.succeed([]),
1207 // Another client revokes a session after the snapshot read it.
1208 listClientSessions: () =>
1209 PubSub.publish(sessionChanges, {
@@ -1246,6 +1247,18 @@ it.effect("access changes made while the snapshot loads reach the client after i
1247 type: "clientRemoved",
1248 payload: { sessionId: revokedElsewhere },
1249 });
1250 + yield* server.write(0, { _tag: "Ack", requestId });
1251 + assert.equal((yield* Queue.take(responses)).type, "pairingLinkRemoved");
1252 + yield* server.write(0, { _tag: "Ack", requestId });
1253 +
1254 + // Device trust has no incremental event, so a change re-sends the whole snapshot.
1255 + yield* PubSub.publish(pairingChanges, { type: "connectDevicesChanged" });
1256 + assert.deepEqual(yield* Queue.take(responses), {
1257 + version: 1,
1258 + revision: 4,
1259 + type: "snapshot",
1260 + payload: { pairingLinks: [], clientSessions: [], connectDevices: [] },
1261 + });
1262 yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });
1263 }).pipe(
1264 Effect.provide(
apps/server/src/ws.ts
+25 -10
@@ -727,7 +727,10 @@ const serverWsRpcs = Array.from(ServerWsRpcGroup.requests.values());
727 const SplitWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isSplitWsRpc));
728 const OtherWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isOtherWsRpc));
729 function toAuthAccessStreamEvent(
730 - change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
730 + change: Exclude<
731 + PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
732 + { readonly type: "connectDevicesChanged" }
733 + >,
734 revision: number,
735 currentSessionId: AuthSessionId,
736 ): AuthAccessStreamEvent {
@@ -1780,6 +1783,7 @@ export const layerWsRpc = (
1783 Effect.all({
1784 pairingLinks: serverAuth.listPairingLinks(),
1785 clientSessions: serverAuth.listClientSessions(currentSessionId),
1786 + connectDevices: serverAuth.listConnectDevices(),
1787 }).pipe(
1788 Effect.mapError(
1789 (error) =>
@@ -3473,17 +3477,28 @@ export const layerWsRpc = (
3477 const initialSnapshot = yield* loadAuthAccessSnapshot();
3478 const revisionRef = yield* Ref.make(1);
3479
3476 - const liveEvents: Stream.Stream<AuthAccessStreamEvent> = Stream.fromQueue(
3477 - liveBuffer,
3478 - ).pipe(
3479 - Stream.mapEffect((change) =>
3480 - Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
3481 - Effect.map((revision) =>
3482 - toAuthAccessStreamEvent(change, revision, currentSessionId),
3480 + const liveEvents: Stream.Stream<AuthAccessStreamEvent, AuthAccessStreamError> =
3481 + Stream.fromQueue(liveBuffer).pipe(
3482 + Stream.mapEffect((change) =>
3483 + Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
3484 + Effect.flatMap((revision) =>
3485 + // Device trust has no incremental event older clients could decode.
3486 + change.type === "connectDevicesChanged"
3487 + ? loadAuthAccessSnapshot().pipe(
3488 + Effect.map((payload): AuthAccessStreamEvent => ({
3489 + version: 1,
3490 + revision,
3491 + type: "snapshot",
3492 + payload,
3493 + })),
3494 + )
3495 + : Effect.succeed(
3496 + toAuthAccessStreamEvent(change, revision, currentSessionId),
3497 + ),
3498 + ),
3499 ),
3500 ),
3485 - ),
3486 - );
3501 + );
3502
3503 return Stream.concat(
3504 rpcInitialItems([
apps/web/src/components/ConnectDeviceApprovalCoordinator.tsx new
+178
@@ -0,0 +1,178 @@
1 +import { useNavigate } from "@tanstack/react-router";
2 +import {
3 + type AtomCommandResult,
4 + isAtomCommandInterrupted,
5 + squashAtomCommandFailure,
6 +} from "@t3tools/client-runtime/state/runtime";
7 +import { AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts";
8 +import * as DateTime from "effect/DateTime";
9 +import { useEffect, useRef, useState } from "react";
10 +
11 +import { authEnvironment } from "../state/auth";
12 +import { useEnvironments } from "../state/environments";
13 +import { useEnvironmentQuery } from "../state/query";
14 +import { useEnvironmentScope } from "../state/session";
15 +import { useAtomCommand } from "../state/use-atom-command";
16 +import { describeConnectDeviceClient } from "./settings/ConnectionsSettings.logic";
17 +import { toastManager } from "./ui/toast";
18 +import { stackedThreadToast } from "./ui/toastHelpers";
19 +
20 +/** Asks whoever can approve to look at T3 Connect devices waiting on an environment. */
21 +export function ConnectDeviceApprovalCoordinator() {
22 + const { environments } = useEnvironments();
23 + return environments.map((environment) =>
24 + environment.connection.phase === "connected" &&
25 + environment.serverConfig?.settings.requireConnectDeviceApproval === true ? (
26 + <EnvironmentConnectDeviceRequests
27 + key={environment.environmentId}
28 + environmentId={environment.environmentId}
29 + environmentLabel={environment.label}
30 + />
31 + ) : null,
32 + );
33 +}
34 +
35 +function EnvironmentConnectDeviceRequests(props: {
36 + readonly environmentId: EnvironmentId;
37 + readonly environmentLabel: string;
38 +}) {
39 + const canApprove = useEnvironmentScope(props.environmentId, AuthAccessWriteScope);
40 + return canApprove ? <ConnectDeviceRequestToasts {...props} /> : null;
41 +}
42 +
43 +/** Reports a failed command and says whether it failed, so its request can be offered again. */
44 +async function reportFailure(
45 + title: string,
46 + action: () => Promise<AtomCommandResult<unknown, unknown>>,
47 +): Promise<boolean> {
48 + const result = await action();
49 + if (result._tag !== "Failure") return false;
50 + if (!isAtomCommandInterrupted(result)) {
51 + const error = squashAtomCommandFailure(result);
52 + toastManager.add(
53 + stackedThreadToast({
54 + type: "error",
55 + title,
56 + description: error instanceof Error ? error.message : "An error occurred.",
57 + }),
58 + );
59 + }
60 + return true;
61 +}
62 +
63 +function ConnectDeviceRequestToasts({
64 + environmentId,
65 + environmentLabel,
66 +}: {
67 + readonly environmentId: EnvironmentId;
68 + readonly environmentLabel: string;
69 +}) {
70 + const navigate = useNavigate();
71 + const access = useEnvironmentQuery(authEnvironment.accessChanges({ environmentId, input: null }));
72 + const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });
73 + const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });
74 + const toasts = useRef(new Map<string, { toastId: string; renderedKey: string }>());
75 + const [, setRetryGeneration] = useState(0);
76 + // A failed approve or deny forgets its toast and re-renders, so the request is offered again.
77 + const settle = async (id: string, failed: Promise<boolean>) => {
78 + if (!(await failed)) return;
79 + toasts.current.delete(id);
80 + setRetryGeneration((generation) => generation + 1);
81 + };
82 +
83 + const requests =
84 + access.data?.type === "snapshot"
85 + ? access.data.payload.pairingLinks.flatMap((link) =>
86 + link.connectDeviceRequest
87 + ? [{ id: link.id, request: link.connectDeviceRequest, expiresAt: link.expiresAt }]
88 + : [],
89 + )
90 + : null;
91 +
92 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens, updates and closes imperative toastManager toasts to match the pending requests
93 + useEffect(() => {
94 + if (requests === null) return;
95 + // The server publishes no event when a request expires, so the toast ends itself then.
96 + const now = Date.now();
97 + const live = requests.flatMap((entry) => {
98 + const remainingMs = DateTime.toEpochMillis(entry.expiresAt) - now;
99 + return remainingMs > 0 ? [{ ...entry, remainingMs }] : [];
100 + });
101 + const pendingIds = new Set(live.map(({ id }) => id));
102 + for (const [id, tracked] of toasts.current) {
103 + if (pendingIds.has(id)) continue;
104 + toastManager.close(tracked.toastId);
105 + toasts.current.delete(id);
106 + }
107 + for (const { id, request, remainingMs } of live) {
108 + const device = describeConnectDeviceClient(request);
109 + const renderedKey = `${request.verificationCode}:${device}`;
110 + const tracked = toasts.current.get(id);
111 + if (tracked?.renderedKey === renderedKey) continue;
112 + const close = () => {
113 + const current = toasts.current.get(id);
114 + if (current) toastManager.close(current.toastId);
115 + };
116 + const options = stackedThreadToast({
117 + type: "info",
118 + title: `A device wants to connect to ${environmentLabel}`,
119 + description: `${device}. Approve only if it shows code ${request.verificationCode}.`,
120 + timeout: remainingMs,
121 + actionProps: {
122 + children: "Approve",
123 + onClick: () => {
124 + close();
125 + void settle(
126 + id,
127 + reportFailure("Could not approve the device", () =>
128 + approve({ environmentId, input: { pairingLinkId: id } }),
129 + ),
130 + );
131 + },
132 + },
133 + data: {
134 + hideCopyButton: true,
135 + secondaryActionProps: {
136 + children: "Deny",
137 + onClick: () => {
138 + close();
139 + void settle(
140 + id,
141 + reportFailure("Could not deny the device", () =>
142 + deny({ environmentId, input: { id } }),
143 + ),
144 + );
145 + },
146 + },
147 + additionalActions: [
148 + {
149 + id: "review",
150 + props: {
151 + children: "Review",
152 + onClick: () =>
153 + void navigate({ to: "/settings/access", search: { machine: environmentId } }),
154 + },
155 + },
156 + ],
157 + },
158 + });
159 + if (tracked) {
160 + toastManager.update(tracked.toastId, options);
161 + toasts.current.set(id, { toastId: tracked.toastId, renderedKey });
162 + } else {
163 + toasts.current.set(id, { toastId: toastManager.add(options), renderedKey });
164 + }
165 + }
166 + });
167 +
168 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes this environment's imperative toasts when it stops needing approval
169 + useEffect(() => {
170 + const tracked = toasts.current;
171 + return () => {
172 + for (const { toastId } of tracked.values()) toastManager.close(toastId);
173 + tracked.clear();
174 + };
175 + }, []);
176 +
177 + return null;
178 +}
apps/web/src/components/chat/useSystemComposerBanners.tsx
+10 -3
@@ -177,8 +177,11 @@ export function useSystemComposerBanners(input: SystemComposerBannersInput) {
177 unavailableConnection !== null &&
178 (unavailableConnection.phase === "connecting" ||
179 unavailableConnection.phase === "reconnecting");
180 + const awaitingApproval = unavailableConnection?.awaitingApproval === true;
181 const suppressUnavailableBanner =
181 - environmentReconnecting && (updateRunning || !reconnectWarningGraceElapsed);
182 + environmentReconnecting &&
183 + !awaitingApproval &&
184 + (updateRunning || !reconnectWarningGraceElapsed);
185 const showUnavailableBanner =
186 activeEnvironmentUnavailableState !== null &&
187 unavailableConnection !== null &&
@@ -189,8 +192,12 @@ export function useSystemComposerBanners(input: SystemComposerBannersInput) {
192 variant: unavailableConnection.phase === "error" ? "error" : "warning",
193 group: "environment",
194 icon: <WifiOffIcon />,
192 - title: `${activeEnvironmentUnavailableState.label} is ${environmentReconnecting ? "reconnecting" : "offline"}`,
193 - description: activeEnvironment ? (
195 + title: awaitingApproval
196 + ? `${activeEnvironmentUnavailableState.label} is waiting to approve this device`
197 + : `${activeEnvironmentUnavailableState.label} is ${environmentReconnecting ? "reconnecting" : "offline"}`,
198 + description: awaitingApproval ? (
199 + (unavailableConnection.error ?? undefined)
200 + ) : activeEnvironment ? (
201 <ConnectionDiagnosisHeadline environment={activeEnvironment} />
202 ) : undefined,
203 actions: (
apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx
+3 -1
@@ -460,7 +460,9 @@ export function CloudEnvironmentConnectRows({
460 className={cn(
461 "mt-1 truncate text-xs",
462 savedConnection?.tone === "error" ||
463 - (savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||
463 + (savedConnection?.tone === "connecting" &&
464 + savedEnvironment?.connection.error &&
465 + !savedEnvironment.connection.awaitingApproval) ||
466 (savedConnection === null && availability === "error")
467 ? "text-destructive"
468 : "text-muted-foreground",
apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+42
@@ -1,6 +1,7 @@
1 import { useAuth } from "@clerk/react";
2 import { useAtomValue } from "@effect/atom-react";
3 import {
4 + AuthAccessWriteScope,
5 AuthRelayReadScope,
6 AuthRelayWriteScope,
7 type AuthSessionState,
@@ -18,6 +19,7 @@ import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
19 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
20 import { useCloudLinkController } from "~/cloud/useCloudLinkController";
21 import { useLocalStorage } from "~/hooks/useLocalStorage";
22 +import { useUpdatePrimarySettings } from "~/hooks/useSettings";
23 import { isHostedStaticApp } from "~/hostedPairing";
24 import {
25 useEnvironments,
@@ -74,6 +76,10 @@ function ConfiguredConnectOnboardingDialog() {
76 const connectAllowed =
77 managedCapabilityDenial(usePrimaryManagedPolicy(), "connect") === undefined;
78 const canManageRelay = canReadRelay && canWriteRelay && connectAllowed;
79 + const canRequireDeviceApproval = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);
80 + const deviceApprovalRequired =
81 + usePrimaryEnvironment()?.serverConfig?.settings.requireConnectDeviceApproval === true;
82 + const updatePrimarySettings = useUpdatePrimarySettings();
83 const sessionScopesKnown =
84 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
85
@@ -89,6 +95,7 @@ function ConfiguredConnectOnboardingDialog() {
95 const [step, setStep] = useState<OnboardingStep>("devices");
96 const [exposeEnvironment, setExposeEnvironment] = useState(true);
97 const [publishAgentActivity, setPublishAgentActivity] = useState(true);
98 + const [requireDeviceApproval, setRequireDeviceApproval] = useState(false);
99 const [dontShowAgain, setDontShowAgain] = useState(false);
100 const [isApplying, setIsApplying] = useState(false);
101 const [prefilledFromLinkState, setPrefilledFromLinkState] = useState(false);
@@ -131,6 +138,7 @@ function ConfiguredConnectOnboardingDialog() {
138 setPrefilledFromLinkState(false);
139 setExposeEnvironment(true);
140 setPublishAgentActivity(true);
141 + setRequireDeviceApproval(false);
142 setDontShowAgain(false);
143 setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
144 setOpenForAccount(requestedAccount);
@@ -165,6 +173,19 @@ function ConfiguredConnectOnboardingDialog() {
173
174 const applyPublishSelection = async () => {
175 if (isApplying) return;
176 + // Onboarding only turns approval on; turning it off stays in Settings. Publishing waits
177 + // for the save, so a failed save cannot leave the machine reachable without approval.
178 + if (requireDeviceApproval && !deviceApprovalRequired) {
179 + setIsApplying(true);
180 + const saved = await new Promise<boolean>((resolve) =>
181 + updatePrimarySettings(
182 + { requireConnectDeviceApproval: true },
183 + { onSaved: () => resolve(true), onFailed: () => resolve(false) },
184 + ),
185 + );
186 + setIsApplying(false);
187 + if (!saved) return;
188 + }
189 if (
190 primaryEnvironmentId === null ||
191 !readEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope) ||
@@ -246,6 +267,11 @@ function ConfiguredConnectOnboardingDialog() {
267 <PublishStep
268 exposeEnvironment={exposeEnvironment}
269 publishAgentActivity={publishAgentActivity}
270 + requireDeviceApproval={
271 + canRequireDeviceApproval ? requireDeviceApproval || deviceApprovalRequired : null
272 + }
273 + requireDeviceApprovalLocked={deviceApprovalRequired}
274 + onRequireDeviceApprovalChange={setRequireDeviceApproval}
275 disabled={isApplying || !canManageRelay || linkStateData === null}
276 operationError={controller.operationError ?? controller.linkState.error}
277 tunnelLimit={controller.tunnelLimit}
@@ -315,6 +341,9 @@ const STEP_LABELS: Record<OnboardingStep, string> = {
341 function PublishStep({
342 exposeEnvironment,
343 publishAgentActivity,
344 + requireDeviceApproval,
345 + requireDeviceApprovalLocked,
346 + onRequireDeviceApprovalChange,
347 disabled,
348 operationError,
349 tunnelLimit,
@@ -324,6 +353,10 @@ function PublishStep({
353 }: {
354 readonly exposeEnvironment: boolean;
355 readonly publishAgentActivity: boolean;
356 + /** Null when this session cannot change who may connect. */
357 + readonly requireDeviceApproval: boolean | null;
358 + readonly requireDeviceApprovalLocked: boolean;
359 + readonly onRequireDeviceApprovalChange: (enabled: boolean) => void;
360 readonly disabled: boolean;
361 readonly operationError: string | null;
362 readonly tunnelLimit: number | null;
@@ -348,6 +381,15 @@ function PublishStep({
381 disabled={disabled}
382 onCheckedChange={onPublishAgentActivityChange}
383 />
384 + {requireDeviceApproval !== null ? (
385 + <OnboardingToggleRow
386 + title="Require approval for new devices"
387 + description="Devices that sign in to your T3 Connect account wait until someone already connected here approves them."
388 + checked={requireDeviceApproval}
389 + disabled={disabled || requireDeviceApprovalLocked}
390 + onCheckedChange={onRequireDeviceApprovalChange}
391 + />
392 + ) : null}
393 </div>
394 {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
395 {tunnelLimit !== null ? (
apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.ts
+1 -1
@@ -27,7 +27,7 @@ export function presentSavedCloudEnvironmentConnection(
27 };
28 case "reconnecting":
29 return {
30 - buttonLabel: "Reconnecting…",
30 + buttonLabel: connection.awaitingApproval ? "Waiting for approval…" : "Reconnecting…",
31 statusText: connectionStatusText(connection),
32 tone: "connecting",
33 };
apps/web/src/components/settings/ConnectDeviceApprovalSettings.tsx new
+163
@@ -0,0 +1,163 @@
1 +import type { AuthConnectDevice, EnvironmentId } from "@t3tools/contracts";
2 +import {
3 + isAtomCommandInterrupted,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import * as DateTime from "effect/DateTime";
7 +import { useState } from "react";
8 +
9 +import type { ServerPairingLinkRecord } from "~/environments/primary";
10 +import { authEnvironment } from "~/state/auth";
11 +import { useAtomCommand } from "~/state/use-atom-command";
12 +import { Button } from "../ui/button";
13 +import { stackedThreadToast, toastManager } from "../ui/toast";
14 +import {
15 + connectDeviceName,
16 + describeConnectDeviceClient,
17 + formatAccessTimestamp,
18 +} from "./ConnectionsSettings.logic";
19 +import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
20 +import { SettingsSection } from "./settingsLayout";
21 +
22 +function reportFailure(title: string, result: Parameters<typeof isAtomCommandInterrupted>[0]) {
23 + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
24 + const error = squashAtomCommandFailure(result);
25 + toastManager.add(
26 + stackedThreadToast({
27 + type: "error",
28 + title,
29 + description: error instanceof Error ? error.message : "An error occurred.",
30 + }),
31 + );
32 +}
33 +
34 +export function ConnectDeviceApprovalSettings({
35 + environmentId,
36 + requests,
37 + devices,
38 + canWrite,
39 + requestRevoke,
40 +}: {
41 + readonly environmentId: EnvironmentId;
42 + readonly requests: ReadonlyArray<ServerPairingLinkRecord>;
43 + readonly devices: ReadonlyArray<AuthConnectDevice>;
44 + readonly canWrite: boolean;
45 + /** Revokes now, or first asks to turn approval on when it is off. */
46 + readonly requestRevoke: (title: string, revoke: () => Promise<void>) => void;
47 +}) {
48 + const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });
49 + const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });
50 + const revoke = useAtomCommand(authEnvironment.revokeConnectDevice, { reportFailure: false });
51 + const [busyId, setBusyId] = useState<string | null>(null);
52 +
53 + const run = async (id: string, action: () => Promise<void>) => {
54 + setBusyId(id);
55 + await action();
56 + setBusyId(null);
57 + };
58 +
59 + return (
60 + <SettingsSection id="connect-devices" title="T3 Connect devices">
61 + {requests.map((request) => {
62 + const connectRequest = request.connectDeviceRequest;
63 + if (!connectRequest) return null;
64 + const busy = busyId === request.id;
65 + return (
66 + <div key={request.id} className={ITEM_ROW_CLASSNAME}>
67 + <div className={ITEM_ROW_INNER_CLASSNAME}>
68 + <div className="min-w-0 flex-1 space-y-1">
69 + <p className="text-sm font-medium text-foreground">
70 + Waiting for approval ·{" "}
71 + <span className="font-mono tabular-nums">{connectRequest.verificationCode}</span>
72 + </p>
73 + <p className="text-xs text-muted-foreground">
74 + {describeConnectDeviceClient(connectRequest)}. Approve only if the device in front
75 + of you shows this code.
76 + </p>
77 + </div>
78 + <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
79 + <Button
80 + size="xs"
81 + variant="destructive-outline"
82 + disabled={!canWrite || busy}
83 + onClick={() =>
84 + void run(request.id, async () =>
85 + reportFailure(
86 + "Could not deny the device",
87 + await deny({ environmentId, input: { id: request.id } }),
88 + ),
89 + )
90 + }
91 + >
92 + Deny
93 + </Button>
94 + <Button
95 + size="xs"
96 + disabled={!canWrite || busy}
97 + onClick={() =>
98 + void run(request.id, async () =>
99 + reportFailure(
100 + "Could not approve the device",
101 + await approve({ environmentId, input: { pairingLinkId: request.id } }),
102 + ),
103 + )
104 + }
105 + >
106 + {busy ? "Saving…" : "Approve"}
107 + </Button>
108 + </div>
109 + </div>
110 + </div>
111 + );
112 + })}
113 + {devices.map((device) => {
114 + const busy = busyId === device.proofKeyThumbprint;
115 + return (
116 + <div key={device.proofKeyThumbprint} className={ITEM_ROW_CLASSNAME}>
117 + <div className={ITEM_ROW_INNER_CLASSNAME}>
118 + <div className="min-w-0 flex-1 space-y-1">
119 + <p className="text-sm font-medium text-foreground">
120 + {describeConnectDeviceClient(device)}
121 + </p>
122 + <p className="text-xs text-muted-foreground">
123 + <span className="font-mono tabular-nums">{device.verificationCode}</span>
124 + <span aria-hidden> · </span>
125 + Trusted since {formatAccessTimestamp(DateTime.formatIso(device.approvedAt))}
126 + </p>
127 + </div>
128 + <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
129 + <Button
130 + size="xs"
131 + variant="destructive-outline"
132 + disabled={!canWrite || busy}
133 + onClick={() =>
134 + requestRevoke(`Revoke ${connectDeviceName(device)}?`, () =>
135 + run(device.proofKeyThumbprint, async () =>
136 + reportFailure(
137 + "Could not revoke the device",
138 + await revoke({
139 + environmentId,
140 + input: { proofKeyThumbprint: device.proofKeyThumbprint },
141 + }),
142 + ),
143 + ),
144 + )
145 + }
146 + >
147 + {busy ? "Revoking…" : "Revoke"}
148 + </Button>
149 + </div>
150 + </div>
151 + </div>
152 + );
153 + })}
154 + {devices.length === 0 && requests.length === 0 ? (
155 + <div className={ITEM_ROW_CLASSNAME}>
156 + <p className="text-xs text-muted-foreground/60">
157 + No device has connected through T3 Connect yet.
158 + </p>
159 + </div>
160 + ) : null}
161 + </SettingsSection>
162 + );
163 +}
apps/web/src/components/settings/ConnectionsSettings.logic.ts
+22
@@ -9,6 +9,7 @@ import {
9 } from "~/environments/primary";
10 import {
11 type AdvertisedEndpoint,
12 + type AuthClientMetadata,
13 type AuthClientSession,
14 type AuthGrantScope,
15 type AuthPairingLink,
@@ -467,3 +468,24 @@ export function resolveAccessEnvironmentId(input: {
468 ?.environmentId ?? null
469 );
470 }
471 +
472 +/** A short name for a T3 Connect device: its label, or what it runs on. */
473 +export function connectDeviceName({
474 + client,
475 +}: {
476 + readonly client?: AuthClientMetadata | undefined;
477 +}): string {
478 + return client?.label ?? client?.os ?? client?.browser ?? "this device";
479 +}
480 +
481 +/** How a T3 Connect device describes itself. It can say anything, so the code is what to trust. */
482 +export function describeConnectDeviceClient({
483 + client,
484 +}: {
485 + readonly client?: AuthClientMetadata | undefined;
486 +}): string {
487 + const bits = [client?.label, client?.os, client?.browser, client?.ipAddress].filter(
488 + (value): value is string => typeof value === "string" && value.length > 0,
489 + );
490 + return bits.length > 0 ? [...new Set(bits)].join(" · ") : "Unknown device";
491 +}
apps/web/src/components/settings/ConnectionsSettings.tsx
+87 -3
@@ -29,6 +29,7 @@ import * as Cause from "effect/Cause";
29 import { isLocalEnvironmentDisabled } from "../../localEnvironment";
30 import {
31 applyWslEnableSelection,
32 + connectDeviceName,
33 isWslSettingsRowVisible,
34 missingTailscaleEndpointDescription,
35 resolveLocalVersionStatusLabel,
@@ -40,6 +41,7 @@ import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsL
41 import { ManagedByOrganization } from "../ManagedPolicy";
42 import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
43 import { searchableSetting } from "./settingsSearch";
44 +import { ConnectDeviceApprovalSettings } from "./ConnectDeviceApprovalSettings";
45 import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
46 import { FoldedSettingsSection } from "./FoldedSettingsSection";
47 import { LinkedEnvironmentsSettings } from "./LinkedEnvironmentsSettings";
@@ -106,6 +108,7 @@ import {
108 usePrimaryEnvironment,
109 } from "~/state/environments";
110 import { requestConfirmDialog } from "~/confirmDialog";
111 +import { useUpdateEnvironmentSettings } from "~/hooks/useSettings";
112 import { useAtomCommand } from "../../state/use-atom-command";
113 import { environmentIdsKey } from "~/state/environmentAtomList";
114 import { environmentUpdateStatesAtom, serverEnvironment } from "~/state/server";
@@ -139,7 +142,13 @@ import {
142 SavedBackendListRow,
143 } from "./SavedEnvironmentRows";
144 import { AddEnvironmentDialog } from "./AddEnvironmentDialog";
145 +import {
146 + type ConnectDeviceRevokeRequest,
147 + RevokeConnectDeviceDialog,
148 +} from "./RevokeConnectDeviceDialog";
149
150 +// Sessions T3 Connect minted for a device signed in to the linked account.
151 +const CLOUD_CONNECT_SESSION_SUBJECT = "cloud-connect";
152 const DEFAULT_TAILSCALE_SERVE_PORT = 443;
153 const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
154
@@ -706,7 +715,58 @@ function ConnectionsSettingsContent({
715 if (confirmed === true) await removeSavedBackend(environment);
716 };
717
709 - const visibleDesktopPairingLinks = desktopPairingLinks;
718 + // T3 Connect devices waiting for approval have their own list.
719 + const visibleDesktopPairingLinks = desktopPairingLinks.filter(
720 + (pairingLink) => pairingLink.connectDeviceRequest === undefined,
721 + );
722 + const connectDeviceRequests = desktopPairingLinks.filter(
723 + (pairingLink) => pairingLink.connectDeviceRequest !== undefined,
724 + );
725 + // Older servers omit the list; they cannot hold devices for approval.
726 + const connectDevices =
727 + authAccessChanges.data?.type === "snapshot"
728 + ? (authAccessChanges.data.payload.connectDevices ?? null)
729 + : null;
730 + const updateAccessSettings = useUpdateEnvironmentSettings(accessEnvironmentId);
731 + const [pendingConnectRevoke, setPendingConnectRevoke] =
732 + useState<ConnectDeviceRevokeRequest | null>(null);
733 + // With approval off a revoked T3 Connect device signs straight back in, so offer to turn it
734 + // on. Older servers have no such setting, and revoking there goes ahead as before.
735 + const connectApprovalOff =
736 + accessEnvironment?.serverConfig?.settings.requireConnectDeviceApproval === false;
737 + const requestConnectRevoke = (title: string, revoke: () => Promise<void>) => {
738 + if (connectApprovalOff && canWriteAccess) setPendingConnectRevoke({ title, revoke });
739 + else void revoke();
740 + };
741 + const requireConnectApproval = () =>
742 + new Promise<boolean>((resolve) =>
743 + updateAccessSettings(
744 + { requireConnectDeviceApproval: true },
745 + { onSaved: () => resolve(true), onFailed: () => resolve(false) },
746 + ),
747 + );
748 + const requestRevokeClientSession = (sessionId: ServerClientSessionRecord["sessionId"]) => {
749 + const session = desktopClientSessions.find((candidate) => candidate.sessionId === sessionId);
750 + if (session?.subject === CLOUD_CONNECT_SESSION_SUBJECT) {
751 + requestConnectRevoke(`Revoke ${connectDeviceName(session)}?`, () =>
752 + handleRevokeDesktopClientSession(sessionId),
753 + );
754 + } else {
755 + void handleRevokeDesktopClientSession(sessionId);
756 + }
757 + };
758 + const requestRevokeOtherClients = () => {
759 + const revokesConnectDevices =
760 + (connectDevices?.length ?? 0) > 0 ||
761 + desktopClientSessions.some(
762 + (session) => !session.current && session.subject === CLOUD_CONNECT_SESSION_SUBJECT,
763 + );
764 + if (revokesConnectDevices) {
765 + requestConnectRevoke("Revoke all other clients?", handleRevokeOtherDesktopClients);
766 + } else {
767 + void handleRevokeOtherDesktopClients();
768 + }
769 + };
770 const tailscaleHttpsEndpoint = desktopAdvertisedEndpoints.find(isTailscaleHttpsEndpoint) ?? null;
771 const visibleDesktopNetworkAdvertisedEndpoints = isLocalBackendNetworkAccessible
772 ? desktopAdvertisedEndpoints.filter((endpoint) => !isTailscaleHttpsEndpoint(endpoint))
@@ -1049,7 +1109,7 @@ function ConnectionsSettingsContent({
1109 revokingPairingLinkId={revokingDesktopPairingLinkId}
1110 revokingClientSessionId={revokingDesktopClientSessionId}
1111 onRevokePairingLink={handleRevokeDesktopPairingLink}
1052 - onRevokeClientSession={handleRevokeDesktopClientSession}
1112 + onRevokeClientSession={requestRevokeClientSession}
1113 canRevoke={canWriteAccess}
1114 />
1115 );
@@ -1241,6 +1301,14 @@ function ConnectionsSettingsContent({
1301 environmentId={accessEnvironmentId}
1302 canReadRelay={canReadRelay}
1303 canManageRelay={canManageRelay}
1304 + connectDeviceApproval={
1305 + accessServerConfig?.settings.requireConnectDeviceApproval === undefined
1306 + ? null
1307 + : {
1308 + required: accessServerConfig.settings.requireConnectDeviceApproval,
1309 + canManage: canWriteAccess,
1310 + }
1311 + }
1312 />
1313 ) : null}
1314 {accessEnvironment ? (
@@ -1287,7 +1355,7 @@ function ConnectionsSettingsContent({
1355 : null
1356 }
1357 isRevokingOtherClients={isRevokingOtherDesktopClients}
1290 - onRevokeOtherClients={handleRevokeOtherDesktopClients}
1358 + onRevokeOtherClients={requestRevokeOtherClients}
1359 />
1360 ) : undefined
1361 }
@@ -1308,6 +1376,22 @@ function ConnectionsSettingsContent({
1376 </ScrollArea>
1377 </FoldedSettingsSection>
1378 ) : null}
1379 + {canReadAccess &&
1380 + connectDevices !== null &&
1381 + (connectDeviceRequests.length > 0 || connectDevices.length > 0) ? (
1382 + <ConnectDeviceApprovalSettings
1383 + environmentId={accessEnvironmentId}
1384 + requests={connectDeviceRequests}
1385 + devices={connectDevices}
1386 + canWrite={canWriteAccess}
1387 + requestRevoke={requestConnectRevoke}
1388 + />
1389 + ) : null}
1390 + <RevokeConnectDeviceDialog
1391 + request={pendingConnectRevoke}
1392 + onClose={() => setPendingConnectRevoke(null)}
1393 + requireApproval={requireConnectApproval}
1394 + />
1395 <AlertDialog
1396 open={pendingDesktopServerExposureMode !== null && canManageLocalBackend}
1397 onOpenChange={(open) => {
apps/web/src/components/settings/RevokeConnectDeviceDialog.tsx new
+114
@@ -0,0 +1,114 @@
1 +import { useState } from "react";
2 +
3 +import {
4 + AlertDialog,
5 + AlertDialogClose,
6 + AlertDialogDescription,
7 + AlertDialogFooter,
8 + AlertDialogHeader,
9 + AlertDialogPopup,
10 + AlertDialogTitle,
11 +} from "../ui/alert-dialog";
12 +import { Button } from "../ui/button";
13 +import { Checkbox } from "../ui/checkbox";
14 +import { Spinner } from "../ui/spinner";
15 +
16 +export interface ConnectDeviceRevokeRequest {
17 + readonly title: string;
18 + /** Revokes the device; resolves once the attempt finished, failed or not. */
19 + readonly revoke: () => Promise<void>;
20 +}
21 +
22 +/**
23 + * With approval off, a revoked T3 Connect device signs straight back in, so revoking offers to
24 + * turn approval on first.
25 + */
26 +export function RevokeConnectDeviceDialog({
27 + request,
28 + onClose,
29 + requireApproval,
30 +}: {
31 + readonly request: ConnectDeviceRevokeRequest | null;
32 + readonly onClose: () => void;
33 + /** Saves the setting; resolves false when the save failed. */
34 + readonly requireApproval: () => Promise<boolean>;
35 +}) {
36 + return (
37 + <AlertDialog
38 + open={request !== null}
39 + onOpenChange={(open) => {
40 + if (!open) onClose();
41 + }}
42 + >
43 + {request ? (
44 + <RevokeConnectDeviceDialogPopup
45 + key={request.title}
46 + request={request}
47 + onClose={onClose}
48 + requireApproval={requireApproval}
49 + />
50 + ) : null}
51 + </AlertDialog>
52 + );
53 +}
54 +
55 +function RevokeConnectDeviceDialogPopup({
56 + request,
57 + onClose,
58 + requireApproval,
59 +}: {
60 + readonly request: ConnectDeviceRevokeRequest;
61 + readonly onClose: () => void;
62 + readonly requireApproval: () => Promise<boolean>;
63 +}) {
64 + const [turnOnApproval, setTurnOnApproval] = useState(true);
65 + const [busy, setBusy] = useState(false);
66 +
67 + const confirm = async () => {
68 + setBusy(true);
69 + if (turnOnApproval && !(await requireApproval())) {
70 + setBusy(false);
71 + return;
72 + }
73 + await request.revoke();
74 + setBusy(false);
75 + onClose();
76 + };
77 +
78 + return (
79 + <AlertDialogPopup>
80 + <AlertDialogHeader>
81 + <AlertDialogTitle>{request.title}</AlertDialogTitle>
82 + <AlertDialogDescription>
83 + Approval for new devices is off, so a revoked device signed in to your T3 Connect account
84 + can connect again on its own.
85 + </AlertDialogDescription>
86 + <label className="mt-2 flex cursor-pointer items-start gap-3">
87 + <Checkbox
88 + className="mt-0.5"
89 + checked={turnOnApproval}
90 + disabled={busy}
91 + onCheckedChange={(checked) => setTurnOnApproval(checked === true)}
92 + />
93 + <span className="min-w-0">
94 + <span className="block text-sm font-medium text-foreground">
95 + Require approval for new devices
96 + </span>
97 + <span className="block text-xs text-muted-foreground">
98 + The device has to be approved here before it can connect again.
99 + </span>
100 + </span>
101 + </label>
102 + </AlertDialogHeader>
103 + <AlertDialogFooter>
104 + <AlertDialogClose disabled={busy} render={<Button variant="outline" disabled={busy} />}>
105 + Cancel
106 + </AlertDialogClose>
107 + <Button variant="destructive" disabled={busy} onClick={() => void confirm()}>
108 + {busy && <Spinner size="sm" />}
109 + Revoke
110 + </Button>
111 + </AlertDialogFooter>
112 + </AlertDialogPopup>
113 + );
114 +}
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+44 -1
@@ -60,6 +60,7 @@ import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/st
60 import { APP_VERSION } from "~/branding";
61 import { useManagedPolicy } from "~/state/managedPolicy";
62 import { useAtomCommand } from "../../state/use-atom-command";
63 +import { useUpdateEnvironmentSettings } from "~/hooks/useSettings";
64 import { serverEnvironment } from "~/state/server";
65 import {
66 OutdatedServerUpdateAction,
@@ -90,6 +91,9 @@ function savedBackendStatus(environment: EnvironmentPresentation): {
91 case "connecting":
92 return { text: "Connecting", tone: "muted" };
93 case "reconnecting":
94 + if (connection.awaitingApproval) {
95 + return { text: connection.error ?? "Waiting for approval", tone: "muted" };
96 + }
97 return {
98 text: connection.error ? `Reconnecting: ${connection.error}` : "Reconnecting",
99 tone: "error",
@@ -522,10 +526,13 @@ function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number |
526 function ConfiguredCloudLinkRow({
527 environmentId,
528 canManageRelay,
529 + connectDeviceApproval,
530 }: {
531 readonly environmentId: EnvironmentId;
532 readonly canManageRelay: boolean;
533 + readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
534 }) {
535 + const updateEnvironmentSettings = useUpdateEnvironmentSettings(environmentId);
536 const {
537 isSignedIn,
538 linkState: cloudLinkState,
@@ -743,18 +750,48 @@ function ConfiguredCloudLinkRow({
750 }
751 />
752 ) : null}
753 + {managedTunnelActive && connectDeviceApproval ? (
754 + <SettingsRow
755 + title={searchableSetting("connect-device-approval").title}
756 + description="Devices that sign in to your T3 Connect account wait until someone already connected here approves them."
757 + managed={connectDenial}
758 + control={
759 + <CloudLinkSwitch
760 + ariaLabel="Require approval for new T3 Connect devices"
761 + checked={connectDeviceApproval.required}
762 + disabled={!connectDeviceApproval.canManage}
763 + disabledReason={
764 + connectDeviceApproval.canManage
765 + ? null
766 + : "Your session does not have permission to manage access."
767 + }
768 + onCheckedChange={(enabled) =>
769 + updateEnvironmentSettings({ requireConnectDeviceApproval: enabled })
770 + }
771 + />
772 + }
773 + />
774 + ) : null}
775 </>
776 );
777 }
778
779 +/** Older servers have no device approval, so callers pass null and the row stays hidden. */
780 +export interface ConnectDeviceApprovalControl {
781 + readonly required: boolean;
782 + readonly canManage: boolean;
783 +}
784 +
785 export function CloudLinkRow({
786 environmentId,
787 canReadRelay,
788 canManageRelay,
789 + connectDeviceApproval,
790 }: {
791 readonly environmentId: EnvironmentId;
792 readonly canReadRelay: boolean;
793 readonly canManageRelay: boolean;
794 + readonly connectDeviceApproval: ConnectDeviceApprovalControl | null;
795 }) {
796 if (!hasCloudPublicConfig()) return null;
797 if (!canReadRelay) {
@@ -765,7 +802,13 @@ export function CloudLinkRow({
802 />
803 );
804 }
768 - return <ConfiguredCloudLinkRow environmentId={environmentId} canManageRelay={canManageRelay} />;
805 + return (
806 + <ConfiguredCloudLinkRow
807 + environmentId={environmentId}
808 + canManageRelay={canManageRelay}
809 + connectDeviceApproval={connectDeviceApproval}
810 + />
811 + );
812 }
813
814 function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
apps/web/src/components/settings/settingsSearch.ts
+9
@@ -1282,6 +1282,15 @@ export const SETTINGS_SEARCH_ITEMS = [
1282 desktopOnly: true,
1283 cloudOnly: true,
1284 },
1285 + {
1286 + id: "connect-device-approval",
1287 + title: "Require approval for new devices",
1288 + to: "/settings/access",
1289 + targetId: "connections-environment",
1290 + searchTerms: ["t3 connect devices approve deny trust revoke pairing code security account"],
1291 + cloudOnly: true,
1292 + managedTunnelOnly: true,
1293 + },
1294 {
1295 id: "hold-webhooks-while-offline",
1296 localEnvironmentOnly: true,
apps/web/src/environments/primary/auth.ts
+3
@@ -1,6 +1,7 @@
1 import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 + AuthConnectDeviceRequest,
5 AuthEnvironmentScope,
6 ServerAuthSessionMethod,
7 AuthSessionId,
@@ -110,6 +111,7 @@ export interface ServerPairingLinkRecord {
111 readonly label?: string;
112 readonly createdAt: string;
113 readonly expiresAt: string;
114 + readonly connectDeviceRequest?: AuthConnectDeviceRequest;
115 }
116
117 export interface ServerClientSessionRecord {
@@ -204,6 +206,7 @@ function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType):
206 return 401;
207 case "EnvironmentScopeRequiredError":
208 case "EnvironmentOperationForbiddenError":
209 + case "EnvironmentConnectApprovalPendingError":
210 return 403;
211 case "EnvironmentResourceNotFoundError":
212 return 404;
apps/web/src/routes/__root.tsx
+2
@@ -32,6 +32,7 @@ import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkC
32 import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
33 import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
34 import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
35 +import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator";
36 import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
37 import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
38 import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
@@ -192,6 +193,7 @@ function RootRouteBranch() {
193 <CustomSnoozeDialogHost />
194 <GuestShareDialogHost />
195 <ProjectCloneToastCoordinator />
196 + <ConnectDeviceApprovalCoordinator />
197 <AddProjectToMachineDialogHost />
198 <UseInAnotherAppDialogHost />
199 {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
apps/web/test/environmentHttpTest.ts
+3 -1
@@ -116,7 +116,9 @@ export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestSc
116 )
117 .handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink"))
118 .handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient"))
119 - .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")),
119 + .handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients"))
120 + .handle("approveConnectDevice", () => unexpectedEndpoint("auth.approveConnectDevice"))
121 + .handle("revokeConnectDevice", () => unexpectedEndpoint("auth.revokeConnectDevice")),
122 ),
123 ]),
124 Effect.provideService(EnvironmentAuthenticatedAuth, authenticatedAuth),
docs/internals/t3-connect.md
+18
@@ -64,6 +64,24 @@ The relay holds the signing authority for mint requests. DPoP protects an honest
64 exchange from credential reuse; it does not make a compromised relay signing
65 key harmless. Keep that trust assumption explicit when changing the protocol.
66
67 +Device approval, off by default, limits what that authority buys. With
68 +`requireConnectDeviceApproval` on, the environment trusts T3 Connect device
69 +keys, meaning DPoP thumbprints, and not the relay. A mint for an untrusted key
70 +still succeeds, so the relay protocol does not change. The credential it returns
71 +cannot be spent until someone with `access:write` on the environment approves
72 +that key, so a forged mint yields a request that waits for approval, never a
73 +session. The waiting device retries the whole mint, and the environment hands
74 +back the same open request, so approvers see one entry with a stable code
75 +derived from the thumbprint. Approval is per key and does not expire. It ends
76 +only when the key is revoked. Revoking a session bound to a key revokes the key,
77 +all its sessions, and its unspent credentials, unless the caller's own session
78 +holds the same key; otherwise the device would mint itself a new session within
79 +seconds. While approval is off, every key that completes an
80 +exchange is recorded as trusted. Turning approval on therefore keeps current
81 +devices working and lists them for review, including any that got in before.
82 +See `issueConnectCredential` in the
83 +[environment auth service](../../apps/server/src/auth/EnvironmentAuth.ts).
84 +
85 Managed tunnels expose only a validated loopback HTTP origin. Link proof checks
86 reject forwarded authority headers, and the relay resolves endpoints from its
87 own managed allocations rather than a caller-supplied URL. Health and mint
docs/user/remote-access.md
+25
@@ -38,6 +38,31 @@ connection. Pull request diffs and provider settings keep working after the
38 previous credential expires. A failed renewal affects that request; it does not
39 disconnect an otherwise healthy conversation.
40
41 +### Approve new devices
42 +
43 +By default, any device signed in to your T3 Connect account can open a linked
44 +machine. To require approval instead, turn on **Require approval for new
45 +devices** with the T3 Connect settings in **Settings → Sharing & access** on the
46 +host, or when you first set up T3 Connect. Then someone who takes over your T3
47 +Connect account cannot reach the machine from a new device without your
48 +approval. Review the devices that are already approved, described below.
49 +
50 +A new device waits and shows a code such as `K7QM-2XFD`. Approve it from a
51 +device that is already connected, using the prompt or **Settings → Sharing &
52 +access**. Check that the code matches the one on the waiting device. On a
53 +headless host, run `t3 auth connect-device list` and then
54 +`t3 auth connect-device approve K7QM-2XFD`. A request expires after 10 minutes,
55 +and the device asks again when it retries. Deny keeps that device out until its
56 +request expires.
57 +
58 +Each device is approved once. Revoke it from **T3 Connect devices** in the same
59 +settings page, or with `t3 auth connect-device revoke <code>`. With approval on,
60 +it has to ask again. With approval off, it can connect again on its own, so
61 +revoking in the app offers to turn approval on first. Devices that connected through T3 Connect while approval was off stay
62 +approved and appear in that list for you to review. A device that has not
63 +connected since you updated T3 Code asks for approval like a new one. Older apps
64 +cannot show the code, so update them before you turn approval on.
65 +
66 ### Scripts and agents
67
68 `t3 up` asks nothing when you name a choice: `--connect`, `--lan`, or their
docs/user/t3-connect-troubleshooting.md
+11 -7
@@ -118,6 +118,10 @@ an active link between your account and the host.
118 - **This device is still loading its T3 Connect sign-in.** Wait a moment;
119 T3 Code retries on its own. If it keeps waiting, reload or restart T3 Code on
120 this device.
121 +- **The host is waiting for you to approve this device.** The host requires
122 + approval for new devices. Approve the code this device shows from a device
123 + that is already connected, or run `t3 auth connect-device approve <code>` on
124 + the host. See [Approve new devices](./remote-access.md#approve-new-devices).
125 - **Your account reached its tunnel limit.** Remove an environment you do not
126 use from your T3 account's T3 Connect page, or
127 [link a paid T3 Chat account](./remote-access.md#more-machines-with-t3-chat)
@@ -136,13 +140,13 @@ This app needs a newer T3 Code on the host. Update T3 Code on the host. See
140
141 ## T3 Connect returned an error
142
139 -| Error | Fix |
140 -| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
141 -| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment or link a paid T3 Chat account, then restart T3 Code on the host. |
142 -| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. |
143 -| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. |
144 -| HTTP 403 without a recognized error | Check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. |
145 -| HTTP 408, 429, or 5xx | Wait a few minutes. T3 Code retries temporary failures on its own. |
143 +| Error | Fix |
144 +| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
145 +| `environment_link_limit_exceeded` or managed tunnel limit | Remove an unused environment or link a paid T3 Chat account, then restart T3 Code on the host. |
146 +| `auth_invalid` or `invalid_bearer` | Run `t3 connect login`. If credentials were revoked, run `t3 connect logout`, then `t3 connect` again. Restart the server after signing in. |
147 +| Expired or invalid link proof | Check the host's date and time, update T3 Code, then restart it. |
148 +| HTTP 403 without a recognized error | If the host requires approval for new devices, update T3 Code on this device and approve it. Otherwise check relay access, proxies, and firewall rules. Keep any Cloudflare Ray ID for a bug report. |
149 +| HTTP 408, 429, or 5xx | Wait a few minutes. T3 Code retries temporary failures on its own. |
150
151 After you fix a permanent rejection, restart the host's server with
152 `t3 service restart`. For a foreground server, stop it and run `t3 serve` again.
packages/client-runtime/src/authorization/service.ts
+19 -1
@@ -1,4 +1,5 @@
1 import {
2 + connectDeviceVerificationCode,
3 type ClientConnectionMethod,
4 EnvironmentId,
5 type ExecutionEnvironmentDescriptor,
@@ -121,6 +122,19 @@ function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemp
122 : mapRemoteDpopEnvironmentError(error);
123 }
124
125 +function approvalPendingError(hostLabel: string, thumbprint: string, traceId: string) {
126 + const verificationCode = connectDeviceVerificationCode(thumbprint);
127 + return new ConnectionTransientError({
128 + reason: "approval-pending",
129 + detail: `Approve this device on ${hostLabel}. It shows code ${verificationCode}.`,
130 + verificationCode,
131 + traceId,
132 + hop: "server",
133 + via: "relay",
134 + failureCause: "approval_pending",
135 + });
136 +}
137 +
138 const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (
139 httpBaseUrl: string,
140 connectionMethod: ClientConnectionMethod,
@@ -367,7 +381,11 @@ export const make = Effect.gen(function* () {
381 dpopProof: bootstrapProof,
382 clientMetadata: presentation.metadata,
383 }).pipe(
370 - Effect.mapError(mapRemoteDpopEnvironmentError),
384 + Effect.mapError((error) =>
385 + error._tag === "EnvironmentConnectApprovalPendingError"
386 + ? approvalPendingError(descriptor.label, thumbprint, error.traceId)
387 + : mapRemoteDpopEnvironmentError(error),
388 + ),
389 Effect.provideService(HttpClient.HttpClient, httpClient),
390 Effect.withSpan("environment.authorization.accessToken.exchange"),
391 );
packages/client-runtime/src/connection/diagnosis.test.ts
+17
@@ -146,6 +146,23 @@ describe("presentConnectionDiagnosis", () => {
146 );
147 });
148
149 + it("asks for approval on the host instead of reporting it unreachable", () => {
150 + const diagnosis = diagnose(
151 + backoff(
152 + new ConnectionTransientError({
153 + reason: "approval-pending",
154 + detail: "Approve this device on Mac mini. It shows code K7QM-2XFD.",
155 + verificationCode: "K7QM-2XFD",
156 + hop: "server",
157 + via: "relay",
158 + failureCause: "approval_pending",
159 + }),
160 + ),
161 + );
162 + expect(diagnosis?.headline).toBe("Mac mini is waiting for someone to approve this device");
163 + expect(diagnosis?.steps.join(" ")).toContain("t3 auth connect-device approve K7QM-2XFD");
164 + });
165 +
166 it("does not report hops as working when the failure names none", () => {
167 const failure = new ConnectionBlockedError({
168 reason: "authentication",
packages/client-runtime/src/connection/diagnosis.ts
+12
@@ -101,6 +101,8 @@ function headline(host: string, located: Located, failure: ConnectionAttemptErro
101 return "This device is offline";
102 case "session_pending":
103 return "This device is still loading its T3 Connect sign-in";
104 + case "approval_pending":
105 + return `${host} is waiting for someone to approve this device`;
106 case "outdated":
107 return `${host} runs an older T3 Code`;
108 case "clock_skew":
@@ -163,6 +165,15 @@ function steps(host: string, located: Located, failure: ConnectionAttemptError |
165 "Wait a moment. T3 Code retries on its own.",
166 "If it keeps waiting, reload or restart T3 Code on this device.",
167 ];
168 + case "approval_pending": {
169 + const code =
170 + failure?._tag === "ConnectionTransientError" ? failure.verificationCode : undefined;
171 + const approve = code ? `approve the device showing ${code}` : "approve this device";
172 + return [
173 + `On a device already connected to ${host}, open Settings > Sharing & access and ${approve}.`,
174 + `Or run \`t3 auth connect-device approve ${code ?? "<code>"}\` on ${host}.`,
175 + ];
176 + }
177 case "outdated":
178 return [`Update T3 Code on ${host}.`];
179 case "clock_skew":
@@ -243,6 +254,7 @@ function helpSection(
254 case "clock_skew":
255 return "the-clock-is-off";
256 case "session_pending":
257 + case "approval_pending":
258 case "not_linked":
259 case "tunnel_not_enabled":
260 return "sign-in-account-or-link-problems";
packages/client-runtime/src/connection/errors.ts
+9
@@ -235,6 +235,15 @@ export function mapRemoteEnvironmentError(
235 hop: unreachableHop,
236 via,
237 });
238 + case "EnvironmentConnectApprovalPendingError":
239 + return new ConnectionTransientError({
240 + reason: "approval-pending",
241 + detail: "This device is waiting for approval on the host.",
242 + traceId: error.traceId,
243 + hop: "server",
244 + via,
245 + failureCause: "approval_pending",
246 + });
247 case "EnvironmentInternalError":
248 return new ConnectionTransientError({
249 reason: "remote-unavailable",
packages/client-runtime/src/connection/model.ts
+4
@@ -64,6 +64,7 @@ export const ConnectionTransientReason = Schema.Literals([
64 "relay-unavailable",
65 "remote-unavailable",
66 "session-pending",
67 + "approval-pending",
68 ]);
69 export type ConnectionTransientReason = typeof ConnectionTransientReason.Type;
70
@@ -87,6 +88,7 @@ export const ConnectionFailureCause = Schema.Literals([
88 "relay_error",
89 "tunnel_pending",
90 "tunnel_not_enabled",
91 + "approval_pending",
92 ]);
93 export type ConnectionFailureCause = typeof ConnectionFailureCause.Type;
94
@@ -108,6 +110,8 @@ export class ConnectionTransientError extends Schema.TaggedError<ConnectionTrans
110 reason: ConnectionTransientReason,
111 detail: Schema.String,
112 traceId: Schema.optionalKey(Schema.String),
113 + /** The code this device shows while the host decides whether to trust it. */
114 + verificationCode: Schema.optionalKey(Schema.String),
115 ...ConnectionFailureFields,
116 },
117 ) {
packages/client-runtime/src/connection/presentation.test.ts
+28 -1
@@ -13,7 +13,12 @@ import {
13 RelayConnectionTarget,
14 type SupervisorConnectionState,
15 } from "./model.ts";
16 -import { environmentMcpUrl, presentConnectionState } from "./presentation.ts";
16 +import {
17 + connectionStatusText,
18 + connectionStatusTitle,
19 + environmentMcpUrl,
20 + presentConnectionState,
21 +} from "./presentation.ts";
22
23 const TARGET = new BearerConnectionTarget({
24 environmentId: EnvironmentId.make("environment-1"),
@@ -155,6 +160,28 @@ describe("connection presentation", () => {
160 error: "Disconnected.",
161 traceId: "trace-1",
162 });
163 + const awaitingApproval = presentConnectionState(
164 + supervisorState({
165 + phase: "backoff",
166 + attempt: 1,
167 + retryAt: 1,
168 + lastFailure: new ConnectionTransientError({
169 + reason: "approval-pending",
170 + detail: "Approve this device on Mac mini. It shows code K7QM-2XFD.",
171 + traceId: "trace-2",
172 + }),
173 + }),
174 + );
175 + expect(awaitingApproval).toEqual({
176 + phase: "reconnecting",
177 + error: "Approve this device on Mac mini. It shows code K7QM-2XFD.",
178 + traceId: "trace-2",
179 + awaitingApproval: true,
180 + });
181 + expect(connectionStatusText(awaitingApproval)).toBe(
182 + "Approve this device on Mac mini. It shows code K7QM-2XFD.",
183 + );
184 + expect(connectionStatusTitle(awaitingApproval)).toBe("Waiting for approval");
185 });
186
187 it("preserves an explicitly available environment while offline", () => {
packages/client-runtime/src/connection/presentation.ts
+22
@@ -18,6 +18,11 @@ export interface EnvironmentConnectionPresentation {
18 readonly phase: EnvironmentConnectionPhase;
19 readonly error: string | null;
20 readonly traceId: string | null;
21 + /**
22 + * Set while reconnecting because the host has not approved this device yet. `error` then
23 + * says where to approve it and shows the code, and is not a failure.
24 + */
25 + readonly awaitingApproval?: true;
26 }
27
28 /**
@@ -36,6 +41,17 @@ export interface EnvironmentPresentation {
41 export function presentConnectionState(
42 state: SupervisorConnectionState,
43 ): EnvironmentConnectionPresentation {
44 + if (
45 + (state.phase === "connecting" || state.phase === "backoff") &&
46 + state.lastFailure?.reason === "approval-pending"
47 + ) {
48 + return {
49 + phase: "reconnecting",
50 + error: state.lastFailure.message,
51 + traceId: state.lastFailure.traceId ?? null,
52 + awaitingApproval: true,
53 + };
54 + }
55 switch (state.phase) {
56 case "available":
57 return { phase: "available", error: null, traceId: null };
@@ -73,6 +89,9 @@ export function connectionStatusText(connection: EnvironmentConnectionPresentati
89 case "connecting":
90 return "Connecting...";
91 case "reconnecting":
92 + if (connection.awaitingApproval) {
93 + return connection.error ?? "Waiting for approval on the host";
94 + }
95 return connection.error
96 ? `Failed to connect. Reconnecting... Reason: ${connection.error}`
97 : "Reconnecting...";
@@ -88,6 +107,9 @@ export function connectionStatusText(connection: EnvironmentConnectionPresentati
107 }
108
109 export function connectionStatusTitle(connection: EnvironmentConnectionPresentation): string {
110 + if (connection.awaitingApproval) {
111 + return "Waiting for approval";
112 + }
113 if (connection.phase === "reconnecting" && connection.error) {
114 return "Failed to connect. Reconnecting...";
115 }
packages/client-runtime/src/connection/supervisor.test.ts
+60
@@ -15,6 +15,7 @@ import * as Random from "effect/Random";
15 import * as Ref from "effect/Ref";
16 import * as Stream from "effect/Stream";
17 import * as SubscriptionRef from "effect/SubscriptionRef";
18 +import * as Clock from "effect/Clock";
19 import * as TestClock from "effect/testing/TestClock";
20
21 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
@@ -442,6 +443,65 @@ describe("EnvironmentSupervisor", () => {
443 }).pipe(Effect.provide(TestClock.layer())),
444 );
445
446 + it.effect("checks back on a pending approval every few seconds instead of backing off", () =>
447 + Effect.gen(function* () {
448 + const pending = new ConnectionTransientError({
449 + reason: "approval-pending",
450 + detail: "Approve this device on Mac mini. It shows code K7QM-2XFD.",
451 + });
452 + const harness = yield* makeHarness({
453 + prepare: (attempt) =>
454 + Effect.fail(attempt <= 8 ? pending : transient("Relay connection timed out.")),
455 + });
456 + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
457 + initiallyDesired: true,
458 + }).pipe(Effect.provide(harness.dependencies));
459 +
460 + for (let attempt = 1; attempt <= 8; attempt++) {
461 + const waiting = yield* awaitState(
462 + supervisor.state,
463 + (state) => state.phase === "backoff" && state.attempt === attempt,
464 + );
465 + expect((waiting.retryAt ?? 0) - (yield* Clock.currentTimeMillis)).toBe(4_000);
466 + yield* TestClock.adjust("4 seconds");
467 + }
468 + // The waits do not count toward backoff, so an outage right after starts at the bottom.
469 + const failed = yield* awaitState(
470 + supervisor.state,
471 + (state) => state.phase === "backoff" && state.attempt === 9,
472 + );
473 + expect((failed.retryAt ?? 0) - (yield* Clock.currentTimeMillis)).toBeLessThanOrEqual(2_000);
474 + }).pipe(Effect.provide(TestClock.layer())),
475 + );
476 +
477 + it.effect("backs off a device nobody approved once its request has expired", () =>
478 + Effect.gen(function* () {
479 + const pending = new ConnectionTransientError({
480 + reason: "approval-pending",
481 + detail: "Approve this device on Mac mini. It shows code K7QM-2XFD.",
482 + });
483 + const harness = yield* makeHarness({ prepare: () => Effect.fail(pending) });
484 + const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
485 + initiallyDesired: true,
486 + }).pipe(Effect.provide(harness.dependencies));
487 +
488 + const delays: number[] = [];
489 + for (let attempt = 1; attempt <= 156; attempt++) {
490 + const waiting = yield* awaitState(
491 + supervisor.state,
492 + (state) => state.phase === "backoff" && state.attempt === attempt,
493 + );
494 + const delay = (waiting.retryAt ?? 0) - (yield* Clock.currentTimeMillis);
495 + delays.push(delay);
496 + yield* TestClock.adjust(delay);
497 + }
498 + // Ten minutes of 4 s checks, then backoff that never polls faster than that.
499 + expect(delays.slice(0, 150).every((delay) => delay === 4_000)).toBe(true);
500 + expect(delays.slice(150).every((delay) => delay >= 4_000)).toBe(true);
501 + expect(delays.at(-1)).toBeGreaterThanOrEqual(32_000);
502 + }).pipe(Effect.provide(TestClock.layer())),
503 + );
504 +
505 it.effect("converts unexpected driver defects into retryable failures", () =>
506 Effect.gen(function* () {
507 const harness = yield* makeHarness({
packages/client-runtime/src/connection/supervisor.ts
+25 -3
@@ -43,6 +43,10 @@ import {
43 const RETRY_BASE_DELAY_MS = 1_000;
44 const RETRY_MAX_DELAY_MS = 300_000;
45 const SESSION_LOSS_RETRY_DELAY_MS = 250;
46 +// Someone is approving this device on the host; check back soon rather than climbing the ladder.
47 +const APPROVAL_PENDING_RETRY_DELAY_MS = 4_000;
48 +// A request lives 10 minutes; past that nobody is approving, so a forgotten device backs off.
49 +const APPROVAL_PENDING_FAST_RETRIES = 150;
50 // A cold server with a large database can take longer than 15 seconds to
51 // answer, and that is not a reason to drop a working connection.
52 const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
@@ -1118,11 +1122,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1122
1123 const run = Effect.fnUntraced(function* () {
1124 let failureCount = 0;
1125 + // Approval waits count as attempts but not toward backoff, so a later outage starts low.
1126 + let backoffFailures = 0;
1127 + let approvalWaits = 0;
1128 let generation = 0;
1129 let latestFailure: ConnectionAttemptError | null = null;
1130 let pendingRetry = Option.none<PendingRetryTrace>();
1131 const resetRetryLadder = () => {
1132 failureCount = 0;
1133 + backoffFailures = 0;
1134 + approvalWaits = 0;
1135 pendingRetry = Option.none();
1136 };
1137 let replacing = false;
@@ -1130,6 +1139,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1139 for (;;) {
1140 if (yield* Ref.getAndSet(resetRetryState, false)) {
1141 failureCount = 0;
1142 + backoffFailures = 0;
1143 + approvalWaits = 0;
1144 latestFailure = null;
1145 pendingRetry = Option.none();
1146 }
@@ -1212,9 +1223,20 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
1223 // still counts it, so a host that keeps dropping sessions backs off.
1224 const firstLoss = outcome.established && failureCount === 0;
1225 failureCount += 1;
1215 - const delayMs = firstLoss
1216 - ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
1217 - : retryDelayMs(failureCount - 1, yield* Random.next);
1226 + if (error.reason === "approval-pending") approvalWaits += 1;
1227 + const awaitingApproval =
1228 + error.reason === "approval-pending" && approvalWaits <= APPROVAL_PENDING_FAST_RETRIES;
1229 + if (!awaitingApproval) backoffFailures += 1;
1230 + const delayMs = awaitingApproval
1231 + ? APPROVAL_PENDING_RETRY_DELAY_MS
1232 + : firstLoss
1233 + ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
1234 + : error.reason === "approval-pending"
1235 + ? Math.max(
1236 + APPROVAL_PENDING_RETRY_DELAY_MS,
1237 + retryDelayMs(backoffFailures - 1, yield* Random.next),
1238 + )
1239 + : retryDelayMs(backoffFailures - 1, yield* Random.next);
1240 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
1241 previousAttempt,
1242 failureCount,
packages/client-runtime/src/rpc/http.ts
+2
@@ -2,6 +2,7 @@ import {
2 EnvironmentHttpApi,
3 EnvironmentHttpCommonError,
4 type EnvironmentAuthInvalidError,
5 + type EnvironmentConnectApprovalPendingError,
6 type EnvironmentInternalError,
7 type EnvironmentOperationForbiddenError,
8 type EnvironmentRequestInvalidError,
@@ -68,6 +69,7 @@ export type RemoteEnvironmentRequestError =
69 | EnvironmentOperationForbiddenError
70 | EnvironmentResourceNotFoundError
71 | EnvironmentInternalError
72 + | EnvironmentConnectApprovalPendingError
73 | RemoteEnvironmentAuthFetchError
74 | RemoteEnvironmentAuthInvalidJsonError
75 | RemoteEnvironmentAuthUndeclaredStatusError
packages/client-runtime/src/state/auth.ts
+25
@@ -1,5 +1,7 @@
1 import type {
2 AuthAccessSnapshot,
3 + AuthApproveConnectDeviceInput,
4 + AuthRevokeConnectDeviceInput,
5 AuthAccessStreamEvent,
6 AuthAccessStreamSnapshotEvent,
7 AuthCreatePairingCredentialInput,
@@ -132,6 +134,29 @@ export function createAuthEnvironmentAtoms<R, E>(
134 request: ({ client, headers }) => client.revokeOtherClients({ headers }),
135 }).pipe(Effect.map((result) => result.revokedCount)),
136 }),
137 + approveConnectDevice: createEnvironmentCommand(runtime, {
138 + label: "environment-data:server:auth-approve-connect-device",
139 + execute: (input: AuthApproveConnectDeviceInput) =>
140 + executeConnectedEnvironmentHttpRequest({
141 + group: "auth",
142 + method: "POST",
143 + url: (urls) => urls.approveConnectDevice(),
144 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
145 + request: ({ client, headers }) =>
146 + client.approveConnectDevice({ headers, payload: input }),
147 + }),
148 + }),
149 + revokeConnectDevice: createEnvironmentCommand(runtime, {
150 + label: "environment-data:server:auth-revoke-connect-device",
151 + execute: (input: AuthRevokeConnectDeviceInput) =>
152 + executeConnectedEnvironmentHttpRequest({
153 + group: "auth",
154 + method: "POST",
155 + url: (urls) => urls.revokeConnectDevice(),
156 + timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,
157 + request: ({ client, headers }) => client.revokeConnectDevice({ headers, payload: input }),
158 + }),
159 + }),
160 accessChanges: createEnvironmentSubscriptionAtomFamily(runtime, {
161 label: "environment-data:server:auth-access-changes",
162 subscribe: (_input: null) =>
packages/contracts/src/auth.ts
+64 -8
@@ -321,6 +321,39 @@ export const AuthPairingCredentialResult = Schema.Struct({
321 });
322 export type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;
323
324 +const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
325 +
326 +/**
327 + * A short code both sides show for a T3 Connect device, read from its proof key thumbprint.
328 + * The waiting device and the approver compare it so an approval lands on the device in hand.
329 + */
330 +export function connectDeviceVerificationCode(proofKeyThumbprint: string): string {
331 + let code = "";
332 + for (const character of proofKeyThumbprint.slice(0, 8)) {
333 + const value = Math.max(0, BASE64URL_ALPHABET.indexOf(character));
334 + code += PAIRING_CODE_ALPHABET[value % PAIRING_CODE_ALPHABET.length]!;
335 + }
336 + return `${code.slice(0, 4)}-${code.slice(4)}`;
337 +}
338 +
339 +export const AuthClientMetadata = Schema.Struct({
340 + label: Schema.optionalKey(TrimmedNonEmptyString),
341 + ipAddress: Schema.optionalKey(TrimmedNonEmptyString),
342 + userAgent: Schema.optionalKey(TrimmedNonEmptyString),
343 + deviceType: AuthClientMetadataDeviceType,
344 + os: Schema.optionalKey(TrimmedNonEmptyString),
345 + browser: Schema.optionalKey(TrimmedNonEmptyString),
346 +});
347 +export type AuthClientMetadata = typeof AuthClientMetadata.Type;
348 +
349 +/** A T3 Connect device waiting for someone on this environment to approve it. */
350 +export const AuthConnectDeviceRequest = Schema.Struct({
351 + verificationCode: TrimmedNonEmptyString,
352 + /** What the device said about itself when it first asked. Absent until it does. */
353 + client: Schema.optionalKey(AuthClientMetadata),
354 +});
355 +export type AuthConnectDeviceRequest = typeof AuthConnectDeviceRequest.Type;
356 +
357 export const AuthPairingLink = Schema.Struct({
358 id: TrimmedNonEmptyString,
359 ...authScopeResponseFields,
@@ -328,18 +361,19 @@ export const AuthPairingLink = Schema.Struct({
361 label: Schema.optionalKey(TrimmedNonEmptyString),
362 createdAt: Schema.DateTimeUtc,
363 expiresAt: Schema.DateTimeUtc,
364 + /** Set while a T3 Connect device waits for approval. Older servers never send it. */
365 + connectDeviceRequest: Schema.optionalKey(AuthConnectDeviceRequest),
366 });
367 export type AuthPairingLink = typeof AuthPairingLink.Type;
368
334 -export const AuthClientMetadata = Schema.Struct({
335 - label: Schema.optionalKey(TrimmedNonEmptyString),
336 - ipAddress: Schema.optionalKey(TrimmedNonEmptyString),
337 - userAgent: Schema.optionalKey(TrimmedNonEmptyString),
338 - deviceType: AuthClientMetadataDeviceType,
339 - os: Schema.optionalKey(TrimmedNonEmptyString),
340 - browser: Schema.optionalKey(TrimmedNonEmptyString),
369 +/** A T3 Connect device key this environment trusts to connect without asking again. */
370 +export const AuthConnectDevice = Schema.Struct({
371 + proofKeyThumbprint: TrimmedNonEmptyString,
372 + verificationCode: TrimmedNonEmptyString,
373 + client: Schema.optionalKey(AuthClientMetadata),
374 + approvedAt: Schema.DateTimeUtc,
375 });
342 -export type AuthClientMetadata = typeof AuthClientMetadata.Type;
376 +export type AuthConnectDevice = typeof AuthConnectDevice.Type;
377
378 export const AuthClientSession = Schema.Struct({
379 sessionId: AuthSessionId,
@@ -358,6 +392,8 @@ export type AuthClientSession = typeof AuthClientSession.Type;
392 export const AuthAccessSnapshot = Schema.Struct({
393 pairingLinks: Schema.Array(AuthPairingLink),
394 clientSessions: Schema.Array(AuthClientSession),
395 + /** Older servers omit it; they have no device approval. */
396 + connectDevices: Schema.optionalKey(Schema.Array(AuthConnectDevice)),
397 });
398 export type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;
399
@@ -442,6 +478,26 @@ export const AuthRevokeClientSessionInput = Schema.Struct({
478 });
479 export type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;
480
481 +export const AuthApproveConnectDeviceInput = Schema.Struct({
482 + pairingLinkId: TrimmedNonEmptyString,
483 +});
484 +export type AuthApproveConnectDeviceInput = typeof AuthApproveConnectDeviceInput.Type;
485 +
486 +export const AuthApproveConnectDeviceResult = Schema.Struct({
487 + approved: Schema.Boolean,
488 +});
489 +export type AuthApproveConnectDeviceResult = typeof AuthApproveConnectDeviceResult.Type;
490 +
491 +export const AuthRevokeConnectDeviceInput = Schema.Struct({
492 + proofKeyThumbprint: TrimmedNonEmptyString,
493 +});
494 +export type AuthRevokeConnectDeviceInput = typeof AuthRevokeConnectDeviceInput.Type;
495 +
496 +export const AuthRevokeConnectDeviceResult = Schema.Struct({
497 + revoked: Schema.Boolean,
498 +});
499 +export type AuthRevokeConnectDeviceResult = typeof AuthRevokeConnectDeviceResult.Type;
500 +
501 export const AuthCreatePairingCredentialInput = Schema.Struct({
502 label: Schema.optionalKey(TrimmedNonEmptyString),
503 scopes: Schema.optionalKey(AuthGrantScopes),
packages/contracts/src/environmentHttp.ts
+44
@@ -30,6 +30,10 @@ import {
30 AuthPairingCredentialResult,
31 AuthRevokeClientSessionInput,
32 AuthRevokePairingLinkInput,
33 + AuthApproveConnectDeviceInput,
34 + AuthApproveConnectDeviceResult,
35 + AuthRevokeConnectDeviceInput,
36 + AuthRevokeConnectDeviceResult,
37 AuthEnvironmentScope,
38 AuthTokenExchangeRequest,
39 AuthSessionState,
@@ -140,6 +144,8 @@ export const EnvironmentInternalErrorReason = Schema.Literals([
144 "pairing_link_revoke_failed",
145 "client_sessions_load_failed",
146 "client_session_revoke_failed",
147 + "connect_device_approve_failed",
148 + "connect_device_revoke_failed",
149 "project_snapshot_failed",
150 "project_mutation_failed",
151 "orchestration_snapshot_failed",
@@ -206,6 +212,26 @@ export class EnvironmentScopeRequiredError extends Schema.TaggedError<Environmen
212 }
213 }
214
215 +/** The host requires approval for this T3 Connect device and nobody has given it yet. */
216 +export class EnvironmentConnectApprovalPendingError extends Schema.TaggedError<EnvironmentConnectApprovalPendingError>()(
217 + "EnvironmentConnectApprovalPendingError",
218 + {
219 + code: Schema.Literal("connect_approval_pending"),
220 + traceId: TrimmedNonEmptyString,
221 + },
222 + { httpApiStatus: 403 },
223 +) {
224 + [HttpServerRespondable.symbol]() {
225 + return HttpServerResponse.schemaJson(EnvironmentConnectApprovalPendingError)(this, {
226 + status: 403,
227 + });
228 + }
229 +
230 + override get message(): string {
231 + return "This device is waiting for approval on the host.";
232 + }
233 +}
234 +
235 export class EnvironmentOperationForbiddenError extends Schema.TaggedError<EnvironmentOperationForbiddenError>()(
236 "EnvironmentOperationForbiddenError",
237 {
@@ -270,6 +296,7 @@ export const EnvironmentHttpCommonError = Schema.Union([
296 EnvironmentOperationForbiddenError,
297 EnvironmentResourceNotFoundError,
298 EnvironmentInternalError,
299 + EnvironmentConnectApprovalPendingError,
300 ]);
301 export type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;
302
@@ -359,6 +386,7 @@ const EnvironmentSessionCreationErrors = [
386 const EnvironmentTokenExchangeErrors = [
387 EnvironmentRequestInvalidError,
388 EnvironmentAuthInvalidError,
389 + EnvironmentConnectApprovalPendingError,
390 EnvironmentInternalError,
391 ] as const;
392 const EnvironmentScopedOperationErrors = [
@@ -621,6 +649,22 @@ class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
649 error: EnvironmentSessionRevokeErrors,
650 }).middleware(EnvironmentAuthenticatedAuth),
651 )
652 + .add(
653 + HttpApiEndpoint.post("approveConnectDevice", "/api/auth/connect-devices/approve", {
654 + headers: OptionalBearerHeaders,
655 + payload: AuthApproveConnectDeviceInput,
656 + success: AuthApproveConnectDeviceResult,
657 + error: EnvironmentScopedOperationErrors,
658 + }).middleware(EnvironmentAuthenticatedAuth),
659 + )
660 + .add(
661 + HttpApiEndpoint.post("revokeConnectDevice", "/api/auth/connect-devices/revoke", {
662 + headers: OptionalBearerHeaders,
663 + payload: AuthRevokeConnectDeviceInput,
664 + success: AuthRevokeConnectDeviceResult,
665 + error: EnvironmentScopedOperationErrors,
666 + }).middleware(EnvironmentAuthenticatedAuth),
667 + )
668 .add(
669 HttpApiEndpoint.post("revokeOtherClients", "/api/auth/clients/revoke-others", {
670 headers: OptionalBearerHeaders,
packages/contracts/src/settings.ts
+12 -2
@@ -1,6 +1,7 @@
1 import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts";
2 import {
3 AuthOrchestrationOperateScope,
4 + AuthAccessWriteScope,
5 AuthSettingsWriteScope,
6 AuthProvidersManageScope,
7 type AuthEnvironmentScope,
@@ -1382,6 +1383,10 @@ export const ServerSettings = Schema.Struct({
1383 ),
1384 /** Holds an OS sleep inhibitor while any run is active; closing a laptop lid still sleeps it. */
1385 keepAwakeWhileAgentsWork: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1386 + /** New T3 Connect device keys wait for approval from someone already trusted here. */
1387 + requireConnectDeviceApproval: Schema.Boolean.pipe(
1388 + Schema.withDecodingDefault(Effect.succeed(false)),
1389 + ),
1390
1391 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
1392 cloudSpeechCredentials: CloudSpeechCredentials.pipe(
@@ -1840,6 +1845,7 @@ export const ServerSettingsPatch = Schema.Struct({
1845 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
1846 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
1847 keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean),
1848 + requireConnectDeviceApproval: Schema.optionalKey(Schema.Boolean),
1849 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
1850 cloudSpeechCredentials: Schema.optionalKey(
1851 Schema.Struct({
@@ -1984,9 +1990,12 @@ export function requiredScopesForServerSettingsPatch(
1990 ): ReadonlyArray<AuthEnvironmentScope> {
1991 let changesProviders = false;
1992 let changesSettings = false;
1993 + let changesAccess = false;
1994 for (const [key, value] of Object.entries(patch)) {
1995 if (value === undefined) continue;
1989 - if (
1996 + if (key === "requireConnectDeviceApproval") {
1997 + changesAccess = true;
1998 + } else if (
1999 key === "providers" ||
2000 key === "providerInstances" ||
2001 key === "usageLimitSources" ||
@@ -2003,8 +2012,9 @@ export function requiredScopesForServerSettingsPatch(
2012 changesSettings = true;
2013 }
2014 return [
2006 - ...(changesSettings || !changesProviders ? [AuthSettingsWriteScope] : []),
2015 + ...(changesSettings || (!changesProviders && !changesAccess) ? [AuthSettingsWriteScope] : []),
2016 ...(changesProviders ? [AuthProvidersManageScope] : []),
2017 + ...(changesAccess ? [AuthAccessWriteScope] : []),
2018 ];
2019 }
2020