The best way to control Claude Code, Codex and more from any computer or phone
refactor(server): CloudLink keeps only the link lifecycle; pure checks live beside it (#16340)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 5, 2026 at 20:46 UTC
ff873b2ec1972b701c3f9edd6a0f727c91604dc4
8 files changed
+556
-480
apps/server/src/auth/replayMarkers.ts
+1
-1
@@ -7,7 +7,7 @@ import * as Option from "effect/Option";
7
import * as Path from "effect/Path";
8
import * as Schedule from "effect/Schedule";
9
10
-import { CLOUD_REPLAY_MARKER_PREFIXES } from "../cloud/CloudLink.ts";
10
+import { CLOUD_REPLAY_MARKER_PREFIXES } from "../cloud/linkChecks.ts";
11
import * as ServerConfig from "../config.ts";
12
import { forkParked } from "../serverActivation.ts";
13
import { DPOP_REPLAY_MARKER_PREFIX } from "./dpop.ts";
apps/server/src/cloud/CloudLink.lifecycle.test.ts
renamed
+74
-245
@@ -8,22 +8,13 @@ import * as FileSystem from "effect/FileSystem";
8
import * as Layer from "effect/Layer";
9
import * as Option from "effect/Option";
10
import * as Path from "effect/Path";
11
-import * as PlatformError from "effect/PlatformError";
11
import * as Schema from "effect/Schema";
12
import * as TestClock from "effect/testing/TestClock";
14
-import * as Tracer from "effect/Tracer";
13
import * as Stream from "effect/Stream";
16
-import {
17
- HttpClient,
18
- HttpClientResponse,
19
- HttpServer,
20
- HttpServerRequest,
21
- type HttpClientRequest,
22
-} from "effect/http";
14
+import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
15
import * as NetAddress from "effect/net/NetAddress";
16
17
import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";
26
-import { RelayClientTracer } from "@t3tools/shared/relayTracing";
18
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
19
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
20
import * as ServerConfigModule from "../config.ts";
@@ -38,10 +29,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
29
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
30
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
31
import * as CliTokenManager from "./CliTokenManager.ts";
41
-import {
42
- RelayManagedEndpointRecoveryRegistrationRequest,
43
- type RelayLinkProofRequest,
44
-} from "@t3tools/contracts/relay";
32
+import { RelayManagedEndpointRecoveryRegistrationRequest } from "@t3tools/contracts/relay";
33
import {
34
CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
35
CLOUD_ENDPOINT_RUNTIME_CONFIG,
@@ -52,31 +40,13 @@ import {
40
RELAY_URL_SECRET,
41
} from "./config.ts";
42
import * as CloudLink from "./CloudLink.ts";
55
-import {
56
- consumeCloudReplayGuards,
57
- isSupportedLinkProviderKind,
58
- linkProofScopes,
59
- pendingServiceUpdateExists,
60
- parseManagedEndpointLocalOrigin,
61
-} from "./CloudLink.ts";
43
+import { pendingServiceUpdateExists } from "./updateHandoff.ts";
44
import {
45
managedTunnelStartupAction,
46
retryManagedTunnelRegistration,
47
} from "./managedTunnelStartup.ts";
48
import { shouldRetryCloudLink } from "./relayResponse.ts";
49
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
68
-import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
69
-
70
-const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
71
- new ServerSecretStore.SecretStorePersistError({
72
- resource: "cloud replay guard",
73
- cause: PlatformError.systemError({
74
- _tag: tag,
75
- module: "FileSystem",
76
- method: "open",
77
- pathOrDescriptor: "cloud-replay-guard.bin",
78
- }),
79
- });
50
51
const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
52
// Linking wakes the awareness relay; these tests do not run it.
@@ -93,22 +63,6 @@ const idleHttpServer = HttpServer.HttpServer.of({
63
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
64
});
65
96
-const reconcileDesiredCloudLink = (localOrigin: string) =>
97
- CloudLink.CloudLink.use((link) => link.reconcileDesiredLink(localOrigin));
98
-const reconcileDesiredCloudLinkIfStillDesired = (localOrigin: string) =>
99
- CloudLink.CloudLink.use((link) => link.reconcileDesiredLinkIfStillDesired(localOrigin));
100
-const recoverManagedCloudTunnel = (
101
- ...args: Parameters<CloudLink.CloudLink["Service"]["recoverManagedTunnel"]>
102
-) => CloudLink.CloudLink.use((link) => link.recoverManagedTunnel(...args));
103
-const registerManagedCloudTunnelRecovery = (
104
- ...args: Parameters<CloudLink.CloudLink["Service"]["registerManagedTunnelRecovery"]>
105
-) => CloudLink.CloudLink.use((link) => link.registerManagedTunnelRecovery(...args));
106
-const releaseManagedTunnelOnShutdown = () =>
107
- CloudLink.CloudLink.use((link) => link.releaseManagedTunnelOnShutdown());
108
-const startManagedCloudTunnelIfOriginConfirmed = (
109
- ...args: Parameters<CloudLink.CloudLink["Service"]["startManagedTunnelIfOriginConfirmed"]>
110
-) => CloudLink.CloudLink.use((link) => link.startManagedTunnelIfOriginConfirmed(...args));
111
-
66
const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
67
Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
68
);
@@ -149,103 +103,11 @@ it("preserves messages surfaced by cloud 500 responses", () => {
103
]);
104
});
105
152
-describe("consumeCloudReplayGuards", () => {
153
- it.effect("reports already-created guards as replay conflicts", () =>
154
- Effect.gen(function* () {
155
- const consumed = yield* consumeCloudReplayGuards({
156
- secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
157
- names: ["cloud-jti", "cloud-nonce"],
158
- value: new Uint8Array(),
159
- });
160
-
161
- expect(consumed).toBe(false);
162
- }),
163
- );
164
-
165
- it.effect("preserves replay-store availability failures", () =>
166
- Effect.gen(function* () {
167
- const failure = storeFailure("PermissionDenied");
168
- const error = yield* Effect.flip(
169
- consumeCloudReplayGuards({
170
- secrets: makeSecretStore(() => Effect.fail(failure)),
171
- names: ["cloud-jti", "cloud-nonce"],
172
- value: new Uint8Array(),
173
- }),
174
- );
175
-
176
- expect(error).toBe(failure);
177
- }),
178
- );
179
-});
180
-
181
-describe("relay request tracing", () => {
182
- it.effect("does not accept an unauthenticated request trace parent", () =>
183
- Effect.gen(function* () {
184
- const spans: Array<Tracer.Span> = [];
185
- const productTracer = Tracer.make({
186
- span: (options) => {
187
- const span = new Tracer.NativeSpan(options);
188
- spans.push(span);
189
- return span;
190
- },
191
- });
192
- const request = HttpServerRequest.fromWeb(
193
- new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
194
- headers: {
195
- traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
196
- },
197
- }),
198
- );
199
-
200
- yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
201
- Effect.provideService(HttpServerRequest.HttpServerRequest, request),
202
- Effect.provideService(RelayClientTracer, Option.some(productTracer)),
203
- );
204
-
205
- expect(spans).toHaveLength(1);
206
- const span = spans[0]!;
207
- expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
208
- expect(Option.isNone(span.parent)).toBe(true);
209
- }),
210
- );
211
-
212
- it.effect("continues an authenticated relay trace with the product tracer", () =>
213
- Effect.gen(function* () {
214
- const spans: Array<Tracer.Span> = [];
215
- const productTracer = Tracer.make({
216
- span: (options) => {
217
- const span = new Tracer.NativeSpan(options);
218
- spans.push(span);
219
- return span;
220
- },
221
- });
222
- const request = HttpServerRequest.fromWeb(
223
- new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
224
- headers: {
225
- traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
226
- },
227
- }),
228
- );
229
-
230
- yield* traceAuthenticatedRelayRequest(
231
- Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
232
- ).pipe(
233
- Effect.provideService(HttpServerRequest.HttpServerRequest, request),
234
- Effect.provideService(RelayClientTracer, Option.some(productTracer)),
235
- );
236
-
237
- expect(spans).toHaveLength(1);
238
- const span = spans[0]!;
239
- expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
240
- expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
241
- }),
242
- );
243
-});
244
-
106
describe("reconcileDesiredCloudLink", () => {
107
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
108
Effect.gen(function* () {
248
- const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
109
+ const link = yield* CloudLink.CloudLink;
110
+ const error = yield* Effect.flip(link.reconcileDesiredLink("http://127.0.0.1:3774"));
111
112
expect(error).toMatchObject({
113
_tag: "EnvironmentHttpUnauthorizedError",
@@ -303,39 +165,6 @@ describe("reconcileDesiredCloudLink", () => {
165
);
166
});
167
306
-describe("parseManagedEndpointLocalOrigin", () => {
307
- it.each([
308
- {
309
- input: "http://127.0.0.1:80",
310
- httpBaseUrl: "http://127.0.0.1",
311
- wsBaseUrl: "ws://127.0.0.1",
312
- port: 80,
313
- },
314
- {
315
- input: "https://127.0.0.1:443",
316
- httpBaseUrl: "https://127.0.0.1",
317
- wsBaseUrl: "wss://127.0.0.1",
318
- port: 443,
319
- },
320
- ])("accepts an explicit default port in $input", ({ input, httpBaseUrl, wsBaseUrl, port }) => {
321
- expect(parseManagedEndpointLocalOrigin(input)).toEqual({
322
- httpBaseUrl,
323
- wsBaseUrl,
324
- origin: { localHttpHost: "127.0.0.1", localHttpPort: port },
325
- });
326
- });
327
-
328
- it.each([
329
- "ftp://127.0.0.1:3773",
330
- "http://user:password@127.0.0.1:3773",
331
- "http://127.0.0.1:3773/api",
332
- "http://127.0.0.1:3773?mode=test",
333
- "http://127.0.0.1:3773#fragment",
334
- ])("rejects non-origin URL %s", (input) => {
335
- expect(() => parseManagedEndpointLocalOrigin(input)).toThrow("Invalid local origin");
336
- });
337
-});
338
-
168
describe("releaseManagedTunnelOnShutdown", () => {
169
const cliToken: CliTokenManager.PersistedToken = {
170
accessToken: "cli-access-token",
@@ -496,11 +325,12 @@ describe("releaseManagedTunnelOnShutdown", () => {
325
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
326
327
return Effect.gen(function* () {
328
+ const link = yield* CloudLink.CloudLink;
329
// Registration started while this marker existed. Unlink removes it
330
// before startup receives the relay's final not_linked response.
331
values.delete(CLOUD_CLI_DESIRED_LINK_SECRET);
332
503
- expect(yield* reconcileDesiredCloudLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
333
+ expect(yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
334
expect(requests).toEqual([]);
335
expect(applyConfigCalls).toEqual([]);
336
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
@@ -512,7 +342,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
342
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
343
344
return Effect.gen(function* () {
515
- const released = yield* releaseManagedTunnelOnShutdown();
345
+ const link = yield* CloudLink.CloudLink;
346
+ const released = yield* link.releaseManagedTunnelOnShutdown();
347
348
expect(released).toBe(true);
349
expect(applyConfigCalls).toEqual([null]);
@@ -534,7 +365,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
365
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
366
367
return Effect.gen(function* () {
537
- const released = yield* releaseManagedTunnelOnShutdown();
368
+ const link = yield* CloudLink.CloudLink;
369
+ const released = yield* link.releaseManagedTunnelOnShutdown();
370
371
expect(released).toBe(false);
372
expect(applyConfigCalls).toEqual([]);
@@ -554,7 +386,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
386
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
387
388
return Effect.gen(function* () {
557
- const released = yield* releaseManagedTunnelOnShutdown();
389
+ const link = yield* CloudLink.CloudLink;
390
+ const released = yield* link.releaseManagedTunnelOnShutdown();
391
392
expect(released).toBe(false);
393
expect(applyConfigCalls).toEqual([]);
@@ -573,7 +406,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
406
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
407
408
return Effect.gen(function* () {
576
- const released = yield* releaseManagedTunnelOnShutdown();
409
+ const link = yield* CloudLink.CloudLink;
410
+ const released = yield* link.releaseManagedTunnelOnShutdown();
411
412
expect(released).toBe(false);
413
expect(applyConfigCalls).toEqual([]);
@@ -588,6 +422,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
422
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
423
424
return Effect.gen(function* () {
425
+ const link = yield* CloudLink.CloudLink;
426
yield* writeLauncherState({
427
id: "update-1",
428
fromVersion: "0.0.30",
@@ -596,7 +431,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
431
status: "pending",
432
});
433
599
- const released = yield* releaseManagedTunnelOnShutdown();
434
+ const released = yield* link.releaseManagedTunnelOnShutdown();
435
436
// The launcher restarts a server immediately, so the tunnel is not
437
// orphaned; keeping it avoids the hostname route re-propagation that
@@ -615,14 +450,15 @@ describe("releaseManagedTunnelOnShutdown", () => {
450
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
451
452
return Effect.gen(function* () {
453
+ const link = yield* CloudLink.CloudLink;
454
yield* TestClock.setTime(yield* writeDesktopUpdateRestartMarker);
455
620
- expect(yield* releaseManagedTunnelOnShutdown()).toBe(false);
456
+ expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(false);
457
expect(requests).toEqual([]);
458
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
459
460
// The shutdown consumed the marker, so a later quit releases the tunnel.
625
- expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
461
+ expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(true);
462
expect(requests).toHaveLength(1);
463
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
464
});
@@ -633,10 +469,11 @@ describe("releaseManagedTunnelOnShutdown", () => {
469
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
470
471
return Effect.gen(function* () {
472
+ const link = yield* CloudLink.CloudLink;
473
const writtenAt = yield* writeDesktopUpdateRestartMarker;
474
yield* TestClock.setTime(writtenAt + Duration.toMillis(Duration.minutes(2)));
475
639
- expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
476
+ expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(true);
477
expect(requests).toHaveLength(1);
478
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
479
});
@@ -650,6 +487,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
487
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
488
489
return Effect.gen(function* () {
490
+ const link = yield* CloudLink.CloudLink;
491
yield* writeLauncherState({
492
id: "update-1",
493
fromVersion: "0.0.30",
@@ -663,7 +501,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
501
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
502
503
expect(yield* pendingServiceUpdateExists).toBe(true);
666
- const released = yield* releaseManagedTunnelOnShutdown();
504
+ const released = yield* link.releaseManagedTunnelOnShutdown();
505
506
expect(released).toBe(true);
507
expect(requests).toHaveLength(1);
@@ -677,6 +515,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
515
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
516
517
return Effect.gen(function* () {
518
+ const link = yield* CloudLink.CloudLink;
519
yield* writeLauncherState({
520
id: "update-1",
521
fromVersion: "0.0.30",
@@ -684,7 +523,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
523
status: "committed",
524
});
525
687
- const released = yield* releaseManagedTunnelOnShutdown();
526
+ const released = yield* link.releaseManagedTunnelOnShutdown();
527
528
expect(released).toBe(true);
529
expect(requests).toHaveLength(1);
@@ -699,7 +538,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
538
const freshConfig = new TextEncoder().encode("fresh-runtime-config");
539
540
return Effect.gen(function* () {
702
- const released = yield* releaseManagedTunnelOnShutdown();
541
+ const link = yield* CloudLink.CloudLink;
542
+ const released = yield* link.releaseManagedTunnelOnShutdown();
543
544
expect(released).toBe(true);
545
// The finalizer only drops the config it released; the one written by
@@ -729,7 +569,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
569
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
570
571
return Effect.gen(function* () {
732
- const released = yield* releaseManagedTunnelOnShutdown();
572
+ const link = yield* CloudLink.CloudLink;
573
+ const released = yield* link.releaseManagedTunnelOnShutdown();
574
575
expect(released).toBe(false);
576
expect(requests).toHaveLength(1);
@@ -750,7 +591,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
591
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
592
593
return Effect.gen(function* () {
753
- const result = yield* Effect.result(releaseManagedTunnelOnShutdown());
594
+ const link = yield* CloudLink.CloudLink;
595
+ const result = yield* Effect.result(link.releaseManagedTunnelOnShutdown());
596
597
expect(result._tag).toBe("Failure");
598
expect(requests).toHaveLength(1);
@@ -781,7 +623,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
623
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
624
625
return Effect.gen(function* () {
784
- expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
626
+ const link = yield* CloudLink.CloudLink;
627
+ expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
628
status: "ready",
629
});
630
expect(requests).toHaveLength(1);
@@ -837,25 +680,28 @@ describe("releaseManagedTunnelOnShutdown", () => {
680
const localOrigin = "http://127.0.0.1:4884";
681
682
return Effect.gen(function* () {
683
+ const link = yield* CloudLink.CloudLink;
684
const fallbackStarted = yield* Deferred.make<void>();
685
const firstFailure = yield* Deferred.make<void>();
842
- expect(yield* startManagedCloudTunnelIfOriginConfirmed(localOrigin)).toBe(false);
686
+ expect(yield* link.startManagedTunnelIfOriginConfirmed(localOrigin)).toBe(false);
687
const registration = yield* Effect.forkChild(
688
retryManagedTunnelRegistration(
845
- registerManagedCloudTunnelRecovery(localOrigin).pipe(
846
- Effect.tapError(() => Deferred.succeed(firstFailure, undefined)),
847
- ),
689
+ link
690
+ .registerManagedTunnelRecovery(localOrigin)
691
+ .pipe(Effect.tapError(() => Deferred.succeed(firstFailure, undefined))),
692
shouldRetryCloudLink,
849
- startManagedCloudTunnelIfOriginConfirmed(localOrigin, {
850
- requireConfirmedOrigin: false,
851
- }).pipe(
852
- Effect.orDie,
853
- Effect.tap((started) => {
854
- expect(started).toBe(true);
855
- return Deferred.succeed(fallbackStarted, undefined);
856
- }),
857
- Effect.asVoid,
858
- ),
693
+ link
694
+ .startManagedTunnelIfOriginConfirmed(localOrigin, {
695
+ requireConfirmedOrigin: false,
696
+ })
697
+ .pipe(
698
+ Effect.orDie,
699
+ Effect.tap((started) => {
700
+ expect(started).toBe(true);
701
+ return Deferred.succeed(fallbackStarted, undefined);
702
+ }),
703
+ Effect.asVoid,
704
+ ),
705
),
706
{ startImmediately: true },
707
);
@@ -918,7 +764,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
764
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
765
766
return Effect.gen(function* () {
921
- expect(yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
767
+ const link = yield* CloudLink.CloudLink;
768
+ expect(yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
769
expect(applyConfigCalls).toEqual([config]);
770
expect(requests).toEqual([]);
771
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
@@ -946,7 +793,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
793
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
794
795
return Effect.gen(function* () {
949
- expect(yield* startManagedCloudTunnelIfOriginConfirmed(origin)).toBe(false);
796
+ const link = yield* CloudLink.CloudLink;
797
+ expect(yield* link.startManagedTunnelIfOriginConfirmed(origin)).toBe(false);
798
expect(applyConfigCalls).toEqual([]);
799
expect(requests).toEqual([]);
800
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
@@ -967,8 +815,9 @@ describe("releaseManagedTunnelOnShutdown", () => {
815
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
816
817
return Effect.gen(function* () {
818
+ const link = yield* CloudLink.CloudLink;
819
expect(
971
- yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
820
+ yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
821
requireConfirmedOrigin: false,
822
}),
823
).toBe(true);
@@ -993,7 +842,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
842
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
843
844
return Effect.gen(function* () {
996
- expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toEqual({
845
+ const link = yield* CloudLink.CloudLink;
846
+ expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({
847
status: "superseded",
848
});
849
expect(applyConfigCalls).toEqual([]);
@@ -1035,7 +885,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
885
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
886
887
return Effect.gen(function* () {
1038
- const registration = yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773");
888
+ const link = yield* CloudLink.CloudLink;
889
+ const registration = yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773");
890
expect(registration).toEqual({
891
status: "recovery_required",
892
config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
@@ -1072,7 +923,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
923
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
924
925
return Effect.gen(function* () {
1075
- expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(true);
926
+ const link = yield* CloudLink.CloudLink;
927
+ expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(true);
928
expect(requests).toHaveLength(1);
929
expect(requests[0]?.method).toBe("POST");
930
expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel");
@@ -1120,7 +972,9 @@ describe("releaseManagedTunnelOnShutdown", () => {
972
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
973
const requestStarted = yield* Deferred.make<void>();
974
const response = yield* Deferred.make<Response>();
1123
- const recovery = yield* recoverManagedCloudTunnel("http://127.0.0.1:3773").pipe(
975
+ const recovery = yield* CloudLink.CloudLink.use((link) =>
976
+ link.recoverManagedTunnel("http://127.0.0.1:3773"),
977
+ ).pipe(
978
provideReleaseHarness({
979
store,
980
applyConfigCalls,
@@ -1162,7 +1016,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
1016
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1017
1018
return Effect.gen(function* () {
1165
- expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1019
+ const link = yield* CloudLink.CloudLink;
1020
+ expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
1021
expect(applyConfigCalls).toEqual([]);
1022
expect(requests).toEqual([]);
1023
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
@@ -1182,8 +1037,9 @@ describe("releaseManagedTunnelOnShutdown", () => {
1037
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1038
1039
return Effect.gen(function* () {
1040
+ const link = yield* CloudLink.CloudLink;
1041
expect(
1186
- yield* recoverManagedCloudTunnel("http://127.0.0.1:3773", {
1042
+ yield* link.recoverManagedTunnel("http://127.0.0.1:3773", {
1043
providerKind: "cloudflare_tunnel",
1044
connectorToken: "old-token",
1045
tunnelId: "old-tunnel",
@@ -1209,7 +1065,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
1065
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1066
1067
return Effect.gen(function* () {
1212
- const error = yield* Effect.flip(recoverManagedCloudTunnel("http://127.0.0.1:3773"));
1068
+ const link = yield* CloudLink.CloudLink;
1069
+ const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773"));
1070
1071
expect(error._tag).toBe(errorTag);
1072
expect(requests).toHaveLength(1);
@@ -1236,7 +1093,8 @@ describe("releaseManagedTunnelOnShutdown", () => {
1093
const freshConfig = new TextEncoder().encode("fresh-config");
1094
1095
return Effect.gen(function* () {
1239
- expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1096
+ const link = yield* CloudLink.CloudLink;
1097
+ expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
1098
expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
1099
expect(applyConfigCalls).toEqual([]);
1100
}).pipe(
@@ -1262,32 +1120,3 @@ describe("releaseManagedTunnelOnShutdown", () => {
1120
);
1121
});
1122
});
1265
-
1266
-describe("link proof provider kinds", () => {
1267
- const proofRequest = (
1268
- providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
1269
- ): RelayLinkProofRequest => ({
1270
- challenge: "challenge",
1271
- relayIssuer: "https://relay.example.test",
1272
- endpoint: {
1273
- httpBaseUrl: "http://127.0.0.1:7331",
1274
- wsBaseUrl: "ws://127.0.0.1:7331",
1275
- providerKind,
1276
- },
1277
- origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
1278
- });
1279
-
1280
- it("accepts managed and manual endpoints but not t3_relay", () => {
1281
- expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
1282
- expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
1283
- expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
1284
- });
1285
-
1286
- it("only claims the managed-tunnel scope for tunnel links", () => {
1287
- expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
1288
- "agent_activity_notifications",
1289
- "managed_tunnels",
1290
- ]);
1291
- expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
1292
- });
1293
-});
apps/server/src/cloud/CloudLink.ts
+18
-233
@@ -7,7 +7,6 @@
7
import * as NodeCrypto from "node:crypto";
8
import {
9
AuthStandardClientScopes,
10
- DESKTOP_UPDATE_RESTART_MARKER_FILE,
10
EnvironmentCloudEndpointUnavailableError,
11
type EnvironmentCloudLinkStateResult,
12
type EnvironmentCloudPreferencesRequest,
@@ -53,7 +52,6 @@ import {
52
verifyRelayJwt,
53
} from "@t3tools/shared/relayJwt";
54
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
56
-import * as Clock from "effect/Clock";
55
import * as Context from "effect/Context";
56
import * as Crypto from "effect/Crypto";
57
import * as DateTime from "effect/DateTime";
@@ -110,29 +108,24 @@ import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
108
import { relayUrlConfig } from "./publicConfig.ts";
109
import { filterRelayResponse, relayRequestError, shouldRetryCloudLink } from "./relayResponse.ts";
110
import {
113
- SERVICE_STATE_FILE,
114
- SERVICE_STOP_MARKER_FILE,
115
- serviceStateHasPendingUpdate,
116
-} from "./serviceProtocol.ts";
117
-
118
-const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
119
-const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";
120
-const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";
121
-const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";
122
-/** Secret store name prefixes of cloud replay markers. The server prunes expired ones. */
123
-export const CLOUD_REPLAY_MARKER_PREFIXES = [
124
- CLOUD_MINT_NONCE_PREFIX,
125
- CLOUD_MINT_JTI_PREFIX,
126
- CLOUD_HEALTH_NONCE_PREFIX,
111
CLOUD_HEALTH_JTI_PREFIX,
128
-] as const;
129
-const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;
130
-const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;
131
-// The desktop app stops its backends within seconds of writing the marker.
132
-const DESKTOP_UPDATE_RESTART_MARKER_TTL = Duration.minutes(1);
133
-const MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT = Duration.minutes(2);
134
-const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
112
+ CLOUD_HEALTH_NONCE_PREFIX,
113
+ CLOUD_MINT_JTI_PREFIX,
114
+ CLOUD_MINT_NONCE_PREFIX,
115
+ consumeCloudReplayGuards,
116
+ hasBoundedCloudProofLifetime,
117
+ hasExactScope,
118
+ hasForwardedAuthorityHeaders,
119
+ isAllowedEndpointOrigin,
120
+ isSupportedLinkProviderKind,
121
+ linkProofScopes,
122
+ managedEndpointRuntimeConfigsMatch,
123
+ parseManagedEndpointLocalOrigin,
124
+ requestAbsoluteUrl,
125
+} from "./linkChecks.ts";
126
+import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
127
128
+const MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT = Duration.minutes(2);
129
const failEnvironmentCloudInternalError =
130
(message: string) =>
131
(cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>
@@ -164,37 +157,6 @@ function stringToBytes(value: string): Uint8Array {
157
return new TextEncoder().encode(value);
158
}
159
167
-export function consumeCloudReplayGuards(input: {
168
- readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
169
- readonly names: ReadonlyArray<string>;
170
- readonly value: Uint8Array;
171
-}) {
172
- return Effect.forEach(
173
- input.names,
174
- (name) =>
175
- input.secrets.create(name, input.value).pipe(
176
- Effect.as(true),
177
- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
178
- ServerSecretStore.isSecretAlreadyExistsError(error)
179
- ? Effect.succeed(false)
180
- : Effect.fail(error),
181
- ),
182
- ),
183
- { concurrency: input.names.length },
184
- ).pipe(Effect.map((created) => created.every(Boolean)));
185
-}
186
-
187
-function normalizePemForSignedPayload(value: string): string {
188
- return value.trim();
189
-}
190
-
191
-function normalizeHostname(hostname: string): string {
192
- return hostname
193
- .trim()
194
- .toLowerCase()
195
- .replace(/^\[(.*)\]$/, "$1");
196
-}
197
-
160
function validateCloudMintPublicKey(
161
publicKey: string,
162
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
@@ -251,190 +213,13 @@ function validateRelayConfigPayload(
213
return Effect.void;
214
}
215
254
-function isLoopbackHostname(hostname: string): boolean {
255
- return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
256
-}
257
-
258
-function firstForwardedHeaderValue(value: string | undefined): string | undefined {
259
- const first = value?.split(",")[0]?.trim();
260
- return first && first.length > 0 ? first : undefined;
261
-}
262
-
263
-function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {
264
- try {
265
- return new URL(request.originalUrl).href;
266
- } catch {
267
- const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";
268
- try {
269
- return new URL(request.originalUrl, `http://${host}`).href;
270
- } catch {
271
- return null;
272
- }
273
- }
274
-}
275
-
276
-function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean {
277
- return (
278
- firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||
279
- firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined
280
- );
281
-}
282
-
283
-function endpointRequestPort(url: URL): number {
284
- return Number(url.port || (url.protocol === "https:" ? 443 : 80));
285
-}
286
-
287
-export function parseManagedEndpointLocalOrigin(localOrigin: string) {
288
- const url = new URL(localOrigin);
289
- if (
290
- localOrigin !== localOrigin.trim() ||
291
- (url.protocol !== "http:" && url.protocol !== "https:") ||
292
- url.username !== "" ||
293
- url.password !== "" ||
294
- url.pathname !== "/" ||
295
- url.search !== "" ||
296
- url.hash !== "" ||
297
- localOrigin.includes("?") ||
298
- localOrigin.includes("#")
299
- ) {
300
- throw new Error("Invalid local origin");
301
- }
302
- const wsUrl = new URL(url.origin);
303
- wsUrl.protocol = url.protocol === "https:" ? "wss:" : "ws:";
304
- return {
305
- httpBaseUrl: url.origin,
306
- wsBaseUrl: wsUrl.origin,
307
- origin: {
308
- localHttpHost: url.hostname,
309
- localHttpPort: endpointRequestPort(url),
310
- } satisfies RelayManagedEndpointOrigin,
311
- };
312
-}
313
-
314
-function isAllowedEndpointOrigin(input: {
315
- readonly origin: RelayManagedEndpointOrigin;
316
- readonly requestUrl: string;
317
-}): boolean {
318
- if (!isLoopbackHostname(input.origin.localHttpHost)) {
319
- return false;
320
- }
321
-
322
- const url = new URL(input.requestUrl);
323
- if (!isLoopbackHostname(url.hostname)) {
324
- return false;
325
- }
326
-
327
- return input.origin.localHttpPort === endpointRequestPort(url);
328
-}
329
-
330
-// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must
331
-// point at a loopback origin. A manual endpoint is reached out of band (e.g.
332
-// Tailscale) or not advertised at all for publish-only links, so it is not
333
-// tied to the managed-tunnel scope.
334
-export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
335
- return (
336
- request.endpoint.providerKind === "cloudflare_tunnel" ||
337
- request.endpoint.providerKind === "manual"
338
- );
339
-}
340
-
341
-export function linkProofScopes(
342
- request: RelayLinkProofRequest,
343
-): RelayEnvironmentLinkProofPayload["scopes"] {
344
- return request.endpoint.providerKind === "cloudflare_tunnel"
345
- ? ["agent_activity_notifications", "managed_tunnels"]
346
- : ["agent_activity_notifications"];
347
-}
348
-
349
-function hasExactScope(input: {
350
- readonly scopes: ReadonlyArray<string>;
351
- readonly expected: string;
352
-}): boolean {
353
- return input.scopes.length === 1 && input.scopes[0] === input.expected;
354
-}
355
-
356
-function hasBoundedCloudProofLifetime(input: {
357
- readonly iat: number;
358
- readonly exp: number;
359
- readonly nowSeconds: number;
360
-}): boolean {
361
- return (
362
- input.exp > input.iat &&
363
- input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&
364
- input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS
365
- );
366
-}
367
-
368
-function managedEndpointRuntimeConfigsMatch(
369
- left: RelayManagedEndpointRuntimeConfig,
370
- right: RelayManagedEndpointRuntimeConfig,
371
-): boolean {
372
- return (
373
- left.providerKind === right.providerKind &&
374
- left.connectorToken === right.connectorToken &&
375
- left.tunnelId === right.tunnelId &&
376
- left.tunnelName === right.tunnelName
377
- );
216
+function normalizePemForSignedPayload(value: string): string {
217
+ return value.trim();
218
}
219
220
const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
221
const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
222
383
-// The launcher owns this durable state, so read it directly both when a trial
384
-// decides whether it owns pre-activation cleanup and while a server tears down.
385
-export const pendingServiceUpdateExists = Effect.gen(function* () {
386
- const config = yield* ServerConfig.ServerConfig;
387
- const fs = yield* FileSystem.FileSystem;
388
- const path = yield* Path.Path;
389
- const runtimeDir = path.join(config.baseDir, "runtime");
390
- const stateText = yield* fs
391
- .readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
392
- .pipe(Effect.option);
393
- return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
394
-});
395
-
396
-// A pending update alone is not proof a replacement server is coming: an
397
-// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
398
-// `launchctl bootout`) during
399
-// the pending window also tears this server down. The launcher marks that case
400
-// just before it signals the child, so pending + no marker is the handoff.
401
-const pendingUpdateHandoffExists = Effect.gen(function* () {
402
- if (!(yield* pendingServiceUpdateExists)) {
403
- return false;
404
- }
405
- const config = yield* ServerConfig.ServerConfig;
406
- const fs = yield* FileSystem.FileSystem;
407
- const path = yield* Path.Path;
408
- const runtimeDir = path.join(config.baseDir, "runtime");
409
- const stopping = yield* fs
410
- .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
411
- .pipe(Effect.orElseSucceed(() => false));
412
- return !stopping;
413
-});
414
-
415
-// The desktop app writes its marker right before it stops this server to
416
-// install an update, whether a remote client or the local app started it.
417
-// Reading consumes it, so shutdown checks it first. Only a fresh marker counts,
418
-// so a marker the server never read (a hard kill) cannot keep the tunnel on a
419
-// later quit.
420
-const desktopUpdateRestartPending = Effect.gen(function* () {
421
- const config = yield* ServerConfig.ServerConfig;
422
- const fs = yield* FileSystem.FileSystem;
423
- const path = yield* Path.Path;
424
- const markerPath = path.join(config.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
425
- const marker = yield* fs.stat(markerPath).pipe(Effect.option);
426
- if (Option.isNone(marker)) {
427
- return false;
428
- }
429
- yield* fs.remove(markerPath).pipe(Effect.ignore);
430
- const now = yield* Clock.currentTimeMillis;
431
- return Option.match(marker.value.mtime, {
432
- onNone: () => false,
433
- onSome: (writtenAt) =>
434
- now - writtenAt.getTime() < Duration.toMillis(DESKTOP_UPDATE_RESTART_MARKER_TTL),
435
- });
436
-});
437
-
223
type ManagedTunnelRecoveryProofInput = {
224
readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"];
225
readonly cloudUserId: string;
apps/server/src/cloud/linkChecks.test.ts
new
+128
@@ -0,0 +1,128 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as PlatformError from "effect/PlatformError";
4
+import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
5
+
6
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
7
+import {
8
+ consumeCloudReplayGuards,
9
+ isSupportedLinkProviderKind,
10
+ linkProofScopes,
11
+ parseManagedEndpointLocalOrigin,
12
+} from "./linkChecks.ts";
13
+
14
+const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
15
+ new ServerSecretStore.SecretStorePersistError({
16
+ resource: "cloud replay guard",
17
+ cause: PlatformError.systemError({
18
+ _tag: tag,
19
+ module: "FileSystem",
20
+ method: "open",
21
+ pathOrDescriptor: "cloud-replay-guard.bin",
22
+ }),
23
+ });
24
+
25
+const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
26
+
27
+function makeSecretStore(
28
+ create: ServerSecretStore.ServerSecretStore["Service"]["create"],
29
+): ServerSecretStore.ServerSecretStore["Service"] {
30
+ return {
31
+ get: unusedSecretStoreOperation,
32
+ set: unusedSecretStoreOperation,
33
+ create,
34
+ getOrCreateRandom: unusedSecretStoreOperation,
35
+ remove: unusedSecretStoreOperation,
36
+ };
37
+}
38
+
39
+describe("consumeCloudReplayGuards", () => {
40
+ it.effect("reports already-created guards as replay conflicts", () =>
41
+ Effect.gen(function* () {
42
+ const consumed = yield* consumeCloudReplayGuards({
43
+ secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
44
+ names: ["cloud-jti", "cloud-nonce"],
45
+ value: new Uint8Array(),
46
+ });
47
+
48
+ expect(consumed).toBe(false);
49
+ }),
50
+ );
51
+
52
+ it.effect("preserves replay-store availability failures", () =>
53
+ Effect.gen(function* () {
54
+ const failure = storeFailure("PermissionDenied");
55
+ const error = yield* Effect.flip(
56
+ consumeCloudReplayGuards({
57
+ secrets: makeSecretStore(() => Effect.fail(failure)),
58
+ names: ["cloud-jti", "cloud-nonce"],
59
+ value: new Uint8Array(),
60
+ }),
61
+ );
62
+
63
+ expect(error).toBe(failure);
64
+ }),
65
+ );
66
+});
67
+
68
+describe("parseManagedEndpointLocalOrigin", () => {
69
+ it.each([
70
+ {
71
+ input: "http://127.0.0.1:80",
72
+ httpBaseUrl: "http://127.0.0.1",
73
+ wsBaseUrl: "ws://127.0.0.1",
74
+ port: 80,
75
+ },
76
+ {
77
+ input: "https://127.0.0.1:443",
78
+ httpBaseUrl: "https://127.0.0.1",
79
+ wsBaseUrl: "wss://127.0.0.1",
80
+ port: 443,
81
+ },
82
+ ])("accepts an explicit default port in $input", ({ input, httpBaseUrl, wsBaseUrl, port }) => {
83
+ expect(parseManagedEndpointLocalOrigin(input)).toEqual({
84
+ httpBaseUrl,
85
+ wsBaseUrl,
86
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: port },
87
+ });
88
+ });
89
+
90
+ it.each([
91
+ "ftp://127.0.0.1:3773",
92
+ "http://user:password@127.0.0.1:3773",
93
+ "http://127.0.0.1:3773/api",
94
+ "http://127.0.0.1:3773?mode=test",
95
+ "http://127.0.0.1:3773#fragment",
96
+ ])("rejects non-origin URL %s", (input) => {
97
+ expect(() => parseManagedEndpointLocalOrigin(input)).toThrow("Invalid local origin");
98
+ });
99
+});
100
+
101
+describe("link proof provider kinds", () => {
102
+ const proofRequest = (
103
+ providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
104
+ ): RelayLinkProofRequest => ({
105
+ challenge: "challenge",
106
+ relayIssuer: "https://relay.example.test",
107
+ endpoint: {
108
+ httpBaseUrl: "http://127.0.0.1:7331",
109
+ wsBaseUrl: "ws://127.0.0.1:7331",
110
+ providerKind,
111
+ },
112
+ origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
113
+ });
114
+
115
+ it("accepts managed and manual endpoints but not t3_relay", () => {
116
+ expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
117
+ expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
118
+ expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
119
+ });
120
+
121
+ it("only claims the managed-tunnel scope for tunnel links", () => {
122
+ expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
123
+ "agent_activity_notifications",
124
+ "managed_tunnels",
125
+ ]);
126
+ expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
127
+ });
128
+});
apps/server/src/cloud/linkChecks.ts
new
+185
@@ -0,0 +1,185 @@
1
+/**
2
+ * Pure checks behind T3 Connect link proofs and relay requests: which local
3
+ * origin a link may point at, which scopes a proof claims and accepts, and the
4
+ * one-shot replay guards for signed relay requests.
5
+ */
6
+import type {
7
+ RelayEnvironmentLinkProofPayload,
8
+ RelayLinkProofRequest,
9
+ RelayManagedEndpointOrigin,
10
+ RelayManagedEndpointRuntimeConfig,
11
+} from "@t3tools/contracts/relay";
12
+import * as Effect from "effect/Effect";
13
+import type { HttpServerRequest } from "effect/http";
14
+
15
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16
+
17
+export const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
18
+export const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";
19
+export const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";
20
+export const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";
21
+/** Secret store name prefixes of cloud replay markers. The server prunes expired ones. */
22
+export const CLOUD_REPLAY_MARKER_PREFIXES = [
23
+ CLOUD_MINT_NONCE_PREFIX,
24
+ CLOUD_MINT_JTI_PREFIX,
25
+ CLOUD_HEALTH_NONCE_PREFIX,
26
+ CLOUD_HEALTH_JTI_PREFIX,
27
+] as const;
28
+const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;
29
+const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;
30
+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
31
+
32
+export function consumeCloudReplayGuards(input: {
33
+ readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
34
+ readonly names: ReadonlyArray<string>;
35
+ readonly value: Uint8Array;
36
+}) {
37
+ return Effect.forEach(
38
+ input.names,
39
+ (name) =>
40
+ input.secrets.create(name, input.value).pipe(
41
+ Effect.as(true),
42
+ Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
43
+ ServerSecretStore.isSecretAlreadyExistsError(error)
44
+ ? Effect.succeed(false)
45
+ : Effect.fail(error),
46
+ ),
47
+ ),
48
+ { concurrency: input.names.length },
49
+ ).pipe(Effect.map((created) => created.every(Boolean)));
50
+}
51
+
52
+function normalizeHostname(hostname: string): string {
53
+ return hostname
54
+ .trim()
55
+ .toLowerCase()
56
+ .replace(/^\[(.*)\]$/, "$1");
57
+}
58
+
59
+function isLoopbackHostname(hostname: string): boolean {
60
+ return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));
61
+}
62
+
63
+function firstForwardedHeaderValue(value: string | undefined): string | undefined {
64
+ const first = value?.split(",")[0]?.trim();
65
+ return first && first.length > 0 ? first : undefined;
66
+}
67
+
68
+export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {
69
+ try {
70
+ return new URL(request.originalUrl).href;
71
+ } catch {
72
+ const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";
73
+ try {
74
+ return new URL(request.originalUrl, `http://${host}`).href;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+}
80
+
81
+export function hasForwardedAuthorityHeaders(
82
+ request: HttpServerRequest.HttpServerRequest,
83
+): boolean {
84
+ return (
85
+ firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||
86
+ firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined
87
+ );
88
+}
89
+
90
+function endpointRequestPort(url: URL): number {
91
+ return Number(url.port || (url.protocol === "https:" ? 443 : 80));
92
+}
93
+
94
+export function parseManagedEndpointLocalOrigin(localOrigin: string) {
95
+ const url = new URL(localOrigin);
96
+ if (
97
+ localOrigin !== localOrigin.trim() ||
98
+ (url.protocol !== "http:" && url.protocol !== "https:") ||
99
+ url.username !== "" ||
100
+ url.password !== "" ||
101
+ url.pathname !== "/" ||
102
+ url.search !== "" ||
103
+ url.hash !== "" ||
104
+ localOrigin.includes("?") ||
105
+ localOrigin.includes("#")
106
+ ) {
107
+ throw new Error("Invalid local origin");
108
+ }
109
+ const wsUrl = new URL(url.origin);
110
+ wsUrl.protocol = url.protocol === "https:" ? "wss:" : "ws:";
111
+ return {
112
+ httpBaseUrl: url.origin,
113
+ wsBaseUrl: wsUrl.origin,
114
+ origin: {
115
+ localHttpHost: url.hostname,
116
+ localHttpPort: endpointRequestPort(url),
117
+ } satisfies RelayManagedEndpointOrigin,
118
+ };
119
+}
120
+
121
+export function isAllowedEndpointOrigin(input: {
122
+ readonly origin: RelayManagedEndpointOrigin;
123
+ readonly requestUrl: string;
124
+}): boolean {
125
+ if (!isLoopbackHostname(input.origin.localHttpHost)) {
126
+ return false;
127
+ }
128
+
129
+ const url = new URL(input.requestUrl);
130
+ if (!isLoopbackHostname(url.hostname)) {
131
+ return false;
132
+ }
133
+
134
+ return input.origin.localHttpPort === endpointRequestPort(url);
135
+}
136
+
137
+// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must
138
+// point at a loopback origin. A manual endpoint is reached out of band (e.g.
139
+// Tailscale) or not advertised at all for publish-only links, so it is not
140
+// tied to the managed-tunnel scope.
141
+export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {
142
+ return (
143
+ request.endpoint.providerKind === "cloudflare_tunnel" ||
144
+ request.endpoint.providerKind === "manual"
145
+ );
146
+}
147
+
148
+export function linkProofScopes(
149
+ request: RelayLinkProofRequest,
150
+): RelayEnvironmentLinkProofPayload["scopes"] {
151
+ return request.endpoint.providerKind === "cloudflare_tunnel"
152
+ ? ["agent_activity_notifications", "managed_tunnels"]
153
+ : ["agent_activity_notifications"];
154
+}
155
+
156
+export function hasExactScope(input: {
157
+ readonly scopes: ReadonlyArray<string>;
158
+ readonly expected: string;
159
+}): boolean {
160
+ return input.scopes.length === 1 && input.scopes[0] === input.expected;
161
+}
162
+
163
+export function hasBoundedCloudProofLifetime(input: {
164
+ readonly iat: number;
165
+ readonly exp: number;
166
+ readonly nowSeconds: number;
167
+}): boolean {
168
+ return (
169
+ input.exp > input.iat &&
170
+ input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&
171
+ input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS
172
+ );
173
+}
174
+
175
+export function managedEndpointRuntimeConfigsMatch(
176
+ left: RelayManagedEndpointRuntimeConfig,
177
+ right: RelayManagedEndpointRuntimeConfig,
178
+): boolean {
179
+ return (
180
+ left.providerKind === right.providerKind &&
181
+ left.connectorToken === right.connectorToken &&
182
+ left.tunnelId === right.tunnelId &&
183
+ left.tunnelName === right.tunnelName
184
+ );
185
+}
apps/server/src/cloud/traceRelayRequest.test.ts
new
+72
@@ -0,0 +1,72 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Option from "effect/Option";
4
+import * as Tracer from "effect/Tracer";
5
+import { HttpServerRequest } from "effect/http";
6
+import { RelayClientTracer } from "@t3tools/shared/relayTracing";
7
+
8
+import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
9
+
10
+describe("relay request tracing", () => {
11
+ it.effect("does not accept an unauthenticated request trace parent", () =>
12
+ Effect.gen(function* () {
13
+ const spans: Array<Tracer.Span> = [];
14
+ const productTracer = Tracer.make({
15
+ span: (options) => {
16
+ const span = new Tracer.NativeSpan(options);
17
+ spans.push(span);
18
+ return span;
19
+ },
20
+ });
21
+ const request = HttpServerRequest.fromWeb(
22
+ new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
23
+ headers: {
24
+ traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
25
+ },
26
+ }),
27
+ );
28
+
29
+ yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
30
+ Effect.provideService(HttpServerRequest.HttpServerRequest, request),
31
+ Effect.provideService(RelayClientTracer, Option.some(productTracer)),
32
+ );
33
+
34
+ expect(spans).toHaveLength(1);
35
+ const span = spans[0]!;
36
+ expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
37
+ expect(Option.isNone(span.parent)).toBe(true);
38
+ }),
39
+ );
40
+
41
+ it.effect("continues an authenticated relay trace with the product tracer", () =>
42
+ Effect.gen(function* () {
43
+ const spans: Array<Tracer.Span> = [];
44
+ const productTracer = Tracer.make({
45
+ span: (options) => {
46
+ const span = new Tracer.NativeSpan(options);
47
+ spans.push(span);
48
+ return span;
49
+ },
50
+ });
51
+ const request = HttpServerRequest.fromWeb(
52
+ new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
53
+ headers: {
54
+ traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
55
+ },
56
+ }),
57
+ );
58
+
59
+ yield* traceAuthenticatedRelayRequest(
60
+ Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
61
+ ).pipe(
62
+ Effect.provideService(HttpServerRequest.HttpServerRequest, request),
63
+ Effect.provideService(RelayClientTracer, Option.some(productTracer)),
64
+ );
65
+
66
+ expect(spans).toHaveLength(1);
67
+ const span = spans[0]!;
68
+ expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
69
+ expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
70
+ }),
71
+ );
72
+});
apps/server/src/cloud/updateHandoff.ts
new
+76
@@ -0,0 +1,76 @@
1
+/**
2
+ * Whether this server is going down only to be replaced by an update. Shutdown
3
+ * keeps the managed tunnel across those restarts instead of releasing it.
4
+ */
5
+import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts";
6
+import * as Clock from "effect/Clock";
7
+import * as Duration from "effect/Duration";
8
+import * as Effect from "effect/Effect";
9
+import * as FileSystem from "effect/FileSystem";
10
+import * as Option from "effect/Option";
11
+import * as Path from "effect/Path";
12
+
13
+import * as ServerConfig from "../config.ts";
14
+import {
15
+ SERVICE_STATE_FILE,
16
+ SERVICE_STOP_MARKER_FILE,
17
+ serviceStateHasPendingUpdate,
18
+} from "./serviceProtocol.ts";
19
+
20
+// The desktop app stops its backends within seconds of writing the marker.
21
+const DESKTOP_UPDATE_RESTART_MARKER_TTL = Duration.minutes(1);
22
+
23
+// The launcher owns this durable state, so read it directly both when a trial
24
+// decides whether it owns pre-activation cleanup and while a server tears down.
25
+export const pendingServiceUpdateExists = Effect.gen(function* () {
26
+ const config = yield* ServerConfig.ServerConfig;
27
+ const fs = yield* FileSystem.FileSystem;
28
+ const path = yield* Path.Path;
29
+ const runtimeDir = path.join(config.baseDir, "runtime");
30
+ const stateText = yield* fs
31
+ .readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
32
+ .pipe(Effect.option);
33
+ return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
34
+});
35
+
36
+// A pending update alone is not proof a replacement server is coming: an
37
+// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
38
+// `launchctl bootout`) during
39
+// the pending window also tears this server down. The launcher marks that case
40
+// just before it signals the child, so pending + no marker is the handoff.
41
+export const pendingUpdateHandoffExists = Effect.gen(function* () {
42
+ if (!(yield* pendingServiceUpdateExists)) {
43
+ return false;
44
+ }
45
+ const config = yield* ServerConfig.ServerConfig;
46
+ const fs = yield* FileSystem.FileSystem;
47
+ const path = yield* Path.Path;
48
+ const runtimeDir = path.join(config.baseDir, "runtime");
49
+ const stopping = yield* fs
50
+ .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
51
+ .pipe(Effect.orElseSucceed(() => false));
52
+ return !stopping;
53
+});
54
+
55
+// The desktop app writes its marker right before it stops this server to
56
+// install an update, whether a remote client or the local app started it.
57
+// Reading consumes it, so shutdown checks it first. Only a fresh marker counts,
58
+// so a marker the server never read (a hard kill) cannot keep the tunnel on a
59
+// later quit.
60
+export const desktopUpdateRestartPending = Effect.gen(function* () {
61
+ const config = yield* ServerConfig.ServerConfig;
62
+ const fs = yield* FileSystem.FileSystem;
63
+ const path = yield* Path.Path;
64
+ const markerPath = path.join(config.baseDir, "runtime", DESKTOP_UPDATE_RESTART_MARKER_FILE);
65
+ const marker = yield* fs.stat(markerPath).pipe(Effect.option);
66
+ if (Option.isNone(marker)) {
67
+ return false;
68
+ }
69
+ yield* fs.remove(markerPath).pipe(Effect.ignore);
70
+ const now = yield* Clock.currentTimeMillis;
71
+ return Option.match(marker.value.mtime, {
72
+ onNone: () => false,
73
+ onSome: (writtenAt) =>
74
+ now - writtenAt.getTime() < Duration.toMillis(DESKTOP_UPDATE_RESTART_MARKER_TTL),
75
+ });
76
+});
apps/server/src/server.ts
+2
-1
@@ -124,6 +124,7 @@ import {
124
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
125
import * as CloudHttp from "./cloud/http.ts";
126
import * as CloudLink from "./cloud/CloudLink.ts";
127
+import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts";
128
import * as RelayTracing from "./cloud/relayTracing.ts";
129
import { shouldRetryCloudLink } from "./cloud/relayResponse.ts";
130
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
@@ -813,7 +814,7 @@ const layerMakeServer = Layer.unwrap(
814
// while the launcher's explicit-stop marker allows it to be released.
815
// Other runtimes wait for activation so a failed standby cannot tear
816
// down the active runtime's tunnel.
816
- const cleanupBeforeActivation = yield* CloudLink.pendingServiceUpdateExists;
817
+ const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
818
if (cleanupBeforeActivation) {
819
yield* Effect.addFinalizer(() => releaseManagedTunnel);
820
}