Skip to content

Commit ddff484

Browse files
fix(connect): revoking a device kills its unspent credentials
Review follow-ups: - Revoking a T3 Connect device, or every other device, also revokes unspent credentials bound to its key. Exchanging one minted before revocation trusted the device again without approval. - Onboarding waits for the approval setting to save before publishing. - Approval waits no longer climb the retry ladder, and the status title reads "Waiting for approval" instead of a failure. - Mobile shows approval prompts one at a time across hosts and offers a request again when approving or denying it fails; web restores the toast after a failure and Review opens the requesting environment. - Code-based revoke moved into EnvironmentAuth; docs corrected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b8de014 commit ddff484

17 files changed

Lines changed: 284 additions & 85 deletions

‎apps/mobile/src/features/connection/ConnectDeviceApprovalCoordinator.tsx‎

Lines changed: 50 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
import { AuthAccessWriteScope, type AuthPairingLink, type EnvironmentId } from "@t3tools/contracts";
2-
import { useEffect, useEffectEvent, useRef } from "react";
2+
import { useEffect, useEffectEvent } from "react";
33

44
import * as Dialog from "../../components/ui/Dialog";
55
import { authEnvironment } from "../../state/auth";
66
import { useEnvironments } from "../../state/environments";
77
import { useEnvironmentQuery } from "../../state/query";
88
import { useEnvironmentsWithScope } from "../../state/session";
99
import { useAtomCommand } from "../../state/use-atom-command";
10-
import { connectDeviceApprovalPrompts } from "./connectDeviceApproval";
10+
import {
11+
type ConnectDeviceApprovalPrompt,
12+
connectDeviceApprovalPrompts,
13+
createApprovalPromptQueue,
14+
} from "./connectDeviceApproval";
1115

1216
/** Asks to approve T3 Connect devices waiting on hosts that require it and this phone manages. */
1317
export function ConnectDeviceApprovalCoordinator() {
@@ -33,47 +37,67 @@ export function ConnectDeviceApprovalCoordinator() {
3337
);
3438
}
3539

40+
interface QueuedApprovalPrompt extends ConnectDeviceApprovalPrompt {
41+
readonly approve: () => Promise<boolean>;
42+
readonly deny: () => Promise<boolean>;
43+
}
44+
45+
// One queue for every host: a second Android alert would replace an unanswered first one.
46+
const approvalPrompts = createApprovalPromptQueue<QueuedApprovalPrompt>((prompt, answer) => {
47+
const respond = (action: () => Promise<boolean>, failure: string) => () =>
48+
void action().then((ok) => {
49+
if (ok) return answer("done");
50+
Dialog.alert(failure, "The request is still waiting. Try again.", [
51+
{ text: "OK", onPress: () => answer("retry") },
52+
]);
53+
});
54+
Dialog.alert(
55+
prompt.title,
56+
prompt.message,
57+
[
58+
{ text: "Deny", onPress: respond(prompt.deny, "Could not deny the device") },
59+
{ text: "Approve", onPress: respond(prompt.approve, "Could not approve the device") },
60+
],
61+
{ cancelable: false },
62+
);
63+
});
64+
3665
function EnvironmentApprovalWatcher(props: {
3766
readonly environmentId: EnvironmentId;
3867
readonly environmentLabel: string;
3968
}) {
4069
const access = useEnvironmentQuery(
4170
authEnvironment.accessChanges({ environmentId: props.environmentId, input: null }),
4271
);
43-
const approve = useAtomCommand(authEnvironment.approveConnectDevice);
44-
const deny = useAtomCommand(authEnvironment.revokePairingLink);
45-
const shownIds = useRef(new Set<string>());
72+
const approve = useAtomCommand(authEnvironment.approveConnectDevice, { reportFailure: false });
73+
const deny = useAtomCommand(authEnvironment.revokePairingLink, { reportFailure: false });
4674
const pairingLinks =
4775
access.data?.type === "snapshot" ? access.data.payload.pairingLinks : undefined;
4876

49-
const showPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {
77+
const offerPrompts = useEffectEvent((links: ReadonlyArray<AuthPairingLink>) => {
5078
const prompts = connectDeviceApprovalPrompts({
5179
environmentLabel: props.environmentLabel,
5280
pairingLinks: links,
53-
shownIds: shownIds.current,
81+
shownIds: approvalPrompts.known,
5482
});
55-
for (const prompt of prompts) {
56-
shownIds.current.add(prompt.pairingLinkId);
57-
Dialog.alert(prompt.title, prompt.message, [
58-
{
59-
text: "Deny",
60-
onPress: () =>
61-
void deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }),
62-
},
63-
{
64-
text: "Approve",
65-
onPress: () =>
66-
void approve({
67-
environmentId: props.environmentId,
68-
input: { pairingLinkId: prompt.pairingLinkId },
69-
}),
70-
},
71-
]);
72-
}
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"),
91+
deny: () =>
92+
deny({ environmentId: props.environmentId, input: { id: prompt.pairingLinkId } }).then(
93+
(result) => result._tag === "Success",
94+
),
95+
})),
96+
);
7397
});
7498
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new request on the access stream opens a native alert
7599
useEffect(() => {
76-
if (pairingLinks !== undefined) showPrompts(pairingLinks);
100+
if (pairingLinks !== undefined) offerPrompts(pairingLinks);
77101
}, [pairingLinks]);
78102

79103
return null;

‎apps/mobile/src/features/connection/connectDeviceApproval.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { AuthPairingLink } from "@t3tools/contracts";
22
import * as DateTime from "effect/DateTime";
33
import { describe, expect, it } from "vite-plus/test";
44

5-
import { connectDeviceApprovalPrompts } from "./connectDeviceApproval";
5+
import { connectDeviceApprovalPrompts, createApprovalPromptQueue } from "./connectDeviceApproval";
66

77
const link = (id: string, createdAtMs: number, request?: AuthPairingLink["connectDeviceRequest"]) =>
88
({
@@ -36,3 +36,23 @@ describe("connectDeviceApprovalPrompts", () => {
3636
expect(prompts[0]?.message).toContain("ABCD-EFGH");
3737
});
3838
});
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") => 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+
});

‎apps/mobile/src/features/connection/connectDeviceApproval.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,37 @@ export function connectDeviceApprovalPrompts(input: {
3535
message: `${describeConnectDevice(device)} wants to connect to ${input.environmentLabel} through T3 Connect. It shows code ${verificationCode}. Approve it only if that code matches.`,
3636
}));
3737
}
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+
*/
43+
export function createApprovalPromptQueue<P extends { readonly pairingLinkId: string }>(
44+
present: (prompt: P, answer: (outcome: "done" | "retry") => void) => void,
45+
) {
46+
const known = new Set<string>();
47+
const waiting: P[] = [];
48+
let showing = false;
49+
const next = () => {
50+
if (showing) return;
51+
const prompt = waiting.shift();
52+
if (prompt === undefined) return;
53+
showing = true;
54+
present(prompt, (outcome) => {
55+
showing = false;
56+
if (outcome === "retry") waiting.unshift(prompt);
57+
next();
58+
});
59+
};
60+
return {
61+
known: known as ReadonlySet<string>,
62+
offer(prompts: ReadonlyArray<P>) {
63+
for (const prompt of prompts) {
64+
if (known.has(prompt.pairingLinkId)) continue;
65+
known.add(prompt.pairingLinkId);
66+
waiting.push(prompt);
67+
}
68+
next();
69+
},
70+
};
71+
}

‎apps/server/src/auth/EnvironmentAuth.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
365365
),
366366
),
367367
);
368+
// A credential minted before revocation must not let the device back in afterwards.
369+
const unspent = yield* serverAuth.issueConnectCredential({
370+
proofKeyThumbprint: deviceKey,
371+
requireApproval: true,
372+
});
368373
const [oldestDeviceSession, newestDeviceSession] = yield* deviceSessions();
369374
expect(newestDeviceSession).toBeDefined();
370375
// Revoking any one of the device's sessions ends all of them and its trust.
@@ -373,6 +378,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
373378
).toBe(true);
374379
expect(yield* deviceSessions()).toEqual([]);
375380
expect(yield* serverAuth.listConnectDevices()).toEqual([]);
381+
expect((yield* exchange(unspent.credential).pipe(Effect.flip))._tag).toBe(
382+
"ServerAuthInvalidCredentialError",
383+
);
384+
expect(yield* serverAuth.listConnectDevices()).toEqual([]);
376385
const afterRevoke = yield* serverAuth.issueConnectCredential({
377386
proofKeyThumbprint: deviceKey,
378387
requireApproval: true,

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,10 @@ export class EnvironmentAuth extends Context.Service<
541541
readonly approveConnectDeviceByCode: (
542542
verificationCode: string,
543543
) => Effect.Effect<boolean, ServerAuthInternalError>;
544+
/** Revokes the one trusted device that shows this code; two that share it are ambiguous. */
545+
readonly revokeConnectDeviceByCode: (
546+
verificationCode: string,
547+
) => Effect.Effect<"revoked" | "not-found" | "ambiguous", ServerAuthInternalError>;
544548
readonly listConnectDevices: () => Effect.Effect<
545549
ReadonlyArray<AuthConnectDevice>,
546550
ServerAuthInternalError
@@ -1217,17 +1221,14 @@ export const make = Effect.gen(function* () {
12171221

12181222
const approveConnectDeviceByCode: EnvironmentAuth["Service"]["approveConnectDeviceByCode"] =
12191223
Effect.fn("EnvironmentAuth.approveConnectDeviceByCode")(function* (verificationCode) {
1220-
const wanted = verificationCode
1221-
.trim()
1222-
.toUpperCase()
1223-
.replace(/[^0-9A-Z]/g, "");
1224+
const wanted = normalizeVerificationCode(verificationCode);
12241225
const links = yield* bootstrapCredentials
12251226
.listActive()
12261227
.pipe(Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })));
12271228
const matches = links.filter(
12281229
(link) =>
12291230
link.connectDeviceRequest !== undefined &&
1230-
link.connectDeviceRequest.verificationCode.replace("-", "") === wanted,
1231+
normalizeVerificationCode(link.connectDeviceRequest.verificationCode) === wanted,
12311232
);
12321233
// Two waiting devices that share a code are ambiguous; approve neither.
12331234
if (matches.length !== 1) return false;
@@ -1252,6 +1253,18 @@ export const make = Effect.gen(function* () {
12521253
return removed || revokedSessions > 0;
12531254
});
12541255

1256+
const revokeConnectDeviceByCode: EnvironmentAuth["Service"]["revokeConnectDeviceByCode"] =
1257+
Effect.fn("EnvironmentAuth.revokeConnectDeviceByCode")(function* (verificationCode) {
1258+
const wanted = normalizeVerificationCode(verificationCode);
1259+
const matches = (yield* listConnectDevices()).filter(
1260+
(device) => normalizeVerificationCode(device.verificationCode) === wanted,
1261+
);
1262+
if (matches.length === 0) return "not-found" as const;
1263+
if (matches.length > 1) return "ambiguous" as const;
1264+
yield* revokeConnectDevice(matches[0]!.proofKeyThumbprint);
1265+
return "revoked" as const;
1266+
});
1267+
12551268
const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
12561269
sessions
12571270
.issue({
@@ -1575,6 +1588,7 @@ export const make = Effect.gen(function* () {
15751588
approveConnectDeviceByCode,
15761589
listConnectDevices,
15771590
revokeConnectDevice,
1591+
revokeConnectDeviceByCode,
15781592
issuePairingCredential,
15791593
issueStartupPairingCredential,
15801594
listPairingLinks,
@@ -1597,6 +1611,8 @@ export const make = Effect.gen(function* () {
15971611

15981612
const isMcpClientAccess = Schema.is(AuthMcpClientAccess);
15991613

1614+
const normalizeVerificationCode = (code: string) => code.toUpperCase().replace(/[^0-9A-Z]/g, "");
1615+
16001616
/** The level an approval code's subject names, or undefined for any other code. */
16011617
const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
16021618
const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,9 +815,22 @@ const make = Effect.gen(function* () {
815815
Effect.mapError((cause) => new ConnectDevicesError({ operation: "list", cause })),
816816
);
817817

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+
818830
const revokeConnectDevice: PairingGrantStore["Service"]["revokeConnectDevice"] = Effect.fn(
819831
"PairingGrantStore.revokeConnectDevice",
820832
)(function* (proofKeyThumbprint) {
833+
yield* revokeUnspentLinks({ proofKeyThumbprint, keepProofKeyThumbprint: null });
821834
const removed = yield* connectDevices
822835
.remove(proofKeyThumbprint)
823836
.pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));
@@ -827,6 +840,7 @@ const make = Effect.gen(function* () {
827840

828841
const revokeConnectDevicesExcept: PairingGrantStore["Service"]["revokeConnectDevicesExcept"] =
829842
Effect.fn("PairingGrantStore.revokeConnectDevicesExcept")(function* (keepProofKeyThumbprint) {
843+
yield* revokeUnspentLinks({ proofKeyThumbprint: null, keepProofKeyThumbprint });
830844
const removed = yield* connectDevices
831845
.removeAllExcept(keepProofKeyThumbprint)
832846
.pipe(Effect.mapError((cause) => new ConnectDevicesError({ operation: "revoke", cause })));

‎apps/server/src/cli/auth.ts‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,6 @@ const pairingCommand = Command.make("pairing").pipe(
167167
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
168168
);
169169

170-
const normalizeVerificationCode = (code: string) => code.toUpperCase().replace(/[^0-9A-Z]/g, "");
171-
172170
const connectDeviceListCommand = Command.make("list", {
173171
...authLocationFlags,
174172
json: jsonFlag,
@@ -223,20 +221,14 @@ const connectDeviceRevokeCommand = Command.make("revoke", {
223221
Command.withHandler((flags) =>
224222
runWithEnvironmentAuth(flags, (environmentAuth) =>
225223
Effect.gen(function* () {
226-
const wanted = normalizeVerificationCode(flags.code);
227-
const matches = (yield* environmentAuth.listConnectDevices()).filter(
228-
(device) => normalizeVerificationCode(device.verificationCode) === wanted,
224+
const outcome = yield* environmentAuth.revokeConnectDeviceByCode(flags.code);
225+
yield* Console.log(
226+
outcome === "revoked"
227+
? `Revoked ${flags.code}.\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`,
229231
);
230-
if (matches.length !== 1) {
231-
yield* Console.log(
232-
matches.length === 0
233-
? `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);
239-
yield* Console.log(`Revoked ${flags.code}.\n`);
240232
}),
241233
),
242234
),

0 commit comments

Comments
 (0)