The best way to control Claude Code, Codex and more from any computer or phone
fix(relay): refuse to relink an active environment under a different key (#39482)
Julius Marminge committed
Nov 19, 2026 at 19:46 UTC
aa685426e75e2cad4db638451ded5d607efbe210
7 files changed
+209
-57
apps/server/src/cloud/relayResponse.ts
+5
-1
@@ -65,8 +65,12 @@ function recoveryHint(error: RelayProtectedError): string {
65
return "Unlink an unused environment in T3 Connect, then restart T3 Code on this machine.";
66
case "RelayAuthInvalidError":
67
return "Run `t3 connect login` to check this machine's authorization. If the stored credential was revoked, sign out with `t3 connect logout`, then run `t3 connect` again. Restart T3 Code after signing in.";
68
- case "RelayEnvironmentLinkProofExpiredError":
68
case "RelayEnvironmentLinkProofInvalidError":
69
+ if (error.reason === "environment_key_mismatch") {
70
+ return "T3 Connect already has this environment linked with a different key. Unlink it in T3 Connect, then restart T3 Code on this machine.";
71
+ }
72
+ return "Check this machine's date and time, update T3 Code, then restart it.";
73
+ case "RelayEnvironmentLinkProofExpiredError":
74
return "Check this machine's date and time, update T3 Code, then restart it.";
75
default:
76
return "Retry when the relay is available. If this continues, include the trace ID when reporting it.";
docs/internals/t3-connect.md
+4
@@ -86,6 +86,10 @@ Managed tunnels expose only this server's own loopback HTTP origin. The link
86
proof signs that origin from the server's listening address and ignores the
87
caller's, so any client holding `relay:configure`, local or remote, can link
88
without being able to point the tunnel at another service on the host. The
89
+relay refuses to relink an active environment id under a different key: an
90
+account bearer alone would otherwise take over that environment's tunnel and
91
+trusted key with an origin it signed itself. Unlinking first releases the
92
+tunnel. The
93
relay resolves endpoints from its own managed allocations rather than a
94
caller-supplied URL. Health and mint
95
requests must not follow redirects. These restrictions keep endpoint discovery
infra/relay/src/environments/EnvironmentLinker.test.ts
+88
-2
@@ -112,6 +112,8 @@ const makeRequest = Effect.gen(function* () {
112
113
function layerTest(input?: {
114
readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"];
115
+ readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"];
116
+ readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"];
117
readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"];
118
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
119
}) {
@@ -130,7 +132,7 @@ function layerTest(input?: {
132
upsert: input?.upsert ?? (() => Effect.void),
133
listDeliveryUsersForEnvironment: () => Effect.succeed([]),
134
listForUser: () => Effect.succeed([]),
133
- getForUser: () => Effect.succeed(null),
135
+ getForUser: input?.getForUser ?? (() => Effect.succeed(null)),
136
findActiveManagedForEnvironment: () => Effect.succeed([]),
137
updateLiveActivityPreference: () =>
138
Effect.die("unexpected Live Activity preference update"),
@@ -144,7 +146,7 @@ function layerTest(input?: {
146
}),
147
Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, {
148
reconcileOrigin: () => Effect.succeed("ready"),
147
- prepareDeprovision: () => Effect.succeed(null),
149
+ prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)),
150
deprovision: input?.deprovision ?? (() => Effect.succeed(true)),
151
release: () => Effect.succeed(true),
152
provision: () =>
@@ -293,6 +295,90 @@ describe("EnvironmentLinker", () => {
295
);
296
});
297
298
+ it.effect("refuses to move an active link to a different environment key", () => {
299
+ const touched: Array<string> = [];
300
+ const activeLink = (environmentPublicKey: string) => ({
301
+ environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"],
302
+ label: "Link Test Environment",
303
+ endpoint: {
304
+ httpBaseUrl: "https://managed.example.test/",
305
+ wsBaseUrl: "wss://managed.example.test/ws",
306
+ providerKind: "cloudflare_tunnel" as const,
307
+ },
308
+ environmentPublicKey,
309
+ linkedAt: "2026-01-01T00:00:00.000Z",
310
+ });
311
+ let linkedKey = "another-environment-key";
312
+ return Effect.gen(function* () {
313
+ const linker = yield* EnvironmentLinker.EnvironmentLinker;
314
+ const refused = yield* linker
315
+ .link({ userId: "user_123", request: (yield* makeRequest).request })
316
+ .pipe(Effect.flip);
317
+ expect(refused).toMatchObject({
318
+ _tag: "EnvironmentLinkProofInvalid",
319
+ reason: "environment_key_mismatch",
320
+ });
321
+ expect(touched).toEqual([]);
322
+
323
+ linkedKey = environmentKeyPair.publicKey.trim();
324
+ yield* linker.link({ userId: "user_123", request: (yield* makeRequest).request });
325
+ expect(touched).toEqual(["deprovision", "upsert"]);
326
+ }).pipe(
327
+ Effect.provide(
328
+ layerTest({
329
+ getForUser: () => Effect.succeed(activeLink(linkedKey)),
330
+ upsert: () => Effect.sync(() => void touched.push("upsert")),
331
+ deprovision: () => Effect.sync(() => touched.push("deprovision") > 0),
332
+ }),
333
+ ),
334
+ );
335
+ });
336
+
337
+ it.effect.each([{ managedTunnelsEnabled: true }, { managedTunnelsEnabled: false }])(
338
+ "finishes a failed unlink teardown before a new link: %o",
339
+ ({ managedTunnelsEnabled }) => {
340
+ const touched: Array<string> = [];
341
+ let tornDown = false;
342
+ return Effect.gen(function* () {
343
+ const linker = yield* EnvironmentLinker.EnvironmentLinker;
344
+ const link = Effect.gen(function* () {
345
+ const { request } = yield* makeRequest;
346
+ return yield* linker.link({
347
+ userId: "user_123",
348
+ request: { ...request, managedTunnelsEnabled },
349
+ });
350
+ });
351
+ expect((yield* link.pipe(Effect.flip))._tag).toBe("ManagedEndpointDeprovisioningFailed");
352
+ expect(touched).toEqual(["deprovision"]);
353
+
354
+ tornDown = true;
355
+ yield* link;
356
+ expect(touched).toEqual(["deprovision", "deprovision", "upsert"]);
357
+ }).pipe(
358
+ Effect.provide(
359
+ layerTest({
360
+ prepareDeprovision: () =>
361
+ Effect.succeed({
362
+ userId: "user_123",
363
+ environmentId: "env-link-test",
364
+ hostname: "managed.example.test",
365
+ tunnelId: "left-behind-tunnel",
366
+ tunnelName: "left-behind",
367
+ dnsRecordId: null,
368
+ readyAt: null,
369
+ origin: null,
370
+ updatedAt: "2026-01-01T00:00:00.000Z",
371
+ generation: 1,
372
+ tunnelReleasedAt: null,
373
+ }),
374
+ deprovision: () => Effect.sync(() => touched.push("deprovision") > 0 && tornDown),
375
+ upsert: () => Effect.sync(() => void touched.push("upsert")),
376
+ }),
377
+ ),
378
+ );
379
+ },
380
+ );
381
+
382
it.effect("rejects replayed JWT ids", () =>
383
Effect.gen(function* () {
384
const { request } = yield* makeRequest;
infra/relay/src/environments/EnvironmentLinker.ts
+33
-2
@@ -55,6 +55,7 @@ export class EnvironmentLinkProofInvalid extends Schema.TaggedError<EnvironmentL
55
"consume_proof_nonce",
56
"consume_challenge_nonce",
57
"validate_origin",
58
+ "validate_existing_link",
59
"validate_endpoint",
60
]),
61
cause: Schema.optional(Schema.Defect()),
@@ -70,6 +71,8 @@ export type EnvironmentLinkError =
71
| EnvironmentLinkProofInvalid
72
| DpopProofs.DpopProofReplayPersistenceError
73
| EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
74
+ | EnvironmentLinks.EnvironmentLinkLookupPersistenceError
75
+ | ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed
76
| EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
77
| ManagedEndpointProvider.ManagedEndpointProviderError;
78
@@ -291,8 +294,36 @@ const make = Effect.gen(function* () {
294
stage: "validate_origin",
295
});
296
}
294
- // Non-tunnel links must release provisioned tunnel/DNS resources; best-effort deprovision is idempotent.
295
- if (!input.request.managedTunnelsEnabled) {
297
+ // The account bearer alone must not move an active link, its tunnel and its trusted key to
298
+ // another key. Unlinking first releases the tunnel.
299
+ const existing = yield* links.getForUser({
300
+ userId: input.userId,
301
+ environmentId: verified.environmentId,
302
+ });
303
+ if (existing !== null && existing.environmentPublicKey !== verified.environmentPublicKey) {
304
+ return yield* new EnvironmentLinkProofInvalid({
305
+ userId: input.userId,
306
+ environmentId: verified.environmentId,
307
+ reason: "environment_key_mismatch",
308
+ stage: "validate_existing_link",
309
+ });
310
+ }
311
+ // An unlink whose teardown failed leaves its tunnel behind, and provisioning would reuse it by
312
+ // name. Finish the teardown before any new link, publish-only too: once that link is active
313
+ // it could turn tunnels on and inherit the old one.
314
+ if (existing === null) {
315
+ const key = { userId: input.userId, environmentId: verified.environmentId };
316
+ const leftover = yield* managedEndpointProvider.prepareDeprovision(key);
317
+ if (!(yield* managedEndpointProvider.deprovision({ ...key, target: leftover }))) {
318
+ return yield* new ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed({
319
+ ...key,
320
+ stage: "claim-deprovision",
321
+ cause: "an earlier tunnel for this environment is still being torn down",
322
+ });
323
+ }
324
+ }
325
+ // An active link going publish-only releases its own tunnel/DNS; best-effort deprovision is idempotent.
326
+ if (existing !== null && !input.request.managedTunnelsEnabled) {
327
yield* managedEndpointProvider
328
.deprovision({
329
userId: input.userId,
infra/relay/src/http/Api.test.ts
+65
-46
@@ -1081,52 +1081,71 @@ describe("relay managed tunnel recovery", () => {
1081
});
1082
1083
describe("relay environment unlink", () => {
1084
- it.effect("drops the unlinked endpoint's held webhooks, even if clearing fails", () => {
1085
- const cleared: Array<string> = [];
1086
- const endpointKey = "0123456789abcdef";
1087
- const unlink = (clearFails: boolean) =>
1088
- unlinkEnvironmentRecord({
1089
- userId: "user-1",
1090
- environmentId: "environment-1",
1091
- managedEndpointNamespace: "dev",
1092
- }).pipe(
1093
- Effect.provide(
1094
- layerRelayUnlinkTest({
1095
- getForUser: () => Effect.succeed(linkedEnvironmentRecord),
1096
- revokeForUser: () => Effect.succeed(true),
1097
- prepareDeprovision: () =>
1098
- Effect.succeed({
1099
- userId: "user-1",
1100
- environmentId: "environment-1",
1101
- hostname: "dev-0123456789abcdef.example.test",
1102
- tunnelId: "tunnel-1",
1103
- tunnelName: `t3coderelay-managedendpoint-dev-${endpointKey}`,
1104
- dnsRecordId: "dns-1",
1105
- readyAt: "2026-07-28T00:00:00.000Z",
1106
- tunnelReleasedAt: null,
1107
- origin: null,
1108
- updatedAt: "2026-07-28T00:00:00.000Z",
1109
- generation: 1,
1110
- }),
1111
- clearInbox: (input) =>
1112
- clearFails
1113
- ? Effect.fail(
1114
- new HookInbox.HookInboxError({
1115
- operation: "clear",
1116
- endpointKey: input.endpointKey,
1117
- cause: new Error("unavailable"),
1118
- }),
1119
- )
1120
- : Effect.sync(() => void cleared.push(input.endpointKey)),
1121
- }),
1122
- ),
1123
- );
1124
- return Effect.gen(function* () {
1125
- expect(yield* unlink(false)).toBe(true);
1126
- expect(cleared).toEqual([endpointKey]);
1127
- expect(yield* unlink(true)).toBe(true);
1128
- });
1129
- });
1084
+ it.effect(
1085
+ "drops the unlinked endpoint's held webhooks, even if clearing or teardown fails",
1086
+ () => {
1087
+ const cleared: Array<string> = [];
1088
+ const endpointKey = "0123456789abcdef";
1089
+ const unlink = (clearFails: boolean, teardownFails = false) =>
1090
+ unlinkEnvironmentRecord({
1091
+ userId: "user-1",
1092
+ environmentId: "environment-1",
1093
+ managedEndpointNamespace: "dev",
1094
+ }).pipe(
1095
+ Effect.provide(
1096
+ layerRelayUnlinkTest({
1097
+ getForUser: () => Effect.succeed(linkedEnvironmentRecord),
1098
+ revokeForUser: () => Effect.succeed(true),
1099
+ prepareDeprovision: () =>
1100
+ Effect.succeed({
1101
+ userId: "user-1",
1102
+ environmentId: "environment-1",
1103
+ hostname: "dev-0123456789abcdef.example.test",
1104
+ tunnelId: "tunnel-1",
1105
+ tunnelName: `t3coderelay-managedendpoint-dev-${endpointKey}`,
1106
+ dnsRecordId: "dns-1",
1107
+ readyAt: "2026-07-28T00:00:00.000Z",
1108
+ tunnelReleasedAt: null,
1109
+ origin: null,
1110
+ updatedAt: "2026-07-28T00:00:00.000Z",
1111
+ generation: 1,
1112
+ }),
1113
+ clearInbox: (input) =>
1114
+ clearFails
1115
+ ? Effect.fail(
1116
+ new HookInbox.HookInboxError({
1117
+ operation: "clear",
1118
+ endpointKey: input.endpointKey,
1119
+ cause: new Error("unavailable"),
1120
+ }),
1121
+ )
1122
+ : Effect.sync(() => void cleared.push(input.endpointKey)),
1123
+ ...(teardownFails
1124
+ ? {
1125
+ deprovision: (input) =>
1126
+ Effect.fail(
1127
+ new ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed({
1128
+ userId: input.userId,
1129
+ environmentId: input.environmentId,
1130
+ stage: "delete-tunnel",
1131
+ cause: new Error("unavailable"),
1132
+ }),
1133
+ ),
1134
+ }
1135
+ : {}),
1136
+ }),
1137
+ ),
1138
+ );
1139
+ return Effect.gen(function* () {
1140
+ expect(yield* unlink(false)).toBe(true);
1141
+ expect(cleared).toEqual([endpointKey]);
1142
+ expect(yield* unlink(true)).toBe(true);
1143
+ // A later link under another key shares the inbox, so it is emptied before teardown can fail.
1144
+ yield* unlink(false, true).pipe(Effect.flip);
1145
+ expect(cleared).toEqual([endpointKey, endpointKey]);
1146
+ });
1147
+ },
1148
+ );
1149
1150
it.effect("commits database revocation before deprovisioning the managed endpoint", () => {
1151
const calls: Array<string> = [];
infra/relay/src/http/Api.ts
+13
-6
@@ -527,12 +527,7 @@ export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnviron
527
environmentId: link.environmentId,
528
environmentPublicKey: link.environmentPublicKey,
529
});
530
- // Deprovision after revocation commits; retry even if already revoked to finish failed Cloudflare cleanup.
531
- const deprovisioned = yield* managedEndpointProvider.deprovision({
532
- userId: input.userId,
533
- environmentId: input.environmentId,
534
- target: deprovisionTarget,
535
- });
530
+ // Cleared before teardown, which can fail: a later link under another key shares this inbox.
531
const endpointKey =
532
deprovisionTarget && input.managedEndpointNamespace
533
? HeldHooks.endpointKeyForTunnelName(
@@ -551,6 +546,12 @@ export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnviron
546
),
547
);
548
}
549
+ // Deprovision after revocation commits; retry even if already revoked to finish failed Cloudflare cleanup.
550
+ const deprovisioned = yield* managedEndpointProvider.deprovision({
551
+ userId: input.userId,
552
+ environmentId: input.environmentId,
553
+ target: deprovisionTarget,
554
+ });
555
if (!deprovisioned) {
556
const key = { userId: input.userId, environmentId: input.environmentId };
557
const retryTarget = yield* managedEndpointProvider.prepareDeprovision(key);
@@ -897,6 +898,12 @@ export const layerClientApi = HttpApiBuilder.group(
898
reason: "origin_not_allowed",
899
traceId,
900
}),
901
+ ManagedEndpointDeprovisioningFailed: (_error, traceId) =>
902
+ new RelayEnvironmentLinkUnavailableError({
903
+ code: "environment_link_unavailable",
904
+ reason: "managed_endpoint_provisioning_failed",
905
+ traceId,
906
+ }),
907
ManagedTunnelLimitExceeded: (limitError, traceId) =>
908
new RelayEnvironmentLinkLimitExceededError({
909
code: "environment_link_limit_exceeded",
packages/contracts/src/relay.ts
+1
@@ -352,6 +352,7 @@ export const RelayEnvironmentLinkProofInvalidReason = Schema.Literals([
352
"challenge_invalid",
353
"origin_not_allowed",
354
"endpoint_not_secure",
355
+ "environment_key_mismatch",
356
]);
357
export type RelayEnvironmentLinkProofInvalidReason =
358
typeof RelayEnvironmentLinkProofInvalidReason.Type;