feat(connect): require approval for new T3 Connect devices #36419
Mergedjuliusmarmingemerged 14 commits into
main fromrefs/pull/36419/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +107,21 @@107+ approve({ environmentId, input: { pairingLinkId: id } }),108+ );109+ },110+ },111+ data: {112+ hideCopyButton: true,113+ secondaryActionProps: {114+ children: "Deny",115+ onClick: () => {116+ close();117+ void reportFailure("Could not deny the device", () =>118+ deny({ environmentId, input: { id } }),119+ );120+ },121+ },122+ additionalActions: [123+ {124+ id: "review",125+ props: {126+ children: "Review",127+ onClick: () => void navigate({ to: "/settings/access" }),@@ -165,3 +173,6 @@165173166174 const applyPublishSelection = async () => {167175 if (isApplying) return;176+ // Onboarding only turns approval on; turning it off stays in Settings.177+ if (requireDeviceApproval && !deviceApprovalRequired) {178+ updatePrimarySettings({ requireConnectDeviceApproval: true });@@ -0,0 +37,21 @@37+ readonly environmentId: EnvironmentId;38+ readonly environmentLabel: string;39+}) {40+ const access = useEnvironmentQuery(41+ authEnvironment.accessChanges({ environmentId: props.environmentId, input: null }),42+ );43+ const approve = useAtomCommand(authEnvironment.approveConnectDevice);44+ const deny = useAtomCommand(authEnvironment.revokePairingLink);45+ const shownIds = useRef(new Set<string>());46+ const pairingLinks =47+ access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;48+49+ const showPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {50+ const prompts = connectDeviceApprovalPrompts({51+ environmentLabel: props.environmentLabel,52+ pairingLinks: links,53+ shownIds: shownIds.current,54+ });55+ for (const prompt of prompts) {56+ shownIds.current.add(prompt.pairingLinkId);57+ Dialog.alert(prompt.title, prompt.message, [@@ -0,0 +46,21 @@46+ const pairingLinks =47+ access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;48+49+ const showPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {50+ const prompts = connectDeviceApprovalPrompts({51+ environmentLabel: props.environmentLabel,52+ pairingLinks: links,53+ shownIds: shownIds.current,54+ });55+ for (const prompt of prompts) {56+ shownIds.current.add(prompt.pairingLinkId);57+ Dialog.alert(prompt.title, prompt.message, [58+ {59+ text: "Deny",60+ style: "destructive",61+ onPress: () =>62+ void deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }),63+ },64+ {65+ text: "Approve",66+ onPress: () =>@@ -1096,0 +1226,21 @@1226+ .pipe(Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })));1227+ const matches = links.filter(1228+ (link) =>1229+ link.connectDeviceRequest !== undefined &&1230+ link.connectDeviceRequest.verificationCode.replace("-", "") === wanted,1231+ );1232+ // Two waiting devices that share a code are ambiguous; approve neither.1233+ if (matches.length !== 1) return false;1234+ return yield* approveConnectDevice(matches[0]!.id);1235+ });1236+1237+ const listConnectDevices: EnvironmentAuth["Service"]["listConnectDevices"] = () =>1238+ bootstrapCredentials.listConnectDevices().pipe(1239+ Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })),1240+ Effect.withSpan("EnvironmentAuth.listConnectDevices"),1241+ );1242+1243+ const revokeConnectDevice: EnvironmentAuth["Service"]["revokeConnectDevice"] = Effect.fn(1244+ "EnvironmentAuth.revokeConnectDevice",1245+ )(function* (proofKeyThumbprint) {1246+ const removed = yield* bootstrapCredentials@@ -91,4 +110,7 @@91110 if (connection.phase === "reconnecting" && connection.error) {92111 return "Failed to connect. Reconnecting...";93112 }113+ if (connection.awaitingApproval) {114+ return "Waiting for approval";115+ }94116 return connectionStatusText({ ...connection, error: null });
- @@ -0,0 +37,21 @@37+ readonly environmentId: EnvironmentId;38+ readonly environmentLabel: string;39+}) {40+ const access = useEnvironmentQuery(41+ authEnvironment.accessChanges({ environmentId: props.environmentId, input: null }),42+ );43+ const approve = useAtomCommand(authEnvironment.approveConnectDevice);44+ const deny = useAtomCommand(authEnvironment.revokePairingLink);45+ const shownIds = useRef(new Set<string>());46+ const pairingLinks =47+ access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;48+49+ const showPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {50+ const prompts = connectDeviceApprovalPrompts({51+ environmentLabel: props.environmentLabel,52+ pairingLinks: links,53+ shownIds: shownIds.current,54+ });55+ for (const prompt of prompts) {56+ shownIds.current.add(prompt.pairingLinkId);57+ Dialog.alert(prompt.title, prompt.message, [@@ -0,0 +50,21 @@50+ const prompts = connectDeviceApprovalPrompts({51+ environmentLabel: props.environmentLabel,52+ pairingLinks: links,53+ shownIds: shownIds.current,54+ });55+ for (const prompt of prompts) {56+ shownIds.current.add(prompt.pairingLinkId);57+ Dialog.alert(prompt.title, prompt.message, [58+ {59+ text: "Deny",60+ style: "destructive",61+ onPress: () =>62+ void deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }),63+ },64+ {65+ text: "Approve",66+ onPress: () =>67+ void approve({68+ environmentId: props.environmentId,69+ input: { pairingLinkId: prompt.pairingLinkId },70+ }),@@ -1096,0 +1185,21 @@1185+ const mustWait =1186+ requireApproval &&1187+ !(yield* bootstrapCredentials1188+ .isConnectDeviceTrusted(proofKeyThumbprint)1189+ .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))));1190+ if (mustWait) {1191+ const pending = yield* bootstrapCredentials1192+ .findPendingConnect(proofKeyThumbprint)1193+ .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));1194+ if (Option.isSome(pending)) {1195+ return { credential: pending.value.credential, expiresAt: pending.value.expiresAt };1196+ }1197+ }1198+ const issued = yield* createPairingLink({1199+ scopes: AuthStandardClientScopes,1200+ subject: CLOUD_CONNECT_SUBJECT,1201+ // Long enough for someone to notice the request and approve it.1202+ ttl: mustWait ? Duration.minutes(10) : Duration.minutes(2),1203+ label: "T3 Connect connect",1204+ proofKeyThumbprint,1205+ ...(mustWait ? { requiresConnectApproval: true } : {}),@@ -168,0 +218,21 @@218+const connectDeviceRevokeCommand = Command.make("revoke", {219+ ...authLocationFlags,220+ code: verificationCodeArgument,221+}).pipe(222+ Command.withDescription("Stop trusting a T3 Connect device and end its sessions."),223+ Command.withHandler((flags) =>224+ runWithEnvironmentAuth(flags, (environmentAuth) =>225+ Effect.gen(function* () {226+ const wanted = normalizeVerificationCode(flags.code);227+ const matches = (yield* environmentAuth.listConnectDevices()).filter(228+ (device) => normalizeVerificationCode(device.verificationCode) === wanted,229+ );230+ if (matches.length !== 1) {231+ yield* Console.log(232+ matches.length === 0233+ ? `No trusted device shows ${flags.code}.\n`234+ : `More than one trusted device shows ${flags.code}; revoke it from a client.\n`,235+ );236+ return;237+ }238+ yield* environmentAuth.revokeConnectDevice(matches[0]!.proofKeyThumbprint);@@ -165,3 +173,6 @@165173166174 const applyPublishSelection = async () => {167175 if (isApplying) return;176+ // Onboarding only turns approval on; turning it off stays in Settings.177+ if (requireDeviceApproval && !deviceApprovalRequired) {178+ updatePrimarySettings({ requireConnectDeviceApproval: true });@@ -0,0 +85,21 @@85+ toastManager.close(tracked.toastId);86+ toasts.current.delete(id);87+ }88+ for (const { id, request } of requests) {89+ const device = describeConnectDeviceClient(request);90+ const renderedKey = `${request.verificationCode}:${device}`;91+ const tracked = toasts.current.get(id);92+ if (tracked?.renderedKey === renderedKey) continue;93+ const close = () => {94+ const current = toasts.current.get(id);95+ if (current) toastManager.close(current.toastId);96+ };97+ const options = stackedThreadToast({98+ type: "info",99+ title: `A device wants to connect to ${environmentLabel}`,100+ description: `${device}. Approve only if it shows code ${request.verificationCode}.`,101+ timeout: 0,102+ actionProps: {103+ children: "Approve",104+ onClick: () => {105+ close();@@ -0,0 +107,21 @@107+ approve({ environmentId, input: { pairingLinkId: id } }),108+ );109+ },110+ },111+ data: {112+ hideCopyButton: true,113+ secondaryActionProps: {114+ children: "Deny",115+ onClick: () => {116+ close();117+ void reportFailure("Could not deny the device", () =>118+ deny({ environmentId, input: { id } }),119+ );120+ },121+ },122+ additionalActions: [123+ {124+ id: "review",125+ props: {126+ children: "Review",127+ onClick: () => void navigate({ to: "/settings/access" }),@@ -64,3 +64,14 @@6464 exchange from credential reuse; it does not make a compromised relay signing6565 key harmless. Keep that trust assumption explicit when changing the protocol.666667+Device approval, off by default, limits what that authority buys. With68+`requireConnectDeviceApproval` on, the environment trusts T3 Connect device69+keys, meaning DPoP thumbprints, and not the relay. A mint for an untrusted key70+still succeeds, so the relay protocol does not change. The credential it returns71+cannot be spent until someone with `access:write` on the environment approves72+that key, so a forged mint yields a request that waits for approval, never a73+session. The waiting device retries the whole mint, and the environment hands74+back the same open request, so approvers see one entry with a stable code75+derived from the thumbprint. Approval is per key and does not expire. It ends76+only when the key is revoked, and revoking any session bound to the key revokes77+the key and all its sessions; otherwise the device would mint itself a new@@ -38,3 +38,10 @@3838 previous credential expires. A failed renewal affects that request; it does not3939 disconnect an otherwise healthy conversation.404041+### Approve new devices42+43+By default, any device signed in to your T3 Connect account can open a linked44+machine. To require approval instead, turn on **Require approval for new45+devices** in **Settings → Sharing & access** on the host, or when you first46+set up T3 Connect. Then someone who takes over your T3 Connect account still47+cannot reach the machine without your approval.@@ -39,2 +39,21 @@3939 disconnect an otherwise healthy conversation.404041+### Approve new devices42+43+By default, any device signed in to your T3 Connect account can open a linked44+machine. To require approval instead, turn on **Require approval for new45+devices** in **Settings → Sharing & access** on the host, or when you first46+set up T3 Connect. Then someone who takes over your T3 Connect account still47+cannot reach the machine without your approval.48+49+A new device waits and shows a code such as `K7QM-2XFD`. Approve it from a50+device that is already connected, using the prompt or **Settings → Sharing &51+access**. Check that the code matches the one on the waiting device. On a52+headless host, run `t3 auth connect-device list` and then53+`t3 auth connect-device approve K7QM-2XFD`. A request expires after 10 minutes,54+and the device asks again when it retries.55+56+Each device is approved once. Revoke it from **T3 Connect devices** in the same57+settings page, or with `t3 auth connect-device revoke <code>`, and it has to ask58+again. Devices that connected before you turned approval on stay approved, and59+appear in that list for you to review. Older apps cannot show the code, so update@@ -91,3 +110,6 @@91110 if (connection.phase === "reconnecting" && connection.error) {92111 return "Failed to connect. Reconnecting...";93112 }113+ if (connection.awaitingApproval) {114+ return "Waiting for approval";115+ }@@ -1212,6 +1214,6 @@12121214 // still counts it, so a host that keeps dropping sessions backs off.12131215 const firstLoss = outcome.established && failureCount === 0;12141216 failureCount += 1;1215- const delayMs = firstLoss1216- ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))1217- : retryDelayMs(failureCount - 1, yield* Random.next);1217+ const delayMs =1218+ error.reason === "approval-pending"1219+ ? APPROVAL_PENDING_RETRY_DELAY_MS
- @@ -743,3 +750,4 @@743750 }744751 />745752 ) : null}753+ {managedTunnelActive && !signedOut && connectDeviceApproval ? (
- @@ -1094,3 +1176,20 @@10941176 Effect.withSpan("EnvironmentAuth.revokePairingLink"),10951177 );109611781179+ const recordConnectRequest = (pairingLinkId: string, client: AuthClientMetadata | undefined) =>1180+ client === undefined1181+ ? Effect.void1182+ : bootstrapCredentials1183+ .recordConnectRequestClient(pairingLinkId, client)1184+ .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));1185+1186+ const issueConnectCredential: EnvironmentAuth["Service"]["issueConnectCredential"] = Effect.fn(1187+ "EnvironmentAuth.issueConnectCredential",1188+ )(function* ({ proofKeyThumbprint, requireApproval }) {1189+ const mustWait =1190+ requireApproval &&1191+ !(yield* bootstrapCredentials1192+ .isConnectDeviceTrusted(proofKeyThumbprint)1193+ .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))));1194+ if (mustWait) {1195+ const pending = yield* bootstrapCredentials@@ -0,0 +64,21 @@64+ environmentLabel,65+}: {66+ readonly environmentId: EnvironmentId;67+ readonly environmentLabel: string;68+}) {69+ const navigate = useNavigate();70+ const access = useEnvironmentQuery(authEnvironment.accessChanges({ environmentId, input: null }));71+ const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });72+ const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });73+ const toasts = useRef(new Map<string, { toastId: string; renderedKey: string }>());74+ const [, setRetryGeneration] = useState(0);75+ // A failed approve or deny forgets its toast and re-renders, so the request is offered again.76+ const settle = async (id: string, failed: Promise<boolean>) => {77+ if (!(await failed)) return;78+ toasts.current.delete(id);79+ setRetryGeneration((generation) => generation + 1);80+ };81+82+ const requests =83+ access.data?.type === "snapshot"84+ ? access.data.payload.pairingLinks.flatMap((link) =>@@ -0,0 +70,21 @@70+ authEnvironment.accessChanges({ environmentId: props.environmentId, input: null }),71+ );72+ const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });73+ const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });74+ const pairingLinks =75+ access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;76+77+ const offerPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {78+ const prompts = connectDeviceApprovalPrompts({79+ environmentLabel: props.environmentLabel,80+ pairingLinks: links,81+ shownIds: approvalPrompts.known,82+ });83+ approvalPrompts.offer(84+ prompts.map((prompt) => ({85+ ...prompt,86+ approve: () =>87+ approve({88+ environmentId: props.environmentId,89+ input: { pairingLinkId: prompt.pairingLinkId },90+ }).then((result) => result._tag === "Success"),
- @@ -0,0 +90,21 @@90+ });91+ approvalPrompts.offer(92+ prompts.map((prompt) => ({93+ ...prompt,94+ approve: () =>95+ approve({96+ environmentId: props.environmentId,97+ input: { pairingLinkId: prompt.pairingLinkId },98+ }).then((result) =>99+ result._tag !== "Success" ? "failed" : result.value.approved ? "done" : "gone",100+ ),101+ deny: () =>102+ deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }).then(103+ (result) =>104+ result._tag !== "Success" ? "failed" : result.value.revoked ? "done" : "gone",105+ ),106+ })),107+ );108+ });109+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new request on the access stream opens a native alert110+ useEffect(() => {
- @@ -0,0 +48,21 @@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("Request no longer waiting", "It expired or was answered elsewhere.", [61+ { text: "OK", onPress: () => answer("done") },62+ ]);63+ }64+ Dialog.alert(failure, "The request is still waiting. Try again.", [65+ { text: "OK", onPress: () => answer("retry") },66+ ]);67+ });68+ Dialog.alert(
- @@ -0,0 +52,21 @@52+ const prompt = waiting.shift();53+ if (prompt === undefined) return;54+ showing = true;55+ let answered = false;56+ present(prompt, (outcome) => {57+ if (answered) return;58+ answered = true;59+ showing = false;60+ if (outcome !== "done") waiting.unshift(prompt);61+ if (outcome !== "later") next();62+ });63+ };64+ return {65+ known: known as ReadonlySet<string>,66+ /** Forgets waiting prompts that match, such as a host that went away. */67+ drop(matches: (prompt: P) => boolean) {68+ for (let index = waiting.length - 1; index >= 0; index--) {69+ const prompt = waiting[index]!;70+ if (!matches(prompt)) continue;71+ waiting.splice(index, 1);72+ known.delete(prompt.pairingLinkId);@@ -39,2 +39,21 @@3939 disconnect an otherwise healthy conversation.404041+### Approve new devices42+43+By default, any device signed in to your T3 Connect account can open a linked44+machine. To require approval instead, turn on **Require approval for new45+devices** with the T3 Connect settings in **Settings → Sharing & access** on the46+host, or when you first set up T3 Connect. Then someone who takes over your T347+Connect account cannot reach the machine from a new device without your48+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 a51+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 a53+headless host, run `t3 auth connect-device list` and then54+`t3 auth connect-device approve K7QM-2XFD`. A request expires after 10 minutes,55+and the device asks again when it retries.56+57+Each device is approved once. Revoke it from **T3 Connect devices** in the same58+settings page, or with `t3 auth connect-device revoke <code>`, and it has to ask59+again. Devices that connected through T3 Connect while approval was off stay
- @@ -964,5 +1036,12 @@9641036 (credential, requestedScopes, requestMetadata, input) => {9651037 return resolveBootstrapGrant(credential, {9661038 ...input,1039+ requestMetadata,9671040 ...(requestedScopes !== undefined ? { requestedScopes } : {}),9681041 }).pipe(1042+ // Every T3 Connect key that gets in is remembered, so turning approval on later1043+ // keeps the devices already in use and lists them for review.1044+ Effect.tap((grant) =>1045+ grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint1046+ ? bootstrapCredentials1047+ .trustConnectDevice(input.proofKeyThumbprint, requestMetadata)
juliusmarminge merged thisa2edd28
juliusmarminge closed this
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed